From 161df8a94bb3b0c34ed16fd4fdba078bd1eeef9a Mon Sep 17 00:00:00 2001 From: Patrick Brady Date: Wed, 13 Dec 2017 11:14:21 -0800 Subject: Second part of onap rename This is the second commit of the rename. The folder structure is renamed for appc-adapters and appc-config in this commit. Change-Id: Iaa2b8c937ff1ca1b5d1178128961fb115ee65d9b Signed-off-by: Patrick Brady Issue-ID: APPC-13 --- .../java/org/onap/appc/ccadaptor/CCAActivator.java | 101 ++ .../appc/ccadaptor/ConfigComponentAdaptor.java | 1064 ++++++++++++++++ .../java/org/onap/appc/ccadaptor/DebugLog.java | 102 ++ .../org/onap/appc/ccadaptor/EncryptionTool.java | 214 ++++ .../org/onap/appc/ccadaptor/SshJcraftWrapper.java | 1277 ++++++++++++++++++++ .../org/onap/appc/ccadaptor/TelnetListener.java | 28 + .../org/onap/appc/ccadaptor/TimedOutException.java | 37 + .../main/java/org/onap/appc/ccadaptor/XmlUtil.java | 163 +++ .../org/openecomp/appc/ccadaptor/CCAActivator.java | 101 -- .../appc/ccadaptor/ConfigComponentAdaptor.java | 1064 ---------------- .../org/openecomp/appc/ccadaptor/DebugLog.java | 102 -- .../openecomp/appc/ccadaptor/EncryptionTool.java | 214 ---- .../openecomp/appc/ccadaptor/SshJcraftWrapper.java | 1277 -------------------- .../openecomp/appc/ccadaptor/TelnetListener.java | 28 - .../appc/ccadaptor/TimedOutException.java | 37 - .../java/org/openecomp/appc/ccadaptor/XmlUtil.java | 163 --- .../appc/ccadaptor/TestConfigComponentAdaptor.java | 132 ++ .../test/org/onap/appc/ccadaptor/TestDebugLog.java | 19 + .../onap/appc/ccadaptor/TestEncryptionTool.java | 24 + .../onap/appc/ccadaptor/TestSshJcraftWrapper.java | 23 + .../test/org/onap/appc/ccadaptor/TestXmlUtil.java | 19 + .../appc/ccadaptor/TestConfigComponentAdaptor.java | 132 -- .../org/openecomp/appc/ccadaptor/TestDebugLog.java | 19 - .../appc/ccadaptor/TestEncryptionTool.java | 24 - .../appc/ccadaptor/TestSshJcraftWrapper.java | 23 - .../org/openecomp/appc/ccadaptor/TestXmlUtil.java | 19 - .../appc/ccadaptor/ConfigComponentAdaptorTest.java | 251 ++++ .../java/org/onap/appc/ccadaptor/DebugLogTest.java | 38 + .../onap/appc/ccadaptor/EncryptionToolTest.java | 46 + .../onap/appc/ccadaptor/SshJcraftWrapperTest.java | 105 ++ .../java/org/onap/appc/ccadaptor/XmlUtilTest.java | 42 + .../appc/ccadaptor/ConfigComponentAdaptorTest.java | 251 ---- .../org/openecomp/appc/ccadaptor/DebugLogTest.java | 38 - .../appc/ccadaptor/EncryptionToolTest.java | 46 - .../appc/ccadaptor/SshJcraftWrapperTest.java | 105 -- .../org/openecomp/appc/ccadaptor/XmlUtilTest.java | 42 - .../onap/sdnc/config/audit/SliAuditActivator.java | 62 + .../onap/sdnc/config/audit/SliAuditConstant.java | 64 + .../sdnc/config/audit/node/CompareCliData.java | 43 + .../sdnc/config/audit/node/CompareConstants.java | 43 + .../config/audit/node/CompareDataInterface.java | 27 + .../sdnc/config/audit/node/CompareJsonData.java | 82 ++ .../onap/sdnc/config/audit/node/CompareNode.java | 138 +++ .../sdnc/config/audit/node/CompareXmlData.java | 105 ++ .../onap/sdnc/config/audit/node/Parameters.java | 102 ++ .../sdnc/config/audit/SliAuditActivator.java | 62 - .../sdnc/config/audit/SliAuditConstant.java | 64 - .../sdnc/config/audit/node/CompareCliData.java | 43 - .../sdnc/config/audit/node/CompareConstants.java | 43 - .../config/audit/node/CompareDataInterface.java | 27 - .../sdnc/config/audit/node/CompareJsonData.java | 82 -- .../sdnc/config/audit/node/CompareNode.java | 138 --- .../sdnc/config/audit/node/CompareXmlData.java | 105 -- .../sdnc/config/audit/node/Parameters.java | 102 -- .../sdnc/config/audit/node/TestCompareNodeCli.java | 70 ++ .../config/audit/node/TestCompareNodeJson.java | 63 + .../sdnc/config/audit/node/TestCompareNodeXml.java | 85 ++ .../sdnc/config/audit/node/TestCompareNodeCli.java | 70 -- .../config/audit/node/TestCompareNodeJson.java | 63 - .../sdnc/config/audit/node/TestCompareNodeXml.java | 85 -- .../config/generator/ConfigGeneratorActivator.java | 86 ++ .../config/generator/ConfigGeneratorConstant.java | 68 ++ .../sdnc/config/generator/convert/ConvertNode.java | 189 +++ .../sdnc/config/generator/merge/MergeNode.java | 132 ++ .../sdnc/config/generator/pattern/PatternNode.java | 81 ++ .../sdnc/config/generator/reader/ReaderNode.java | 62 + .../sdnc/config/generator/tool/CheckDataTool.java | 84 ++ .../onap/sdnc/config/generator/tool/Constants.java | 32 + .../generator/tool/CustomJsonNodeFactory.java | 32 + .../sdnc/config/generator/tool/CustomTextNode.java | 50 + .../sdnc/config/generator/tool/DbServiceUtil.java | 75 ++ .../sdnc/config/generator/tool/EscapeUtils.java | 102 ++ .../onap/sdnc/config/generator/tool/JSONTool.java | 157 +++ .../sdnc/config/generator/tool/LogParserTool.java | 94 ++ .../onap/sdnc/config/generator/tool/MergeTool.java | 109 ++ .../generator/transform/XSLTTransformerNode.java | 96 ++ .../config/generator/writer/FileWriterNode.java | 70 ++ .../config/generator/ConfigGeneratorActivator.java | 86 -- .../config/generator/ConfigGeneratorConstant.java | 68 -- .../sdnc/config/generator/convert/ConvertNode.java | 189 --- .../sdnc/config/generator/merge/MergeNode.java | 132 -- .../sdnc/config/generator/pattern/PatternNode.java | 81 -- .../sdnc/config/generator/reader/ReaderNode.java | 62 - .../sdnc/config/generator/tool/CheckDataTool.java | 84 -- .../sdnc/config/generator/tool/Constants.java | 32 - .../generator/tool/CustomJsonNodeFactory.java | 32 - .../sdnc/config/generator/tool/CustomTextNode.java | 50 - .../sdnc/config/generator/tool/DbServiceUtil.java | 75 -- .../sdnc/config/generator/tool/EscapeUtils.java | 102 -- .../sdnc/config/generator/tool/JSONTool.java | 157 --- .../sdnc/config/generator/tool/LogParserTool.java | 94 -- .../sdnc/config/generator/tool/MergeTool.java | 109 -- .../generator/transform/XSLTTransformerNode.java | 96 -- .../config/generator/writer/FileWriterNode.java | 70 -- .../config/generator/convert/TestConvertNode.java | 146 +++ .../sdnc/config/generator/merge/TestMergeNode.java | 103 ++ .../config/generator/pattern/TestPatternNode.java | 81 ++ .../config/generator/reader/TestReaderNode.java | 49 + .../sdnc/config/generator/tool/TestDataTool.java | 153 +++ .../transform/TestXSLTTransformerNode.java | 56 + .../generator/writer/TestFileWriterNode.java | 45 + .../config/generator/convert/TestConvertNode.java | 146 --- .../sdnc/config/generator/merge/TestMergeNode.java | 103 -- .../config/generator/pattern/TestPatternNode.java | 81 -- .../config/generator/reader/TestReaderNode.java | 49 - .../sdnc/config/generator/tool/TestDataTool.java | 153 --- .../transform/TestXSLTTransformerNode.java | 56 - .../generator/writer/TestFileWriterNode.java | 45 - .../sdnc/config/params/ParamsHandlerActivator.java | 70 ++ .../sdnc/config/params/ParamsHandlerConstant.java | 55 + .../onap/sdnc/config/params/data/Parameter.java | 126 ++ .../config/params/data/PropertyDefinition.java | 56 + .../onap/sdnc/config/params/data/RequestKey.java | 51 + .../onap/sdnc/config/params/data/ResponseKey.java | 57 + .../params/parser/PropertyDefinitionNode.java | 251 ++++ .../params/transformer/ArtificatTransformer.java | 87 ++ .../transformer/tosca/ArtifactProcessor.java | 68 ++ .../tosca/ArtifactProcessorFactory.java | 43 + .../transformer/tosca/ArtifactProcessorImpl.java | 401 ++++++ .../exceptions/ArtifactProcessorException.java | 48 + .../sdnc/config/params/ParamsHandlerActivator.java | 70 -- .../sdnc/config/params/ParamsHandlerConstant.java | 55 - .../sdnc/config/params/data/Parameter.java | 126 -- .../config/params/data/PropertyDefinition.java | 56 - .../sdnc/config/params/data/RequestKey.java | 51 - .../sdnc/config/params/data/ResponseKey.java | 57 - .../params/parser/PropertyDefinitionNode.java | 251 ---- .../params/transformer/ArtificatTransformer.java | 87 -- .../transformer/tosca/ArtifactProcessor.java | 68 -- .../tosca/ArtifactProcessorFactory.java | 43 - .../transformer/tosca/ArtifactProcessorImpl.java | 401 ------ .../exceptions/ArtifactProcessorException.java | 48 - .../params/parser/TestPropertyDefinitionNode.java | 116 ++ .../transformer/tosca/TestArtifactProcessor.java | 105 ++ .../tosca/TestGenerateArtifactObject.java | 254 ++++ .../tosca/TestGenerateArtifactString.java | 155 +++ .../transformer/tosca/TestPropertyQueryString.java | 171 +++ .../params/transformer/tosca/TestReadArtifact.java | 103 ++ .../params/parser/TestPropertyDefinitionNode.java | 116 -- .../transformer/tosca/TestArtifactProcessor.java | 105 -- .../tosca/TestGenerateArtifactObject.java | 254 ---- .../tosca/TestGenerateArtifactString.java | 155 --- .../transformer/tosca/TestPropertyQueryString.java | 171 --- .../params/transformer/tosca/TestReadArtifact.java | 103 -- .../data/services/AppcDataServiceActivator.java | 59 + .../data/services/AppcDataServiceConstant.java | 51 + .../appc/data/services/db/DGGeneralDBService.java | 446 +++++++ .../appc/data/services/db/GeneralDataService.java | 80 ++ .../data/services/node/ConfigResourceNode.java | 751 ++++++++++++ .../onap/appc/data/services/utils/EscapeUtils.java | 39 + .../data/services/AppcDataServiceActivator.java | 59 - .../data/services/AppcDataServiceConstant.java | 51 - .../appc/data/services/db/DGGeneralDBService.java | 446 ------- .../appc/data/services/db/GeneralDataService.java | 80 -- .../data/services/node/ConfigResourceNode.java | 751 ------------ .../appc/data/services/utils/EscapeUtils.java | 39 - .../data/services/db/TestConfigResourceNode.java | 170 +++ .../data/services/db/TestDGGeneralDBService.java | 210 ++++ .../appc/data/services/db/TestSQLSaveQuery.java | 140 +++ .../data/services/db/TestConfigResourceNode.java | 170 --- .../data/services/db/TestDGGeneralDBService.java | 210 ---- .../appc/data/services/db/TestSQLSaveQuery.java | 140 --- .../encryptiontool/EncryptionToolActivator.java | 55 + .../appc/encryptiontool/wrapper/Constants.java | 33 + .../appc/encryptiontool/wrapper/DbServiceUtil.java | 72 ++ .../encryptiontool/wrapper/EncryptionTool.java | 168 +++ .../wrapper/EncryptionToolDGWrapper.java | 79 ++ .../wrapper/WrapperEncryptionTool.java | 129 ++ .../encryptiontool/EncryptionToolActivator.java | 55 - .../appc/encryptiontool/wrapper/Constants.java | 33 - .../appc/encryptiontool/wrapper/DbServiceUtil.java | 72 -- .../encryptiontool/wrapper/EncryptionTool.java | 168 --- .../wrapper/EncryptionToolDGWrapper.java | 79 -- .../wrapper/WrapperEncryptionTool.java | 129 -- .../appc/encryptiontool/TestEncryptionTool.java | 75 ++ .../appc/encryptiontool/TestEncryptionTool.java | 75 -- .../flow/controller/FlowControllerActivator.java | 80 ++ .../DefaultResponseHandler.java | 55 + .../flow/controller/data/ActionIdentifier.java | 70 ++ .../onap/appc/flow/controller/data/Parameters.java | 82 ++ .../onap/appc/flow/controller/data/PreCheck.java | 93 ++ .../appc/flow/controller/data/PrecheckOption.java | 120 ++ .../onap/appc/flow/controller/data/Response.java | 79 ++ .../appc/flow/controller/data/ResponseAction.java | 103 ++ .../appc/flow/controller/data/Transaction.java | 365 ++++++ .../appc/flow/controller/data/Transactions.java | 50 + .../controller/dbervices/FlowControlDBService.java | 222 ++++ .../controller/executorImpl/GraphExecutor.java | 163 +++ .../flow/controller/executorImpl/NodeExecutor.java | 47 + .../flow/controller/executorImpl/RestExecutor.java | 156 +++ .../executorImpl/SecureRestClientTrustManager.java | 54 + .../controller/interfaceData/ActionIdentifier.java | 158 +++ .../controller/interfaceData/Capabilities.java | 190 +++ .../controller/interfaceData/DependencyInfo.java | 86 ++ .../appc/flow/controller/interfaceData/Input.java | 199 +++ .../controller/interfaceData/InventoryInfo.java | 80 ++ .../controller/interfaceData/ObjectFactory.java | 147 +++ .../flow/controller/interfaceData/RequestInfo.java | 164 +++ .../interfaceData/TunableParameters.java | 153 +++ .../appc/flow/controller/interfaceData/Vm.java | 108 ++ .../flow/controller/interfaceData/VnfInfo.java | 172 +++ .../appc/flow/controller/interfaceData/Vnfcs.java | 176 +++ .../flow/controller/interfaceData/Vnfcslist.java | 127 ++ .../flow/controller/interfaceData/Vnflist.java | 150 +++ .../controller/interfaceData/package-info.java | 29 + .../interfaces/FlowExecutorInterface.java | 37 + .../appc/flow/controller/node/FlowControlNode.java | 562 +++++++++ .../appc/flow/controller/node/FlowGenerator.java | 80 ++ .../appc/flow/controller/node/JsonParsingNode.java | 98 ++ .../appc/flow/controller/node/RestServiceNode.java | 207 ++++ .../appc/flow/controller/utils/EscapeUtils.java | 39 + .../controller/utils/FlowControllerConstants.java | 117 ++ .../flow/controller/FlowControllerActivator.java | 80 -- .../DefaultResponseHandler.java | 55 - .../flow/controller/data/ActionIdentifier.java | 70 -- .../appc/flow/controller/data/Parameters.java | 82 -- .../appc/flow/controller/data/PreCheck.java | 93 -- .../appc/flow/controller/data/PrecheckOption.java | 120 -- .../appc/flow/controller/data/Response.java | 79 -- .../appc/flow/controller/data/ResponseAction.java | 103 -- .../appc/flow/controller/data/Transaction.java | 365 ------ .../appc/flow/controller/data/Transactions.java | 50 - .../controller/dbervices/FlowControlDBService.java | 222 ---- .../controller/executorImpl/GraphExecutor.java | 163 --- .../flow/controller/executorImpl/NodeExecutor.java | 47 - .../flow/controller/executorImpl/RestExecutor.java | 156 --- .../executorImpl/SecureRestClientTrustManager.java | 54 - .../controller/interfaceData/ActionIdentifier.java | 158 --- .../controller/interfaceData/Capabilities.java | 190 --- .../controller/interfaceData/DependencyInfo.java | 86 -- .../appc/flow/controller/interfaceData/Input.java | 199 --- .../controller/interfaceData/InventoryInfo.java | 80 -- .../controller/interfaceData/ObjectFactory.java | 147 --- .../flow/controller/interfaceData/RequestInfo.java | 164 --- .../interfaceData/TunableParameters.java | 153 --- .../appc/flow/controller/interfaceData/Vm.java | 108 -- .../flow/controller/interfaceData/VnfInfo.java | 172 --- .../appc/flow/controller/interfaceData/Vnfcs.java | 176 --- .../flow/controller/interfaceData/Vnfcslist.java | 127 -- .../flow/controller/interfaceData/Vnflist.java | 150 --- .../controller/interfaceData/package-info.java | 29 - .../interfaces/FlowExecutorInterface.java | 37 - .../appc/flow/controller/node/FlowControlNode.java | 562 --------- .../appc/flow/controller/node/FlowGenerator.java | 80 -- .../appc/flow/controller/node/JsonParsingNode.java | 98 -- .../appc/flow/controller/node/RestServiceNode.java | 207 ---- .../appc/flow/controller/utils/EscapeUtils.java | 39 - .../controller/utils/FlowControllerConstants.java | 117 -- .../executor/node/FlowControlDBServiceTest.java | 172 +++ .../flow/executor/node/FlowControlNodeTest.java | 165 +++ .../appc/flow/executor/node/RestExecutorTest.java | 103 ++ .../flow/executor/node/TestFlowExecutorNode.java | 79 ++ .../appc/flow/executor/node/TestParsingNode.java | 52 + .../flow/executor/node/TestRestServiceNode.java | 87 ++ .../executor/node/FlowControlDBServiceTest.java | 172 --- .../flow/executor/node/FlowControlNodeTest.java | 165 --- .../appc/flow/executor/node/RestExecutorTest.java | 103 -- .../flow/executor/node/TestFlowExecutorNode.java | 79 -- .../appc/flow/executor/node/TestParsingNode.java | 52 - .../flow/executor/node/TestRestServiceNode.java | 87 -- 260 files changed, 16971 insertions(+), 16971 deletions(-) create mode 100644 appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/CCAActivator.java create mode 100644 appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/ConfigComponentAdaptor.java create mode 100644 appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/DebugLog.java create mode 100644 appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/EncryptionTool.java create mode 100644 appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/SshJcraftWrapper.java create mode 100644 appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/TelnetListener.java create mode 100644 appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/TimedOutException.java create mode 100644 appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/XmlUtil.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/CCAActivator.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/ConfigComponentAdaptor.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/DebugLog.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/EncryptionTool.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/SshJcraftWrapper.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/TelnetListener.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/TimedOutException.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/XmlUtil.java create mode 100644 appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestConfigComponentAdaptor.java create mode 100644 appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestDebugLog.java create mode 100644 appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestEncryptionTool.java create mode 100644 appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestSshJcraftWrapper.java create mode 100644 appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestXmlUtil.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestConfigComponentAdaptor.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestDebugLog.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestEncryptionTool.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestSshJcraftWrapper.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestXmlUtil.java create mode 100644 appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/ConfigComponentAdaptorTest.java create mode 100644 appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/DebugLogTest.java create mode 100644 appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/EncryptionToolTest.java create mode 100644 appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/SshJcraftWrapperTest.java create mode 100644 appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/XmlUtilTest.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/ConfigComponentAdaptorTest.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/DebugLogTest.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/EncryptionToolTest.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/SshJcraftWrapperTest.java delete mode 100644 appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/XmlUtilTest.java create mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/SliAuditActivator.java create mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/SliAuditConstant.java create mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareCliData.java create mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareConstants.java create mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareDataInterface.java create mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareJsonData.java create mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareNode.java create mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareXmlData.java create mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/Parameters.java delete mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/SliAuditActivator.java delete mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/SliAuditConstant.java delete mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareCliData.java delete mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareConstants.java delete mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareDataInterface.java delete mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareJsonData.java delete mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareNode.java delete mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareXmlData.java delete mode 100644 appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/Parameters.java create mode 100644 appc-config/appc-config-audit/provider/src/test/java/org/onap/sdnc/config/audit/node/TestCompareNodeCli.java create mode 100644 appc-config/appc-config-audit/provider/src/test/java/org/onap/sdnc/config/audit/node/TestCompareNodeJson.java create mode 100644 appc-config/appc-config-audit/provider/src/test/java/org/onap/sdnc/config/audit/node/TestCompareNodeXml.java delete mode 100644 appc-config/appc-config-audit/provider/src/test/java/org/openecomp/sdnc/config/audit/node/TestCompareNodeCli.java delete mode 100644 appc-config/appc-config-audit/provider/src/test/java/org/openecomp/sdnc/config/audit/node/TestCompareNodeJson.java delete mode 100644 appc-config/appc-config-audit/provider/src/test/java/org/openecomp/sdnc/config/audit/node/TestCompareNodeXml.java create mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/ConfigGeneratorActivator.java create mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/ConfigGeneratorConstant.java create mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/convert/ConvertNode.java create mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/merge/MergeNode.java create mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/pattern/PatternNode.java create mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/reader/ReaderNode.java create mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/CheckDataTool.java create mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/Constants.java create mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/CustomJsonNodeFactory.java create mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/CustomTextNode.java create mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/DbServiceUtil.java create mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/EscapeUtils.java create mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/JSONTool.java create mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/LogParserTool.java create mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/MergeTool.java create mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/transform/XSLTTransformerNode.java create mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/writer/FileWriterNode.java delete mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/ConfigGeneratorActivator.java delete mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/ConfigGeneratorConstant.java delete mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/convert/ConvertNode.java delete mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/merge/MergeNode.java delete mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/pattern/PatternNode.java delete mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/reader/ReaderNode.java delete mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/CheckDataTool.java delete mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/Constants.java delete mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/CustomJsonNodeFactory.java delete mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/CustomTextNode.java delete mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/DbServiceUtil.java delete mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/EscapeUtils.java delete mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/JSONTool.java delete mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/LogParserTool.java delete mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/MergeTool.java delete mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/transform/XSLTTransformerNode.java delete mode 100644 appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/writer/FileWriterNode.java create mode 100644 appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/convert/TestConvertNode.java create mode 100644 appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/merge/TestMergeNode.java create mode 100644 appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/pattern/TestPatternNode.java create mode 100644 appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/reader/TestReaderNode.java create mode 100644 appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/tool/TestDataTool.java create mode 100644 appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/transform/TestXSLTTransformerNode.java create mode 100644 appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/writer/TestFileWriterNode.java delete mode 100644 appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/convert/TestConvertNode.java delete mode 100644 appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/merge/TestMergeNode.java delete mode 100644 appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/pattern/TestPatternNode.java delete mode 100644 appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/reader/TestReaderNode.java delete mode 100644 appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/tool/TestDataTool.java delete mode 100644 appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/transform/TestXSLTTransformerNode.java delete mode 100644 appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/writer/TestFileWriterNode.java create mode 100644 appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/ParamsHandlerActivator.java create mode 100644 appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/ParamsHandlerConstant.java create mode 100644 appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/data/Parameter.java create mode 100644 appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/data/PropertyDefinition.java create mode 100644 appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/data/RequestKey.java create mode 100644 appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/data/ResponseKey.java create mode 100644 appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/parser/PropertyDefinitionNode.java create mode 100644 appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/ArtificatTransformer.java create mode 100644 appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/tosca/ArtifactProcessor.java create mode 100644 appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/tosca/ArtifactProcessorFactory.java create mode 100644 appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/tosca/ArtifactProcessorImpl.java create mode 100644 appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/tosca/exceptions/ArtifactProcessorException.java delete mode 100644 appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/ParamsHandlerActivator.java delete mode 100644 appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/ParamsHandlerConstant.java delete mode 100644 appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/data/Parameter.java delete mode 100644 appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/data/PropertyDefinition.java delete mode 100644 appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/data/RequestKey.java delete mode 100644 appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/data/ResponseKey.java delete mode 100644 appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/parser/PropertyDefinitionNode.java delete mode 100644 appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/ArtificatTransformer.java delete mode 100644 appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/tosca/ArtifactProcessor.java delete mode 100644 appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/tosca/ArtifactProcessorFactory.java delete mode 100644 appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/tosca/ArtifactProcessorImpl.java delete mode 100644 appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/tosca/exceptions/ArtifactProcessorException.java create mode 100644 appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/parser/TestPropertyDefinitionNode.java create mode 100644 appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestArtifactProcessor.java create mode 100644 appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestGenerateArtifactObject.java create mode 100644 appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestGenerateArtifactString.java create mode 100644 appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestPropertyQueryString.java create mode 100644 appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestReadArtifact.java delete mode 100644 appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/parser/TestPropertyDefinitionNode.java delete mode 100644 appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestArtifactProcessor.java delete mode 100644 appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestGenerateArtifactObject.java delete mode 100644 appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestGenerateArtifactString.java delete mode 100644 appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestPropertyQueryString.java delete mode 100644 appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestReadArtifact.java create mode 100644 appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/AppcDataServiceActivator.java create mode 100644 appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/AppcDataServiceConstant.java create mode 100644 appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/db/DGGeneralDBService.java create mode 100644 appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/db/GeneralDataService.java create mode 100644 appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/node/ConfigResourceNode.java create mode 100644 appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/utils/EscapeUtils.java delete mode 100644 appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/AppcDataServiceActivator.java delete mode 100644 appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/AppcDataServiceConstant.java delete mode 100644 appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/db/DGGeneralDBService.java delete mode 100644 appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/db/GeneralDataService.java delete mode 100644 appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/node/ConfigResourceNode.java delete mode 100644 appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/utils/EscapeUtils.java create mode 100644 appc-config/appc-data-services/provider/src/test/java/org/onap/appc/data/services/db/TestConfigResourceNode.java create mode 100644 appc-config/appc-data-services/provider/src/test/java/org/onap/appc/data/services/db/TestDGGeneralDBService.java create mode 100644 appc-config/appc-data-services/provider/src/test/java/org/onap/appc/data/services/db/TestSQLSaveQuery.java delete mode 100644 appc-config/appc-data-services/provider/src/test/java/org/openecomp/appc/data/services/db/TestConfigResourceNode.java delete mode 100644 appc-config/appc-data-services/provider/src/test/java/org/openecomp/appc/data/services/db/TestDGGeneralDBService.java delete mode 100644 appc-config/appc-data-services/provider/src/test/java/org/openecomp/appc/data/services/db/TestSQLSaveQuery.java create mode 100644 appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/EncryptionToolActivator.java create mode 100644 appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/Constants.java create mode 100644 appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/DbServiceUtil.java create mode 100644 appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/EncryptionTool.java create mode 100644 appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/EncryptionToolDGWrapper.java create mode 100644 appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/WrapperEncryptionTool.java delete mode 100644 appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/EncryptionToolActivator.java delete mode 100644 appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/Constants.java delete mode 100644 appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/DbServiceUtil.java delete mode 100644 appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/EncryptionTool.java delete mode 100644 appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/EncryptionToolDGWrapper.java delete mode 100644 appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/WrapperEncryptionTool.java create mode 100644 appc-config/appc-encryption-tool/provider/src/test/java/org/onap/appc/encryptiontool/TestEncryptionTool.java delete mode 100644 appc-config/appc-encryption-tool/provider/src/test/java/org/openecomp/appc/encryptiontool/TestEncryptionTool.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/FlowControllerActivator.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/ResponseHandlerImpl/DefaultResponseHandler.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/ActionIdentifier.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/Parameters.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/PreCheck.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/PrecheckOption.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/Response.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/ResponseAction.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/Transaction.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/Transactions.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/dbervices/FlowControlDBService.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/executorImpl/GraphExecutor.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/executorImpl/NodeExecutor.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/executorImpl/RestExecutor.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/executorImpl/SecureRestClientTrustManager.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/ActionIdentifier.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Capabilities.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/DependencyInfo.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Input.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/InventoryInfo.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/ObjectFactory.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/RequestInfo.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/TunableParameters.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Vm.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/VnfInfo.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Vnfcs.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Vnfcslist.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Vnflist.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/package-info.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaces/FlowExecutorInterface.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/node/FlowControlNode.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/node/FlowGenerator.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/node/JsonParsingNode.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/node/RestServiceNode.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/utils/EscapeUtils.java create mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/utils/FlowControllerConstants.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/FlowControllerActivator.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/ResponseHandlerImpl/DefaultResponseHandler.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/ActionIdentifier.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/Parameters.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/PreCheck.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/PrecheckOption.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/Response.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/ResponseAction.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/Transaction.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/Transactions.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/dbervices/FlowControlDBService.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/executorImpl/GraphExecutor.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/executorImpl/NodeExecutor.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/executorImpl/RestExecutor.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/executorImpl/SecureRestClientTrustManager.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/ActionIdentifier.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Capabilities.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/DependencyInfo.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Input.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/InventoryInfo.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/ObjectFactory.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/RequestInfo.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/TunableParameters.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Vm.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/VnfInfo.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Vnfcs.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Vnfcslist.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Vnflist.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/package-info.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaces/FlowExecutorInterface.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/node/FlowControlNode.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/node/FlowGenerator.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/node/JsonParsingNode.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/node/RestServiceNode.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/utils/EscapeUtils.java delete mode 100644 appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/utils/FlowControllerConstants.java create mode 100644 appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/FlowControlDBServiceTest.java create mode 100644 appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/FlowControlNodeTest.java create mode 100644 appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/RestExecutorTest.java create mode 100644 appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/TestFlowExecutorNode.java create mode 100644 appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/TestParsingNode.java create mode 100644 appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/TestRestServiceNode.java delete mode 100644 appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/FlowControlDBServiceTest.java delete mode 100644 appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/FlowControlNodeTest.java delete mode 100644 appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/RestExecutorTest.java delete mode 100644 appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/TestFlowExecutorNode.java delete mode 100644 appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/TestParsingNode.java delete mode 100644 appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/TestRestServiceNode.java (limited to 'appc-config') diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/CCAActivator.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/CCAActivator.java new file mode 100644 index 000000000..d9d2b11b0 --- /dev/null +++ b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/CCAActivator.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.ccadaptor; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.Properties; + +import org.onap.ccsdk.sli.core.sli.ConfigurationException; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class CCAActivator implements BundleActivator +{ + + private static final String CCA_PROP_FILE_VAR = "SDNC_CCA_PROPERTIES"; + private static final String SDNC_CONFIG_DIR_VAR = "APPC_CONFIG_DIR"; + + @SuppressWarnings("rawtypes") + private ServiceRegistration registration = null; + + //private static final Logger log = LoggerFactory.getLogger(CCAActivator.class); + private static final EELFLogger log = EELFManager.getInstance().getLogger(CCAActivator.class); + + @Override + public void start(BundleContext ctx) throws Exception + { + // Read properties + Properties props = new Properties(); + + // Read properties from appc-config-adaptor.properties + String propFileName = System.getenv(CCA_PROP_FILE_VAR); + if (propFileName == null) + { + String propDir = System.getenv(SDNC_CONFIG_DIR_VAR); + if (propDir == null) + throw new ConfigurationException( + "Cannot find config file - " + CCA_PROP_FILE_VAR + " and " + SDNC_CONFIG_DIR_VAR + " unset"); + + propFileName = propDir + "/appc-config-adaptor.properties"; + log.warn("Environment variable " + CCA_PROP_FILE_VAR + " unset - defaulting to " + propFileName); + } + + File propFile = new File(propFileName); + if (!propFile.exists()) + throw new ConfigurationException("Missing configuration properties file: " + propFile); + + try(InputStream in = new FileInputStream(propFile)) { + props.load(in); + log.info("Loaded properties: "); + } + catch (Exception e) + { + throw new ConfigurationException("Could not load properties file " + propFileName, e); + } + + // Advertise adaptor + ConfigComponentAdaptor adaptor = new ConfigComponentAdaptor(props); + if (registration == null) + { + log.info("Registering service " + ConfigComponentAdaptor.class.getName()); + registration = ctx.registerService(ConfigComponentAdaptor.class.getName(), adaptor, null); + } + + } + + @Override + public void stop(BundleContext ctx) throws Exception + { + if (registration != null) + { + registration.unregister(); + registration = null; + } + } +} diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/ConfigComponentAdaptor.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/ConfigComponentAdaptor.java new file mode 100644 index 000000000..1434b3d93 --- /dev/null +++ b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/ConfigComponentAdaptor.java @@ -0,0 +1,1064 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property.All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.ccadaptor; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.FileReader; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.StringTokenizer; +import java.util.NoSuchElementException; +import java.io.StringReader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.core.util.Base64; +import org.jdom.input.SAXBuilder; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ConfigComponentAdaptor implements SvcLogicAdaptor +{ + + private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class); + + private String configUrl = null; + private String configUser = null; + private String configPassword = null; + private String auditUrl = null; + private String auditUser = null; + private String auditPassword = null; + private String configCallbackUrl = null; + private String auditCallbackUrl = null; + DebugLog debugLog = new DebugLog(); + + public ConfigComponentAdaptor(Properties props) + { + if (props != null) + { + configUrl = props.getProperty("configComponent.url", ""); + configUser = props.getProperty("configComponent.user", ""); + configPassword = props.getProperty("configComponent.passwd", ""); + auditUrl = props.getProperty("auditComponent.url", ""); + auditUser = props.getProperty("auditComponent.user", ""); + auditPassword = props.getProperty("auditComponent.passwd", ""); + configCallbackUrl = props.getProperty("service-configuration-notification-url", ""); + auditCallbackUrl = props.getProperty("audit-configuration-notification-url", ""); + } + else + { + configUrl = ""; + configUser = ""; + configPassword = ""; + auditUrl = ""; + auditUser = ""; + auditPassword = ""; + configCallbackUrl = ""; + auditCallbackUrl = ""; + } + } + + @Override + public ConfigStatus configure(String key, Map parameters, SvcLogicContext ctx) + { + String fnName = "ConfigComponentAdaptor.configure"; + HttpResponse r = new HttpResponse(); + r.code = 200; + log.debug("ConfigComponentAdaptor.configure - key = " + key); + debugLog.printRTAriDebug(fnName, "key = " + key); + log.debug("Parameters:"); + debugLog.printRTAriDebug(fnName, "Parameters:"); + for (String parmName : parameters.keySet()) + { + log.debug(" " + parmName + " = " + parameters.get(parmName)); + debugLog.printRTAriDebug(fnName, " " + parmName + " = " + parameters.get(parmName)); + } + + String parmval = parameters.get("config-component-configUrl"); + if ((parmval != null) && (parmval.length() > 0)) + { + log.debug("Overwriting URL with " + parmval); + configUrl = parmval; + } + + parmval = parameters.get("config-component-configPassword"); + if ((parmval != null) && (parmval.length() > 0)) + { + log.debug("Overwriting configPassword with " + parmval); + configPassword = parmval; + } + + parmval = parameters.get("config-component-configUser"); + if ((parmval != null) && (parmval.length() > 0)) + { + log.debug("Overwriting configUser id with " + parmval); + configUser = parmval; + } + + String action = parameters.get("action"); + + String chg = ctx.getAttribute( + "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name"); + if (chg != null && "prepare".equalsIgnoreCase(action)) + return prepare(ctx, "CHANGE", "change"); + if (chg != null && "activate".equalsIgnoreCase(action)) + return activate(ctx, true); + + String scale = ctx.getAttribute( + "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type"); + if (scale != null && "prepare".equalsIgnoreCase(action)) + return prepare(ctx, "CHANGE", "scale"); + if (scale != null && "activate".equalsIgnoreCase(action)) + return activate(ctx, true); + + if ("prepare".equalsIgnoreCase(action)) + return prepare(ctx, "BASE", "create"); + if ("activate".equalsIgnoreCase(action)) + return activate(ctx, false); + + if ("backup".equalsIgnoreCase(action)) + return prepare(ctx, "BACKUP", "backup"); + if ("restorebackup".equalsIgnoreCase(action)) + return prepare(ctx, "RESTOREBACKUP", "restorebackup"); + if ("deletebackup".equalsIgnoreCase(action)) + return prepare(ctx, "DELETEBACKUP", "deletebackup"); + if ("audit".equalsIgnoreCase(action)) + return audit(ctx, "FULL"); + if ("getrunningconfig".equalsIgnoreCase(action)) + return audit(ctx, "RUNNING"); + + if ((key.equals("put")) || (key.equals("get"))) + { + String loginId = parameters.get("loginId"); + String host = parameters.get("host"); + String password = parameters.get("password"); + password = EncryptionTool.getInstance().decrypt(password); + String fullPathFileName = parameters.get("fullPathFileName"); + String data = null; + + SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + log.debug("SCP: SshJcraftWrapper has been instantiated"); + debugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated"); + try + { + if (key.equals("put")) + { + data = parameters.get("data"); + if (data != null) { + debugLog.printRTAriDebug(fnName, "Command is for put: Length of data is: " + data.length()); + InputStream is = new ByteArrayInputStream(data.getBytes()); + log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName); + debugLog.printRTAriDebug(fnName, "SCP: Doing a put: fullPathFileName=" + fullPathFileName); + sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password); + try + { + debugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds...."); + Thread.sleep(1000 * 180); + debugLog.printRTAriDebug(fnName, "Woke up...."); + } + catch (java.lang.InterruptedException ee) + { + boolean ignore = true; + } + } else { + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + log.debug(fnName + " Command is for put: data is null"); + } + } + else // Must be a get + { + log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName); + debugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName); + String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password); + debugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object"); + ctx.setAttribute("fileContents", response); + log.debug("SCP: Closing the SFTP connection"); + } + sshJcraftWrapper = null; + return (setResponseStatus(ctx, r)); + } + catch (IOException e) + { + DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e); + log.debug(fnName + " : Caught a IOException e=" + e); + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.message = e.getMessage(); + sshJcraftWrapper = null; + return (setResponseStatus(ctx, r)); + } + } + if (key.equals("cli")) + { + String loginId = parameters.get("loginId"); + String host = parameters.get("host"); + String password = parameters.get("password"); + password = EncryptionTool.getInstance().decrypt(password); + String cliCommand = parameters.get("cli"); + String portNumber = parameters.get("portNumber"); + SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + try + { + log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId + " password=" + password + + " portNumber=" + portNumber); + debugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId + + " password=" + password + " portNumber=" + portNumber); + sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber)); + + DebugLog.printAriDebug(fnName, "Sending 'sdc'"); + String response = sshJcraftWrapper.send("sdc", ":"); + DebugLog.printAriDebug(fnName, "Sending 1"); + response = sshJcraftWrapper.send("1", ":"); + DebugLog.printAriDebug(fnName, "Sending 1, the second time"); + response = sshJcraftWrapper.send("1", "#"); + DebugLog.printAriDebug(fnName, "Sending paging-options disable"); + response = sshJcraftWrapper.send("paging-options disable", "#"); + DebugLog.printAriDebug(fnName, "Sending show config"); + response = sshJcraftWrapper.send("show config", "#"); + + DebugLog.printAriDebug(fnName, "response is now:'" + response + "'"); + DebugLog.printAriDebug(fnName, "Populating the ctx object with the response"); + ctx.setAttribute("cliOutput", response); + sshJcraftWrapper.closeConnection(); + r.code = 200; + sshJcraftWrapper = null; + return (setResponseStatus(ctx, r)); + } + catch (IOException e) + { + DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e); + log.debug(fnName + " : Caught a IOException e=" + e); + sshJcraftWrapper.closeConnection(); + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.message = e.getMessage(); + sshJcraftWrapper = null; + DebugLog.printAriDebug(fnName, "Returning error message"); + return (setResponseStatus(ctx, r)); + } + } + if (key.equals("escapeSql")) + { + String data = parameters.get("artifactContents"); + log.debug("ConfigComponentAdaptor.configure - escapeSql"); + data = escapeMySql(data); + ctx.setAttribute("escapedData", data); + return (setResponseStatus(ctx, r)); + } + if(key.equals("GetCliRunningConfig")) + { + debugLog.printRTAriDebug (fnName, "key was: GetCliRunningConfig: "); + log.debug("key was: GetCliRunningConfig: "); + String User_name = parameters.get("User_name"); + String Host_ip_address = parameters.get("Host_ip_address"); + String Password = parameters.get("Password"); + Password = EncryptionTool.getInstance().decrypt(Password); + String Port_number = parameters.get("Port_number"); + String Get_config_template = parameters.get("Get_config_template"); + SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated"); + debugLog.printRTAriDebug (fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated"); + try + { + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name="+User_name + + " Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number); + log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address="+Host_ip_address + + " User_name="+User_name+" Password="+Password+" Port_number="+Port_number); + StringBuffer sb = new StringBuffer(); + String response = ""; + String CliResponse = ""; + boolean showConfigFlag = false; + sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number)); + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device"); + StringTokenizer st = new StringTokenizer(Get_config_template, "\n"); + String command = null; + try + { + while (st.hasMoreTokens()) + { + String line = st.nextToken(); + DebugLog.printAriDebug(fnName, "line="+line); + if (line.indexOf("Request:") != -1) + { + DebugLog.printAriDebug(fnName, "Found a Request line: line="+line); + command = getStringBetweenQuotes(line); + DebugLog.printAriDebug(fnName, "Sending command="+command); + sshJcraftWrapper.send(command); + DebugLog.printAriDebug(fnName, "command has been sent"); + if (line.indexOf("show config") != -1) + { + showConfigFlag = true; + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true"); + log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true"); + } + } + if (line.indexOf("Response: Ends_With") != -1) + { + DebugLog.printAriDebug(fnName, "Found a Response line: line="+line); + String delemeter = getStringBetweenQuotes(line); + DebugLog.printAriDebug(fnName, "The delemeter="+delemeter); + String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, 30*1000, command); + response += tmpResponse; + if (showConfigFlag) + { + showConfigFlag = false; + StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n"); + // Strip off the last line which is the command prompt from the VNF device. + while (st2.hasMoreTokens()) + { + String line2 = st2.nextToken(); + if (line2.indexOf("#") == -1) + CliResponse += line2 +"\n"; + } + } + } + } + } + catch (NoSuchElementException e) + { + DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e="+e); + } + DebugLog.printAriDebug(fnName, "CliResponse=\n"+CliResponse); + ctx.setAttribute("cliOutput", CliResponse); + sshJcraftWrapper.closeConnection(); + r.code = 200; + sshJcraftWrapper = null; + return(setResponseStatus(ctx, r)); + } + catch(IOException e) + { + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e="+e); + log.debug(fnName +" : GetCliRunningConfig: Caught a IOException e="+e); + sshJcraftWrapper.closeConnection(); + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.message = e.getMessage(); + sshJcraftWrapper = null; + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Returning error message"); + return(setResponseStatus(ctx, r)); + } + } + if(key.equals("xml-download")) + { + log(fnName, "key was: xml-download"); + String User_name = parameters.get("User_name"); + String Host_ip_address = parameters.get("Host_ip_address"); + String Password = parameters.get("Password"); + Password = EncryptionTool.getInstance().decrypt(Password); + String Port_number = parameters.get("Port_number"); + String Contents = parameters.get("Contents"); + String netconfHelloCmd = "\n \n \n urn:ietf:params:netconf:base:1.0\n urn:com:ericsson:ebase:1.1.0 \n "; + String terminateConnectionCmd = "\n \n \n \n ]]>]]>"; + String commitCmd = "\n \n ]]>]]>"; + + log(fnName, "xml-download: User_name="+User_name +" Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number); + SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + try + { + sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number), "netconf"); + String NetconfHelloCmd = netconfHelloCmd; + NetconfHelloCmd = NetconfHelloCmd +"]]>]]>"; + log(fnName, "Sending the hello command"); + sshJcraftWrapper.send(NetconfHelloCmd); + String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, ""); + log(fnName, "Sending xmlCmd cmd"); + String xmlCmd = Contents; + String messageId = "1"; + messageId= "\"" +messageId+"\""; + String loadConfigurationString = " merge "+xmlCmd+" "; + loadConfigurationString = loadConfigurationString +"]]>]]>"; + sshJcraftWrapper.send(loadConfigurationString); + DebugLog.printAriDebug(fnName,":After sending loadConfigurationString"); + response = sshJcraftWrapper.receiveUntil("", 600000, ""); + if (response.indexOf("rpc-error") != -1) + { + DebugLog.printAriDebug(fnName,"Error from device: Response from device had 'rpc-error'"); + DebugLog.printAriDebug(fnName,"response=\n"+response +"\n"); + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.message = response; + } + else + { + DebugLog.printAriDebug(fnName,":LoadConfiguration was a success, sending commit cmd"); + sshJcraftWrapper.send(commitCmd); + DebugLog.printAriDebug(fnName,":After sending commitCmd"); + response = sshJcraftWrapper.receiveUntil("", 180000, ""); + if (response.indexOf("rpc-error") != -1) + { + DebugLog.printAriDebug(fnName,"Error from device: Response from device had 'rpc-error'"); + DebugLog.printAriDebug(fnName,"response=\n"+response +"\n"); + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.message = response; + } + else + { + DebugLog.printAriDebug(fnName,":Looks like a success"); + DebugLog.printAriDebug(fnName,"response=\n"+response +"\n"); + r.code = 200; + } + } + sshJcraftWrapper.send(terminateConnectionCmd); + sshJcraftWrapper.closeConnection(); + sshJcraftWrapper = null; + return(setResponseStatus(ctx, r)); + } + catch (Exception e) + { + log(fnName, "Caught an Exception, e="+e); + log(fnName, "StackTrace="+DebugLog.getStackTraceString(e)); + sshJcraftWrapper.closeConnection(); + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.message = e.getMessage(); + sshJcraftWrapper = null; + log(fnName, "Returning error message"); + return (setResponseStatus(ctx, r)); + } + } + if(key.equals("xml-getrunningconfig")) + { + log(fnName, "key was: : xml-getrunningconfig"); + String xmlGetRunningConfigCmd = " \n"; + String Host_ip_address = parameters.get("Host_ip_address"); + String User_name = parameters.get("User_name"); + String Password = parameters.get("Password"); + Password = EncryptionTool.getInstance().decrypt(Password); + String Port_number = parameters.get("Port_number"); + String Protocol = parameters.get("Protocol"); + String netconfHelloCmd = "\n \n \n urn:ietf:params:netconf:base:1.0\n urn:com:ericsson:ebase:1.1.0 \n "; + String terminateConnectionCmd = "\n \n \n \n ]]>]]>"; + log(fnName, "xml-getrunningconfig: User_name="+User_name +" Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number); + SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + try + { + String NetconfHelloCmd = netconfHelloCmd; + sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number), "netconf"); + NetconfHelloCmd = NetconfHelloCmd +"]]>]]>"; + log(fnName, ":Sending the hello command"); + sshJcraftWrapper.send(NetconfHelloCmd); + String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, ""); + log(fnName, "Sending get running config command"); + sshJcraftWrapper.send(xmlGetRunningConfigCmd +"]]>]]>\n"); + response = sshJcraftWrapper.receiveUntil("", 180000, ""); + DebugLog.printAriDebug(fnName,"Response from getRunningconfigCmd="+response); + response = trimResponse(response); + ctx.setAttribute("xmlRunningConfigOutput", response); + sshJcraftWrapper.send(terminateConnectionCmd); + sshJcraftWrapper.closeConnection(); + r.code = 200; + sshJcraftWrapper = null; + return(setResponseStatus(ctx, r)); + } + catch (Exception e) + { + log(fnName, "Caught an Exception, e="+e); + log(fnName, "StackTrace="+DebugLog.getStackTraceString(e)); + sshJcraftWrapper.closeConnection(); + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.message = e.getMessage(); + sshJcraftWrapper = null; + log(fnName, "Returning error message"); + return (setResponseStatus(ctx, r)); + } + } + if(key.equals("DownloadCliConfig")) + { + debugLog.printRTAriDebug (fnName, "key was: DownloadCliConfig: "); + log.debug("key was: DownloadCliConfig: "); + String User_name = parameters.get("User_name"); + String Host_ip_address = parameters.get("Host_ip_address"); + String Password = parameters.get("Password"); + Password = EncryptionTool.getInstance().decrypt(Password); + String Port_number = parameters.get("Port_number"); + String Download_config_template = parameters.get("Download_config_template"); + String Config_contents = parameters.get("Config_contents"); + DebugLog.printAriDebug(fnName, "Contents of the 'Config_contents' are: "+Config_contents); + SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated"); + debugLog.printRTAriDebug (fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated"); + int timeout = 4*60*1000; + try + { + DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name="+User_name + + " Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number); + log.debug("DownloadCliConfig: Attempting to login: Host_ip_address="+Host_ip_address + + " User_name="+User_name+" Password="+Password+" Port_number="+Port_number); + StringBuffer sb = new StringBuffer(); + String response = ""; + String CliResponse = ""; + sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number)); + DebugLog.printAriDebug(fnName, "DownloadCliConfig: On the VNF device"); + StringTokenizer st = new StringTokenizer(Download_config_template, "\n"); + String command = null; + String executeConfigContentsDelemeter = null; + try + { + while (st.hasMoreTokens()) + { + String line = st.nextToken(); + DebugLog.printAriDebug(fnName, "line="+line); + if (line.indexOf("Request:") != -1) + { + DebugLog.printAriDebug(fnName, "Found a Request line: line="+line); + command = getStringBetweenQuotes(line); + DebugLog.printAriDebug(fnName, "Sending command="+command); + sshJcraftWrapper.send(command); + DebugLog.printAriDebug(fnName, "command has been sent"); + } + else if ((line.indexOf("Response: Ends_With") != -1) && (line.indexOf("Execute_config_contents Response: Ends_With") == -1)) + { + DebugLog.printAriDebug(fnName, "Found a Response line: line="+line); + String delemeter = getStringBetweenQuotes(line); + DebugLog.printAriDebug(fnName, "The delemeter="+delemeter); + String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, timeout, command); + response += tmpResponse; + CliResponse += tmpResponse; + } + else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) + { + DebugLog.printAriDebug(fnName, "Found a 'Execute_config_contents Response:' line="+line); + executeConfigContentsDelemeter = getStringBetweenQuotes(line); + DebugLog.printAriDebug(fnName, "executeConfigContentsDelemeter="+executeConfigContentsDelemeter); + StringTokenizer st2 = new StringTokenizer(Config_contents, "\n"); + while (st2.hasMoreTokens()) + { + String cmd = st2.nextToken(); + DebugLog.printAriDebug(fnName, "Config_contents: cmd="+cmd); + sshJcraftWrapper.send(cmd); + String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter, timeout, command); + CliResponse += tmpResponse; + } + } + } + } + catch (NoSuchElementException e) + { + DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e="+e); + } + sshJcraftWrapper.closeConnection(); + sshJcraftWrapper = null; + DebugLog.printAriDebug(fnName, ":Escaping all the single and double quotes in the response"); + CliResponse = CliResponse.replaceAll("\"", "\\\\\""); + CliResponse = CliResponse.replaceAll("\'", "\\\\'"); + DebugLog.printAriDebug(fnName, "CliResponse=\n"+CliResponse); + ctx.setAttribute("cliOutput", CliResponse); + r.code = 200; + return(setResponseStatus(ctx, r)); + } + catch(IOException e) + { + DebugLog.printAriDebug(fnName, "DownloadCliConfig: Caught a IOException e="+e); + log.debug(fnName +" : DownloadCliConfig: Caught a IOException e="+e); + sshJcraftWrapper.closeConnection(); + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.message = e.getMessage(); + sshJcraftWrapper = null; + DebugLog.printAriDebug(fnName, "DownloadCliConfig: Returning error message"); + return(setResponseStatus(ctx, r)); + } + } + + debugLog.printRTAriDebug (fnName, "Unsupported action - " + action); + log.error("Unsupported action - " + action); + return ConfigStatus.FAILURE; + } + + private void log (String fileName, String messg) + { + debugLog.printRTAriDebug (fileName, messg); + log.debug(fileName +": "+messg); + } + + private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) + { + String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml"; + String ndTemplate = readFile(templateName); + String nd = buildNetworkData2(ctx, ndTemplate, operation); + + String reqTemplate = readFile("/config-request.xml"); + Map param = new HashMap(); + param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id")); + param.put("request-type", requestType); + param.put("callback-url", configCallbackUrl); + if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) + param.put("action", "GenerateOnly"); + param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id")); + param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address")); + param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor")); + param.put("network-data", nd); + + String req = null; + try + { + req = buildXmlRequest(param, reqTemplate); + } + catch (Exception e) + { + log.error("Error building the XML request: ", e); + + HttpResponse r = new HttpResponse(); + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.message = e.getMessage(); + return setResponseStatus(ctx, r); + } + + HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword); + return setResponseStatus(ctx, r); + } + + private ConfigStatus activate(SvcLogicContext ctx, boolean change) + { + String reqTemplate = readFile("/config-request.xml"); + Map param = new HashMap(); + param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id")); + param.put("callback-url", configCallbackUrl); + param.put("action", change ? "DownloadChange" : "DownloadBase"); + param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id")); + + String req = null; + try + { + req = buildXmlRequest(param, reqTemplate); + } + catch (Exception e) + { + log.error("Error building the XML request: ", e); + + HttpResponse r = new HttpResponse(); + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.message = e.getMessage(); + return setResponseStatus(ctx, r); + } + + HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword); + return setResponseStatus(ctx, r); + } + + private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) + { + String reqTemplate = readFile("/audit-request.xml"); + Map param = new HashMap(); + param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id")); + param.put("callback-url", auditCallbackUrl); + param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id")); + param.put("audit-level", auditLevel); + + String req = null; + try + { + req = buildXmlRequest(param, reqTemplate); + } + catch (Exception e) + { + log.error("Error building the XML request: ", e); + + HttpResponse r = new HttpResponse(); + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.message = e.getMessage(); + return setResponseStatus(ctx, r); + } + + HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword); + return setResponseStatus(ctx, r); + } + + @Override + public ConfigStatus activate(String key, SvcLogicContext ctx) + { + return ConfigStatus.SUCCESS; + } + + @Override + public ConfigStatus deactivate(String key, SvcLogicContext ctx) + { + return ConfigStatus.SUCCESS; + } + + private String escapeMySql(String input) + { + if (input == null) + return null; + + input = input.replace("\\", "\\\\"); + input = input.replace("\'", "\\'"); + + return input; + } + + private String readFile(String fileName) + { + InputStream is = getClass().getResourceAsStream(fileName); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader in = new BufferedReader(isr); + StringBuilder ss = new StringBuilder(); + try + { + String s = in.readLine(); + while (s != null) + { + ss.append(s).append('\n'); + s = in.readLine(); + } + } + catch (IOException e) + { + System.out.println("Error reading " + fileName + ": " + e.getMessage()); + throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e); + } + finally + { + try + { + in.close(); + } + catch (Exception e) + { + log.warn("Could not close BufferedReader", e); + } + try + { + isr.close(); + } + catch (Exception e) + { + log.warn("Could not close InputStreamReader", e); + } + try + { + is.close(); + } + catch (Exception e) + { + log.warn("Could not close InputStream", e); + } + } + return ss.toString(); + } + + private String buildXmlRequest(Map param, String template) + { + StringBuilder ss = new StringBuilder(); + int i = 0; + while (i < template.length()) + { + int i1 = template.indexOf("${", i); + if (i1 < 0) + { + ss.append(template.substring(i)); + break; + } + + int i2 = template.indexOf('}', i1 + 2); + if (i2 < 0) + throw new RuntimeException("Template error: Matching } not found"); + + String var1 = template.substring(i1 + 2, i2); + String value1 = param.get(var1); + if (value1 == null || value1.trim().length() == 0) + { + // delete the whole element (line) + int i3 = template.lastIndexOf('\n', i1); + if (i3 < 0) + i3 = 0; + int i4 = template.indexOf('\n', i1); + if (i4 < 0) + i4 = template.length(); + + if (i < i3) + ss.append(template.substring(i, i3)); + i = i4; + } + else + { + ss.append(template.substring(i, i1)).append(value1); + i = i2 + 1; + } + } + + return ss.toString(); + } + + private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) + { + log.info("Building XML started"); + long t1 = System.currentTimeMillis(); + + template = expandRepeats(ctx, template, 1); + + Map mm = new HashMap<>(); + for (String s : ctx.getAttributeKeySet()) + mm.put(s, ctx.getAttribute(s)); + mm.put("operation", operation); + + StringBuilder ss = new StringBuilder(); + int i = 0; + while (i < template.length()) + { + int i1 = template.indexOf("${", i); + if (i1 < 0) + { + ss.append(template.substring(i)); + break; + } + + int i2 = template.indexOf('}', i1 + 2); + if (i2 < 0) + throw new RuntimeException("Template error: Matching } not found"); + + String var1 = template.substring(i1 + 2, i2); + String value1 = XmlUtil.getXml(mm, var1); + if (value1 == null || value1.trim().length() == 0) + { + // delete the whole element (line) + int i3 = template.lastIndexOf('\n', i1); + if (i3 < 0) + i3 = 0; + int i4 = template.indexOf('\n', i1); + if (i4 < 0) + i4 = template.length(); + + if (i < i3) + ss.append(template.substring(i, i3)); + i = i4; + } + else + { + ss.append(template.substring(i, i1)).append(value1); + i = i2 + 1; + } + } + + long t2 = System.currentTimeMillis(); + log.info("Building XML completed. Time: " + (t2 - t1)); + + return ss.toString(); + } + + private String expandRepeats(SvcLogicContext ctx, String template, int level) + { + StringBuilder newTemplate = new StringBuilder(); + int k = 0; + while (k < template.length()) + { + int i1 = template.indexOf("${repeat:", k); + if (i1 < 0) + { + newTemplate.append(template.substring(k)); + break; + } + + int i2 = template.indexOf(':', i1 + 9); + if (i2 < 0) + throw new RuntimeException( + "Template error: Context variable name followed by : is required after repeat"); + + // Find the closing }, store in i3 + int nn = 1; + int i3 = -1; + int i = i2; + while (nn > 0 && i < template.length()) + { + i3 = template.indexOf('}', i); + if (i3 < 0) + throw new RuntimeException("Template error: Matching } not found"); + int i32 = template.indexOf('{', i); + if (i32 >= 0 && i32 < i3) + { + nn++; + i = i32 + 1; + } + else + { + nn--; + i = i3 + 1; + } + } + + String var1 = template.substring(i1 + 9, i2); + String value1 = ctx.getAttribute(var1); + log.info(" " + var1 + ": " + value1); + int n = 0; + try + { + n = Integer.parseInt(value1); + } + catch (Exception e) + { + n = 0; + } + + newTemplate.append(template.substring(k, i1)); + + String rpt = template.substring(i2 + 1, i3); + + for (int ii = 0; ii < n; ii++) + { + String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]"); + newTemplate.append(ss); + } + + k = i3 + 1; + } + + if (k == 0) + return newTemplate.toString(); + + return expandRepeats(ctx, newTemplate.toString(), level + 1); + } + + private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) + { + try + { + Client client = Client.create(); + client.setConnectTimeout(5000); + WebResource webResource = client.resource(url); + + log.info("SENDING..............."); + log.info(xmlRequest); + + String authString = user + ":" + password; + byte[] authEncBytes = Base64.encode(authString); + String authStringEnc = new String(authEncBytes); + authString = "Basic " + authStringEnc; + + ClientResponse response = + webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post( + ClientResponse.class, xmlRequest); + + int code = response.getStatus(); + String message = null; + + log.info("RESPONSE..............."); + log.info("HTTP response code: " + code); + log.info("HTTP response message: " + message); + log.info(""); + + HttpResponse r = new HttpResponse(); + r.code = code; + r.message = message; + return r; + + } + catch (Exception e) + { + log.error("Error sending the request: ", e); + + HttpResponse r = new HttpResponse(); + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.message = e.getMessage(); + return r; + } + } + + private static class HttpResponse + { + + public int code; + public String message; + } + + private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) + { + ctx.setAttribute("error-code", String.valueOf(r.code)); + ctx.setAttribute("error-message", r.message); + + return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS; + } + + private String getStringBetweenQuotes(String string) + { + String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes"; + DebugLog.printAriDebug(fnName, "string="+string); + String retString = null; + int start = string.indexOf("\""); + int end = string.lastIndexOf("\""); + retString = string.substring(start+1, end); + DebugLog.printAriDebug(fnName, "retString="+retString); + return(retString); + } + + public static String _readFile(String fileName) + { + StringBuffer strBuff = new StringBuffer(); + String line; + try (BufferedReader in = new BufferedReader(new FileReader(fileName))) + { + while ((line = in.readLine()) != null) + { + strBuff.append(line+"\n"); + } + } + catch (IOException e) + { + System.out.println("Caught an IOException in method readFile(): e="+e.toString()); + } + return (strBuff.toString()); + } + + private String trimResponse(String response) + { + StringTokenizer line = new StringTokenizer(response, "\n"); + StringBuffer sb = new StringBuffer(); + boolean captureText = false; + while (line.hasMoreTokens()) + { + String token = line.nextToken(); + if (token.indexOf("") != -1) + captureText = false; + } + return(sb.toString()); + } + + public static void main (String args[]) throws Exception + { + Properties props = null; + System.out.println("*************************Hello*****************************"); + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String Get_config_template = _readFile ("/home/userID/data/Get_config_template"); + String Download_config_template = _readFile ("/home/userID/data/Download_config_template_2"); + String key = "GetCliRunningConfig"; + Map parameters = new HashMap(); + parameters.put("Host_ip_address", "000.00.000.00"); + parameters.put("User_name", "root"); + parameters.put("Password", "!bootstrap"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", Get_config_template); + + SvcLogicContext ctx = null; + System.out.println("*************************TRACE 1*****************************"); + cca.configure(key, parameters, ctx); + } + +} + diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/DebugLog.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/DebugLog.java new file mode 100644 index 000000000..15db56c90 --- /dev/null +++ b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/DebugLog.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.ccadaptor; + +import java.io.*; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + + +public class DebugLog +{ + private static String fileName = "/tmp/rt.log"; + + public static void main (String args[]) + { + DebugLog debugLog = new DebugLog(); + debugLog.printAriDebug("DebugLog", "The Message"); + } + + public static void printAriDebug(String fn, String messg) + { + String logMessg = getDateTime() +" " +fn +" " + messg; + appendToFile(logMessg +"\n"); + + } + + public static void printRTAriDebug(String fn, String messg) + { + // System.out.println (getDateTime() +" " +fn +" " + messg); + String logMessg = getDateTime() +" " +fn +" " + messg; + appendToFile(logMessg +"\n"); + } + public static String getDateTime() + { + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + // DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); + Date date = new Date(); + return dateFormat.format(date); + } + + public static void appendToFile (String dataToWrite) + { + String fn = "DebugLog.appendToFile"; + try + { + // First check to see if a file 'fileName' exist, if it does + // write to it. If it does not exist, don't write to it. + File tmpFile = new File(fileName); + if (tmpFile.exists()) + { + BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true)); + out.write(dataToWrite); + out.close(); + } + } + catch (IOException e) + { + DebugLog.printRTAriDebug (fn, "writeToFile() exception: " + e); + //System.err.println("writeToFile() exception: " + e); + e.printStackTrace(); + } + } + + public void outputStackTrace(Exception e) + { + String fn = "DebugLog.outputStackTrace"; + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw)); + String stackTrace = sw.toString(); + DebugLog.printRTAriDebug(fn, "Stack trace::: "+stackTrace); + } + + public static String getStackTraceString(Exception e) + { + String fn = "DebugLog.outputStackTrace"; + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw)); + String stackTrace = sw.toString(); + return(stackTrace); + } + +} + diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/EncryptionTool.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/EncryptionTool.java new file mode 100644 index 000000000..ad09d7faf --- /dev/null +++ b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/EncryptionTool.java @@ -0,0 +1,214 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.ccadaptor; + +import java.security.Provider; +import java.security.Provider.Service; +import java.security.Security; + +import javax.crypto.Cipher; + +import org.jasypt.contrib.org.apache.commons.codec_1_3.binary.Base64; +import org.jasypt.util.text.BasicTextEncryptor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class is used to encapsulate the encryption and decryption support in one place and to provide a utility to + * encrypt and decrypt data. + */ +public class EncryptionTool { + + /** + * This lock object is used ONLY if the singleton has not been set up. + */ + private static final Object lock = new Object(); + + /** + * The salt is used to initialize the PBE (password Based Encrpytion) algorithm. + */ + private static final byte[] DEFAULT_SALT = { + (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 + }; + + /** + * The prefix we insert onto any data we encrypt so that we can tell if it is encrpyted later and therefore decrypt + * it + */ + @SuppressWarnings("nls") + public static final String ENCRYPTED_VALUE_PREFIX = "enc:"; + + /** + * The instance of the encryption utility object + */ + private static EncryptionTool instance = null; + + /** + * The iteration count used to initialize the PBE algorithm and to generate the key spec + */ + private static final int ITERATION_COUNT = 20; + + /** + * The logger for this class. + */ + private static final Logger LOG = LoggerFactory.getLogger(EncryptionTool.class); + + /** + * The secret passphrase (PBE) that we use to perform encryption and decryption. The algorithm we are using is a + * symmetrical cipher. + */ + private static char[] secret = { + 'C', '_', 'z', 'l', '!', 'K', '!', '4', '?', 'O', 'z', 'E', 'K', 'E', '>', 'U', 'R', '/', '%', 'Y', '\\', 'f', + 'b', '"', 'e', 'n', '{', '"', 'l', 'U', 'F', '+', 'E', '\'', 'R', 'T', 'p', '1', 'V', '4', 'l', 'a', '9', 'w', + 'v', '5', 'Z', '#', 'i', 'V', '"', 'd', 'l', '!', 'L', 'M', 'g', 'L', 'Q', '{', 'v', 'v', 'K', 'V' + }; + + /** + * The algorithm to encrypt and decrpyt data is "Password (or passphrase) Based Encryption with Message Digest #5 + * and the Data Encryption Standard", i.e., PBEWithMD5AndDES. + */ + @SuppressWarnings("nls") + private static final String SECURITY_ALGORITHM = "PBEWITHMD5AND256BITAES";// "PBEWithMD5AndDES"; + + /** + * The decryption cipher object + */ + private Cipher decryptCipher = null; + + /** + * The encryption cipher object + */ + private Cipher encryptCipher = null; + + private BasicTextEncryptor encryptor; + + /** + * Get an instance of the EncryptionTool + * + * @return The encryption tool to be used + */ + public static final EncryptionTool getInstance() { + if (instance == null) { + synchronized (lock) { + if (instance == null) { + instance = new EncryptionTool(); + } + } + } + return instance; + } + + /** + * Create the EncryptionTool instance + */ + @SuppressWarnings("nls") + private EncryptionTool() { + // encryptor = new BasicTextEncryptor(); + // encryptor.setPassword(secret.toString()); + String out = "Found the following security algorithms:"; + for (Provider p : Security.getProviders()) { + for (Service s : p.getServices()) { + String algo = s.getAlgorithm(); + out += + String.format("\n -Algorithm [ %s ] in provider [ %s ] and service [ %s ]", algo, p.getName(), + s.getClassName()); + } + } + LOG.debug(out); + } + + /** + * Decrypt the provided encrypted text + * + * @param cipherText + * THe cipher text to be decrypted. If the ciphertext is not encrypted, then it is returned as is. + * @return the clear test of the (possibly) encrypted value. The original value if the string is not encrypted. + */ + @SuppressWarnings("nls") + public synchronized String decrypt(String cipherText) { + if (isEncrypted(cipherText)) { + String encValue = cipherText.substring(ENCRYPTED_VALUE_PREFIX.length()); + // return encryptor.decrypt(encValue); + byte[] plainByte = Base64.decodeBase64(encValue.getBytes()); + byte[] decryptByte = xorWithSecret(plainByte); + return new String(decryptByte); + } else { + return cipherText; + } + + } + + /** + * Encrypt the provided clear text + * + * @param clearText + * The clear text to be encrypted + * @return the encrypted text. If the clear text is empty (null or zero length), then an empty string is returned. + * If the clear text is already encrypted, it is not encrypted again and is returned as is. Otherwise, the + * clear text is encrypted and returned. + */ + @SuppressWarnings("nls") + public synchronized String encrypt(String clearText) { + if (clearText != null) { + byte[] encByte = xorWithSecret(clearText.getBytes()); + String encryptedValue = new String(Base64.encodeBase64(encByte)); + return ENCRYPTED_VALUE_PREFIX + encryptedValue; + } else { + return null; + } + } + + /** + * Is a value encrypted? A value is considered to be encrypted if it begins with the + * {@linkplain #ENCRYPTED_VALUE_PREFIX encrypted value prefix}. + * + * @param value + * the value to check. + * @return true/false; + */ + private static boolean isEncrypted(final String value) { + return value != null && value.startsWith(ENCRYPTED_VALUE_PREFIX); + } + + /** + * XORs the input byte array with the secret key, padding 0x0 to the end of the secret key if the input is longer + * and returns a byte array the same size as input + * + * @param inp + * The byte array to be XORed with secret + * @return A byte array the same size as inp or null if input is null. + */ + private byte[] xorWithSecret(byte[] inp) { + if (inp == null) { + return null; + } + + byte[] secretBytes = new String(secret).getBytes(); + int size = inp.length; + + byte[] out = new byte[size]; + for (int i = 0; i < size; i++) { + out[i] = (byte) ((inp[i]) ^ (secretBytes[i % secretBytes.length])); + } + return out; + } + +} diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/SshJcraftWrapper.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/SshJcraftWrapper.java new file mode 100644 index 000000000..eb9e28fa2 --- /dev/null +++ b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/SshJcraftWrapper.java @@ -0,0 +1,1277 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.ccadaptor; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.*; +import java.util.*; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import com.jcraft.jsch.*; + +public class SshJcraftWrapper +{ + + private String debugLogFileName = "/tmp/sshJcraftWrapperDebug"; + InputStream inputStream = null; + OutputStream outputStream = null; + private TelnetListener listener = null; + private String routerLogFileName = null; + DebugLog debugLog = new DebugLog(); + private String host = null; + private String RouterName = null; + private int BUFFER_SIZE = 512000; + // private int BUFFER_SIZE = 4000000; + private DataInputStream dis = null; + private BufferedReader reader = null; + char[] charBuffer = new char[BUFFER_SIZE]; + private BufferedWriter out = null; + private File _tmpFile = null; + private JSch jsch = null; + private Session session = null; + private Channel channel = null; + private String tId = ""; + private String aggregatedReceivedString = ""; + private File extraDebugFile = new File("/tmp/sshJcraftWrapperDEBUG"); + private String routerCmdType = "XML"; + private String routerFileName = null; + private File jcraftReadSwConfigFileFromDisk = new File("/tmp/jcraftReadSwConfigFileFromDisk"); + private String equipNameCode = null; + private String hostName = null; + private String userName = null; + private String passWord = null; + private StringBuffer charactersFromBufferFlush = new StringBuffer(); + private Runtime runtime = Runtime.getRuntime(); + private DebugLog dbLog = new DebugLog(); + + public void SshJcraftWrapper() + { + String fn = "SshJcraftWrapper.SshJcraftWrapper"; + debugLog.printRTAriDebug (fn, "SshJcraftWrapper has been instantated"); + routerLogFileName = "/tmp/" +host; + this.host = host; + } + + public void connect (String hostname, String username, String password, String prompt, int timeOut) throws IOException + { + String fn = "SshJcraftWrapper.connect"; + jsch = new JSch(); + debugLog.printRTAriDebug (fn, "Attempting to connect to "+hostname +" username="+username +" password="+password + " prompt='"+prompt +"' timeOut="+timeOut); + debugLog.printRTAriDebug (fn, "Trace A"); + RouterName = hostname; + hostName = hostname; + userName = username; + passWord = password; + try + { + session = jsch.getSession(username, hostname, 22); + UserInfo ui = new MyUserInfo(); + session.setPassword(password); + session.setUserInfo(ui); + session.connect(timeOut); + channel = session.openChannel("shell"); + session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!! + ((ChannelShell)channel).setPtyType("vt102"); + inputStream = channel.getInputStream(); + dis = new DataInputStream(inputStream); + reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE); + channel.connect(); + debugLog.printRTAriDebug (fn, "Successfully connected."); + debugLog.printRTAriDebug (fn, "Flushing input buffer"); + try + { + receiveUntil(prompt, 3000, "No cmd was sent, just waiting"); + } + catch (Exception e) + { + debugLog.printRTAriDebug (fn, "Caught an Exception: Nothing to flush out."); + } + } + catch (Exception e) + { + debugLog.printRTAriDebug (fn, "Caught an Exception. e="+e); + // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e); + throw new IOException(e.toString()); + } + } + + // User specifies the port number. + public void connect (String hostname, String username, String password, String prompt, int timeOut, int portNum) throws IOException + { + String fn = "SshJcraftWrapper.connect"; + debugLog.printRTAriDebug (fn, ":Attempting to connect to "+hostname +" username="+username +" password="+password + " prompt='"+prompt +"' timeOut="+timeOut +" portNum="+portNum); + RouterName = hostname; + hostName = hostname; + userName = username; + passWord = password; + RouterName = hostname; + jsch = new JSch(); + try + { + session = jsch.getSession(username, hostname, portNum); + UserInfo ui = new MyUserInfo(); + session.setPassword(password); + session.setUserInfo(ui); + session.setConfig("StrictHostKeyChecking", "no"); + debugLog.printRTAriDebug (fn, ":StrictHostKeyChecking set to 'no'"); + + session.connect(timeOut); + session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!! + channel = session.openChannel("shell"); + ((ChannelShell)channel).setPtyType("vt102"); + inputStream = channel.getInputStream(); + dis = new DataInputStream(inputStream); + reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE); + channel.connect(); + debugLog.printRTAriDebug (fn, ":Successfully connected."); + debugLog.printRTAriDebug (fn, ":Flushing input buffer"); + try + { + if (prompt.equals("]]>]]>")) + receiveUntil("]]>]]>", 10000, "No cmd was sent, just waiting"); + else + receiveUntil(":~#", 5000, "No cmd was sent, just waiting"); + } + catch (Exception e) + { + debugLog.printRTAriDebug (fn, "Caught an Exception::: Nothing to flush out."); + } + } + catch (Exception e) + { + debugLog.printRTAriDebug (fn, ":Caught an Exception. e="+e); + dbLog.outputStackTrace(e); + + // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e); + throw new IOException(e.toString()); + } + } + + + public String receiveUntil (String delimeters, int timeout, String cmdThatWasSent) throws TimedOutException, IOException + { + String fn = "SshJcraftWrapper.receiveUntil"; + boolean match = false; + boolean cliPromptCmd = false; + StringBuffer sb2 = new StringBuffer(); + StringBuffer sbReceive = new StringBuffer(); + debugLog.printRTAriDebug (fn, "delimeters='"+delimeters +"' timeout="+timeout +" cmdThatWasSent='"+cmdThatWasSent +"'"); + appendToFile(debugLogFileName, fn +" delimeters='"+delimeters +"' timeout="+timeout +" cmdThatWasSent='"+cmdThatWasSent +"'\n"); + String CmdThatWasSent = removeWhiteSpaceAndNewLineCharactersAroundString(cmdThatWasSent); + int readCounts = 0; + aggregatedReceivedString = ""; + + long deadline = new Date().getTime() + timeout; + try + { + session.setTimeout(timeout); // This is the socket timeout value. + while (!match) + { + if(new Date().getTime() > deadline) + { + debugLog.printRTAriDebug (fn, "Throwing a TimedOutException: time in routine has exceed our deadline: RouterName:"+RouterName +" CmdThatWasSent="+ CmdThatWasSent); + throw new TimedOutException("Timeout: time in routine has exceed our deadline"); + } + try + { + Thread.sleep(500); + } + catch (java.lang.InterruptedException ee) + { + boolean ignore = true; + } + int len = reader.read(charBuffer, 0, BUFFER_SIZE); + appendToFile(debugLogFileName, fn +" After reader.read cmd: len="+len +"\n"); + if (len <= 0) + { + debugLog.printRTAriDebug (fn, "Reader read "+len +" bytes. Looks like we timed out, router="+RouterName); + throw new TimedOutException ("Received a SocketTimeoutException router="+RouterName); + } + if (!cliPromptCmd) + { + if (cmdThatWasSent.indexOf("IOS_XR_uploadedSwConfigCmd") != -1) + { + if (out == null) + { + // This is a IOS XR sw config file. We will write it to the disk. + timeout = timeout * 2; + deadline = new Date().getTime() + timeout; + debugLog.printRTAriDebug (fn, "IOS XR upload for software config: timeout="+timeout); + StringTokenizer st = new StringTokenizer(cmdThatWasSent); + st.nextToken(); + routerFileName = st.nextToken(); + out = new BufferedWriter(new FileWriter(routerFileName)); + routerLogFileName = "/tmp/"+RouterName; + _tmpFile = new File(routerLogFileName); + debugLog.printRTAriDebug (fn, "Will write the swConfigFile to disk, routerFileName="+routerFileName); + } + int c; + out.write(charBuffer, 0, len); + out.flush(); + appendToFile(debugLogFileName, fn +" Wrote "+len +" bytes to the disk\n"); + if (_tmpFile.exists()) + appendToRouterFile(routerLogFileName, len); + match = checkIfReceivedStringMatchesDelimeter(len, "\nXML>"); + if (match == true) + { + out.flush(); + out.close(); + out = null; + return null; + } + } + else + { + readCounts ++; + appendToFile(debugLogFileName, fn +" readCounts="+readCounts +" Reader read "+len +" of data\n"); + int c; + sb2.setLength(0); + for(int i=0; i") != -1) + { + debugLog.printRTAriDebug (fn, "Found our prompt"); + match = true; + break; + } + } + } + } + catch (JSchException e) + { + debugLog.printRTAriDebug (fn, "Caught an JSchException e="+e.toString()); + dbLog.outputStackTrace(e); + throw new TimedOutException (e.toString()); + } + catch (IOException ee) + { + debugLog.printRTAriDebug (fn, "Caught an IOException: ee="+ee.toString()); + dbLog.outputStackTrace(ee); + throw new TimedOutException (ee.toString()); + } + String result = stripOffCmdFromRouterResponse(sbReceive.toString()); + debugLog.printRTAriDebug (fn, "Leaving method successfully"); + return (result); + } + + public boolean checkIfReceivedStringMatchesDelimeter(String delimeters, String receivedString, String cmdThatWasSent) + { + // The delimeters are in a '|' seperated string. Return true on the first match. + String fn = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter"; + appendToFile(debugLogFileName, fn +" Entered: delimeters='"+delimeters +" cmdThatWasSent='"+cmdThatWasSent +"' receivedString='"+receivedString +"'\n"); + StringTokenizer st = new StringTokenizer(delimeters, "|"); + + if ((delimeters.indexOf("#$") != -1) || (routerCmdType.equals("CLI"))) // This would be an IOS XR, CLI command. + { + int x = receivedString.lastIndexOf("#"); + int y = receivedString.length() - 1; + appendToFile(debugLogFileName, fn +" IOS XR, CLI command\n"); + if (extraDebugFile.exists()) + appendToFile(debugLogFileName, fn +" :::cmdThatWasSent='"+cmdThatWasSent +"' x="+x +" y="+y +"\n"); + if ((x != -1) && (y == x)) + return(true); + else + return(false); + } + if (cmdThatWasSent.indexOf("show config") != -1) + { + appendToFile(debugLogFileName, fn +"In the block for 'show config'\n"); + while (st.hasMoreTokens()) + { + String delimeter = st.nextToken(); + // Make sure we don't get faked out by a response of " #". + // Proc #0 + // # signaling-local-address ipv6 FD00:F4D5:EA06:1::110:136:254 + // LAAR2# + int x = receivedString.lastIndexOf(delimeter); + if ((receivedString.lastIndexOf(delimeter) != -1) && (receivedString.lastIndexOf(" #") != x-1)) + { + appendToFile(debugLogFileName, fn +"receivedString=\n'" +receivedString +"'\n"); + appendToFile(debugLogFileName, fn +"Returning true for the 'show config' command. We found our real delmeter. \n\n"); + return (true); + } + } + } + else + { + aggregatedReceivedString = aggregatedReceivedString + receivedString; + _appendToFile ("/tmp/aggregatedReceivedString.debug", aggregatedReceivedString); + + while (st.hasMoreTokens()) + { + String delimeter = st.nextToken(); + appendToFile(debugLogFileName, fn +" Looking for an delimeter of:'"+delimeter+"'\n"); + appendToFile(debugLogFileName, fn +" receivedString='"+receivedString); + if (aggregatedReceivedString.indexOf(delimeter) != -1) + { + debugLog.printRTAriDebug (fn, "Found our delimeter, which was: '"+delimeter +"'"); + aggregatedReceivedString = ""; + return (true); + } + } + } + return (false); + } + + public boolean checkIfReceivedStringMatchesDelimeter(int len, String delimeter) + { + String fnName = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter:::"; + int x; + int c; + String str = null; + + if (jcraftReadSwConfigFileFromDisk()) + { + DebugLog.printAriDebug(fnName, "jcraftReadSwConfigFileFromDisk block"); + File fileName = new File(routerFileName); + appendToFile(debugLogFileName, fnName +" jcraftReadSwConfigFileFromDisk::: Will read the tail end of the file from the disk"); + try + { + str = getLastFewLinesOfFile(fileName, 3); + } + catch (IOException e) + { + DebugLog.printAriDebug(fnName, "Caught an Exception, e="+e); + dbLog.outputStackTrace(e); + e.printStackTrace(); + } + } + else + { + // DebugLog.printAriDebug(fnName, "TRACE 1: ******************************"); + // When looking at the end of the charBuffer, don't include any linefeeds or spaces. We only want to make the smallest string possible. + for(x=len-1; x>=0; x--) + { + c = charBuffer[x]; + if (extraDebugFile.exists()) + appendToFile(debugLogFileName, fnName +" x="+x +" c="+c +"\n"); + if ((c != 10) && (c != 32)) // Not a line feed nor a space. + break; + } + if ((x+1 - 13) >= 0) + { + str = new String (charBuffer, (x+1-13), 13); + appendToFile(debugLogFileName, fnName +" str:'"+str +"'\n"); + } + else + { + File fileName = new File(routerFileName); + appendToFile(debugLogFileName, fnName +" Will read the tail end of the file from the disk, x="+x +" len="+len +" str::'"+str +"' routerFileName='" +routerFileName +"'\n"); + DebugLog.printAriDebug(fnName, "Will read the tail end of the file from the disk, x="+x +" len="+len +" str::'"+str +"' routerFileName='" +routerFileName +"'"); + try + { + str = getLastFewLinesOfFile(fileName, 3); + } + catch (IOException e) + { + DebugLog.printAriDebug(fnName, "Caught an Exception, e="+e); + dbLog.outputStackTrace(e); + e.printStackTrace(); + } + } + } + + if (str.indexOf(delimeter) != -1) + { + DebugLog.printAriDebug(fnName, "str in break is:'"+str +"'" +" delimeter='" +delimeter +"'"); + appendToFile(debugLogFileName, fnName +" str in break is:'"+str +" delimeter='" +delimeter +"'" +"'\n"); + return(true); + } + else + { + appendToFile(debugLogFileName, fnName +" Returning false"); + return(false); + } + + } + + public void closeConnection() + { + String fn = "SshJcraftWrapper.closeConnection"; + debugLog.printRTAriDebug (fn, "Executing the closeConnection...."); + inputStream = null; + outputStream = null; + dis = null; + charBuffer = null; + session.disconnect(); + session = null; + } + + public void send (String cmd) throws IOException + { + String fn = "SshJcraftWrapper.send"; + OutputStream out = channel.getOutputStream(); + DataOutputStream dos = new DataOutputStream(out); + + if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r')) + cmd += "\n"; + int length = cmd.length(); + int i = -1; + int nchars = 300000; + int ncharsTotalSent = 0; + int ncharsSent = 0; + + appendToFile(debugLogFileName, fn+": Sending: '"+cmd ); + // debugLog.printRTAriDebug (fn, "cmd = "+cmd); + debugLog.printRTAriDebug (fn, "Length of cmd is:" +length); // 2,937,706 + try + { + if (length > 600000) + { + int timeout = 9000; + for (i=0; i\n"); + out.write(dataToWrite.toString()); + out.close(); + } + } + } + catch (IOException e) + { + System.err.println("writeToFile() exception: " + e); + e.printStackTrace(); + } + } + + public void appendToRouterFile (String fileName, int len) + { + String fnName = "SshJcraftWrapper.appendToFile"; + // debugLog.printRTAriDebug (fnName, "Entered.... len="+len); + try + { + // First check to see if a file 'fileName' exist, if it does + // write to it. If it does not exist, don't write to it. + File tmpFile = new File(fileName); + // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true))) + if (tmpFile.exists()) + { + BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true)); + // out.write("\n"); + out.write(charBuffer, 0, len); + out.close(); + } + } + catch (IOException e) + { + System.err.println("writeToFile() exception: " + e); + e.printStackTrace(); + } + } + + public String removeWhiteSpaceAndNewLineCharactersAroundString(String str) + { + if (str != null) + { + StringTokenizer strTok = new StringTokenizer(str, "\n"); + StringBuffer sb = new StringBuffer(); + + while (strTok.hasMoreTokens()) + { + String line = strTok.nextToken(); + sb.append(line); + } + return (sb.toString().trim()); + } + else + return(str); + } + + public String stripOffCmdFromRouterResponse(String routerResponse) + { + String fn = "SshJcraftWrapper.stripOffCmdFromRouterResponse"; + // appendToFile(debugLogFileName, fn+": routerResponse='"+routerResponse +"'\n"); + + // The session of SSH will echo the command sent to the router, in the router's response. + // Since all our commands are terminated by a '\n', strip off the first line + // of the response from the router. This first line contains the orginal command. + + StringTokenizer rr = new StringTokenizer(routerResponse, "\n"); + StringBuffer sb = new StringBuffer(); + + int numTokens = rr.countTokens(); + // debugLog.printRTAriDebug (fn, "Number of lines in the response from the router is:" +numTokens); + if (numTokens > 1) + { + rr.nextToken(); //Skip the first line. + while (rr.hasMoreTokens()) + { + sb.append(rr.nextToken()+'\n'); + } + } + return (sb.toString()); + } + + public void setRouterCommandType(String type) + { + String fn = "SshJcraftWrapper.setRouterCommandType"; + this.routerCmdType = type; + debugLog.printRTAriDebug (fn, "Setting routerCmdType to a value of '"+type +"'"); + } + + public String getLastFewLinesOfFile(File file, int linesToRead) throws FileNotFoundException, IOException + { + String fn = "SshJcraftWrapper.getLastFewLinesOfFile"; + RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); + int lines = 0; + StringBuilder builder = new StringBuilder(); + String tail = ""; + long length = file.length(); + length--; + randomAccessFile.seek(length); + for(long seek = length; seek >= 0; --seek) + { + randomAccessFile.seek(seek); + char c = (char)randomAccessFile.read(); + builder.append(c); + if(c == '\n') + { + builder = builder.reverse(); + // System.out.println(builder.toString()); + tail = builder.toString() + tail; + lines++; + builder.setLength(0); + if (lines == linesToRead) + { + break; + } + } + } + randomAccessFile.close(); + if(!jcraftReadSwConfigFileFromDisk()) + debugLog.printRTAriDebug (fn, "tail='"+tail +"'"); + appendToFile(debugLogFileName, "tail='"+tail +"'\n"); + return tail; + } + + public boolean jcraftReadSwConfigFileFromDisk() + { + if (jcraftReadSwConfigFileFromDisk.exists()) + return(true); + else + return(false); + } + + public String getEquipNameCode() + { + return (equipNameCode); + + } + + public void setEquipNameCode(String equipNameCode) + { + this.equipNameCode = equipNameCode; + } + + public String getRouterName() + { + return(RouterName); + } + + // Routine does reads until it has read 'nchars' or times out. + public void receiveUntilBufferFlush (int ncharsSent, int timeout, String message) throws TimedOutException, IOException + { + String fn = "SshJcraftWrapper.receiveUntilBufferFlush"; + StringBuffer sb2 = new StringBuffer(); + StringBuffer sbReceive = new StringBuffer(); + debugLog.printRTAriDebug (fn, "ncharsSent="+ncharsSent+" timeout="+timeout +" "+message); + int ncharsTotalReceived = 0; + int ncharsRead = 0; + boolean flag = false; + charactersFromBufferFlush.setLength(0); + + long deadline = new Date().getTime() + timeout; + logMemoryUsage(); + try + { + session.setTimeout(timeout); // This is the socket timeout value. + while (true) + { + if(new Date().getTime() > deadline) + { + debugLog.printRTAriDebug (fn, "Throwing a TimedOutException: time in routine has exceed our deadline: ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived); + flag = true; + throw new TimedOutException("Timeout: time in routine has exceed our deadline"); + } + ncharsRead = reader.read(charBuffer, 0, BUFFER_SIZE); + if (listener != null) + listener.receivedString(String.copyValueOf(charBuffer,0,ncharsRead)); + appendToRouterFile("/tmp/"+RouterName, ncharsRead); + ncharsTotalReceived = ncharsTotalReceived + ncharsRead; + // debugLog.printRTAriDebug (fn, "::ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived +" ncharsRead="+ncharsRead); + if (ncharsTotalReceived >= ncharsSent) + { + debugLog.printRTAriDebug (fn, "Received the correct number of characters, ncharsSent="+ncharsSent +" ncharsTotalReceived="+ncharsTotalReceived); + logMemoryUsage(); + return; + } + } + } + catch (JSchException e) + { + debugLog.printRTAriDebug (fn, "Caught an JSchException e="+e.toString()); + debugLog.printRTAriDebug (fn, "ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived +" ncharsRead="+ncharsRead); + throw new TimedOutException (e.toString()); + } + } + + public String getHostName() + { + return(hostName); + } + + public String getUserName() + { + return(userName); + } + + public String getPassWord() + { + return(passWord); + } + + public void sftpPut(String sourcePath, String destDirectory) throws IOException + { + String fn = "SshJcraftWrapper.sftp"; + try + { + Session sftpSession = jsch.getSession(userName, hostName, 22); + UserInfo ui = new MyUserInfo(); + sftpSession.setPassword(passWord); + sftpSession.setUserInfo(ui); + sftpSession.connect(30*1000); + debugLog.printRTAriDebug (fn, "Opening up an sftp channel...."); + ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp"); + debugLog.printRTAriDebug (fn, "Connecting...."); + sftp.connect(); + debugLog.printRTAriDebug (fn, "Sending "+sourcePath +" --> "+destDirectory); + sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE); + debugLog.printRTAriDebug (fn, "Sent successfully"); + sftpSession.disconnect(); + } + catch (Exception e) + { + debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e); + // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); + throw new IOException(e.toString()); + } + } + + + + public void SftpPut(String stringOfData, String fullPathDest) throws IOException + { + String fn = "SshJcraftWrapper.Sftp"; + try + { + Session sftpSession = jsch.getSession(userName, hostName, 22); + UserInfo ui = new MyUserInfo(); + sftpSession.setPassword(passWord); + sftpSession.setUserInfo(ui); + sftpSession.connect(30*1000); + debugLog.printRTAriDebug (fn, "Opening up an sftp channel...."); + ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp"); + debugLog.printRTAriDebug (fn, "Connecting...."); + sftp.connect(); + InputStream is = new ByteArrayInputStream(stringOfData.getBytes()); + debugLog.printRTAriDebug (fn, "Sending stringOfData --> "+fullPathDest); + sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE); + debugLog.printRTAriDebug (fn, "Sent successfully"); + sftpSession.disconnect(); + } + catch (Exception e) + { + debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e); + // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); + throw new IOException(e.toString()); + } + } + + public String sftpGet(String fullFilePathName) throws IOException + { + String fn = "SshJcraftWrapper.Sftp"; + try + { + Session sftpSession = jsch.getSession(userName, hostName, 22); + UserInfo ui = new MyUserInfo(); + sftpSession.setPassword(passWord); + sftpSession.setUserInfo(ui); + sftpSession.connect(30*1000); + debugLog.printRTAriDebug (fn, "Opening up an sftp channel...."); + ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp"); + debugLog.printRTAriDebug (fn, "Connecting...."); + sftp.connect(); + InputStream in = null; + in = sftp.get(fullFilePathName); + String sftpFileString = readInputStreamAsString(in); + debugLog.printRTAriDebug (fn, "Retreived successfully"); + // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString); + sftpSession.disconnect(); + return(sftpFileString); + } + catch (Exception e) + { + debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e); + // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); + throw new IOException(e.toString()); + } + } + + public static String readInputStreamAsString(InputStream in) throws IOException + { + BufferedInputStream bis = new BufferedInputStream(in); + ByteArrayOutputStream buf = new ByteArrayOutputStream(); + int result = bis.read(); + while(result != -1) + { + byte b = (byte)result; + buf.write(b); + result = bis.read(); + } + return buf.toString(); + } + + + public void logMemoryUsage() + { + String fn = "SshJcraftWrapper.logMemoryUsage"; + int mb = 1024*1024; + long usedMemory; + long maxMemoryAdvailable; + long memoryLetfOnHeap; + maxMemoryAdvailable = (runtime.maxMemory() / mb); + usedMemory = ((runtime.totalMemory()/mb) - (runtime.freeMemory()/mb)); + memoryLetfOnHeap = maxMemoryAdvailable - usedMemory; + DebugLog.printAriDebug(fn, "maxMemoryAdvailable="+maxMemoryAdvailable +" usedMemory="+usedMemory +" memoryLetfOnHeap="+memoryLetfOnHeap); + } + + // ---------------------------------------------------------------------------- + // ---------------------------------------------------------------------------- + // ---------------------------------------------------------------------------- + // ---------------------------------------------------------------------------- + + + // User specifies the port number, and the subsystem + public void connect (String hostname, String username, String password, String prompt, int timeOut, int portNum, String subsystem) throws IOException + { + String fn = "SshJcraftWrapper.connect"; + + debugLog.printRTAriDebug (fn, ":::Attempting to connect to "+hostname +" username="+username +" password="+password + " prompt='"+prompt +"' timeOut="+timeOut +" portNum="+portNum +" subsystem="+subsystem); + RouterName = hostname; + jsch = new JSch(); + try + { + session = jsch.getSession(username, hostname, portNum); + UserInfo ui = new MyUserInfo(); + session.setPassword(password); + session.setUserInfo(ui); + session.setConfig("StrictHostKeyChecking", "no"); + session.connect(timeOut); + session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!! + channel = session.openChannel("subsystem"); + ((ChannelSubsystem)channel).setSubsystem(subsystem); + // ((ChannelSubsystem)channel).setPtyType("vt102"); + ((ChannelSubsystem)channel).setPty(true); + + inputStream = channel.getInputStream(); + dis = new DataInputStream(inputStream); + reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE); + channel.connect(); + debugLog.printRTAriDebug (fn, "Successfully connected."); + debugLog.printRTAriDebug (fn, "Five second sleep...."); + try { Thread.sleep(5000); } catch (java.lang.InterruptedException ee) { boolean ignore = true; } + } + catch (Exception e) + { + debugLog.printRTAriDebug (fn, "Caught an Exception. e="+e); + throw new IOException(e.toString()); + } + } + + public void connect (String hostName, String username, String password, int portNumber) throws IOException + { + String fn = "SshJcraftWrapper.connect"; + jsch = new JSch(); + debugLog.printRTAriDebug (fn, "::Attempting to connect to "+hostName +" username="+username +" password="+password +" portNumber="+portNumber); + debugLog.printRTAriDebug (fn, "Trace C"); + RouterName = hostName; + this.hostName = hostName; + userName = username; + passWord = password; + try + { + java.util.Properties config = new java.util.Properties(); + config.put("StrictHostKeyChecking", "no"); + session = jsch.getSession(username, hostName, 22); + // session = jsch.getSession(username, hostName, portNumber); + UserInfo ui = new MyUserInfo(); + session.setConfig(config); + session.setPassword(password); + session.setUserInfo(ui); + session.connect(30000); + channel = session.openChannel("shell"); + session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!! + ((ChannelShell)channel).setPtyType("vt102"); + inputStream = channel.getInputStream(); + dis = new DataInputStream(inputStream); + reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE); + channel.connect(); + debugLog.printRTAriDebug (fn, "::Successfully connected."); + debugLog.printRTAriDebug (fn, "::Flushing input buffer"); + try + { + receiveUntil(":~#", 9000, "No cmd was sent, just waiting, but we can stop on a '~#'"); + } + catch (Exception e) + { + debugLog.printRTAriDebug (fn, "Caught an Exception::: Nothing to flush out."); + } + + } + catch (Exception e) + { + debugLog.printRTAriDebug (fn, "Caught an Exception. e="+e); + // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostName +" "+e); + throw new IOException(e.toString()); + } + } + + + public void put(String sourcePath, String destDirectory) throws IOException + { + String fn = "SshJcraftWrapper.sftp"; + try + { + Session sftpSession = jsch.getSession(userName, hostName, 22); + UserInfo ui = new MyUserInfo(); + sftpSession.setPassword(passWord); + sftpSession.setUserInfo(ui); + sftpSession.connect(30*1000); + debugLog.printRTAriDebug (fn, "Opening up an sftp channel...."); + ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp"); + debugLog.printRTAriDebug (fn, "Connecting...."); + sftp.connect(); + debugLog.printRTAriDebug (fn, "Sending "+sourcePath +" --> "+destDirectory); + sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE); + debugLog.printRTAriDebug (fn, "Sent successfully"); + sftpSession.disconnect(); + } + catch (Exception e) + { + debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e); + // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); + throw new IOException(e.toString()); + } + } + + public void put(InputStream is, String fullPathDest, String hostName, String userName, String passWord) throws IOException + { + String fn = "SshJcraftWrapper.put"; + Session sftpSession = null; + try + { + debugLog.printRTAriDebug (fn, "userName="+userName +" hostName="+hostName +" passWord="+passWord); + jsch = new JSch(); + java.util.Properties config = new java.util.Properties(); + config.put("StrictHostKeyChecking", "no"); + sftpSession = jsch.getSession(userName, hostName, 22); + UserInfo ui = new MyUserInfo(); + sftpSession.setPassword(passWord); + sftpSession.setUserInfo(ui); + sftpSession.setConfig(config); + sftpSession.connect(30*1000); + debugLog.printRTAriDebug (fn, "Opening up an sftp channel...."); + ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp"); + debugLog.printRTAriDebug (fn, "Connecting...."); + sftp.connect(); + String oldFiles = fullPathDest +"*"; + debugLog.printRTAriDebug (fn, "Deleting old files --> "+oldFiles); + try{ + sftp.rm(oldFiles); + debugLog.printRTAriDebug (fn, "Sending stringOfData --> "+fullPathDest); + } + catch(SftpException sft){ + String exp = "No such file"; + if(sft.getMessage()!=null && sft.getMessage().contains(exp)) + debugLog.printRTAriDebug (fn, "No files found -- Continue"); + else{ + debugLog.printRTAriDebug (fn, "Exception while sftp.rm " + sft.getMessage()); + sft.printStackTrace(); + throw sft; + } + } + sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE); + debugLog.printRTAriDebug (fn, "Sent successfully"); + sftpSession.disconnect(); + sftpSession = null; + } + catch (Exception e) + { + debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e); + sftpSession.disconnect(); + sftpSession = null; + // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); + throw new IOException(e.toString()); + } + } + + + public String get(String fullFilePathName, String hostName, String userName, String passWord) throws IOException + { + String fn = "SshJcraftWrapper.get"; + Session sftpSession = null; + try + { + debugLog.printRTAriDebug (fn, "userName="+userName +" hostName="+hostName +" passWord="+passWord); + jsch = new JSch(); + sftpSession = jsch.getSession(userName, hostName, 22); + java.util.Properties config = new java.util.Properties(); + config.put("StrictHostKeyChecking", "no"); + UserInfo ui = new MyUserInfo(); + sftpSession.setPassword(passWord); + sftpSession.setUserInfo(ui); + sftpSession.setConfig(config); + sftpSession.connect(30*1000); + debugLog.printRTAriDebug (fn, "Opening up an sftp channel...."); + ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp"); + debugLog.printRTAriDebug (fn, "Connecting...."); + sftp.connect(); + InputStream in = null; + in = sftp.get(fullFilePathName); + String sftpFileString = readInputStreamAsString(in); + debugLog.printRTAriDebug (fn, "Retreived successfully"); + // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString); + sftpSession.disconnect(); + sftpSession = null; + return(sftpFileString); + } + catch (Exception e) + { + debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e); + sftpSession.disconnect(); + sftpSession = null; + // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); + throw new IOException(e.toString()); + } + } + + public String send(String cmd, String delimiter) throws IOException + { + String fn = "SshJcraftWrapper.send"; + OutputStream out = channel.getOutputStream(); + DataOutputStream dos = new DataOutputStream(out); + + if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r')) + cmd += "\n"; + int length = cmd.length(); + int i = -1; + int nchars = 300000; + int ncharsTotalSent = 0; + int ncharsSent = 0; + + debugLog.printRTAriDebug (fn, "Length of cmd is:" +length); // 2,937,706 + debugLog.printRTAriDebug (fn, "Length of cmd is:" +length); // 2,937,706 + try + { + if (length > 600000) + { + int timeout = 9000; + for (i=0; i varmap, String var) + { + Object o = createStructure(varmap, var); + return generateXml(o, 0); + } + + private static Object createStructure(Map flatmap, String var) + { + if (flatmap.containsKey(var)) + return flatmap.get(var); + + Map mm = new HashMap<>(); + for (String k : flatmap.keySet()) + if (k.startsWith(var + ".")) + { + int i1 = k.indexOf('.', var.length() + 1); + int i2 = k.indexOf('[', var.length() + 1); + int i3 = k.length(); + if (i1 > 0 && i1 < i3) + i3 = i1; + if (i2 > 0 && i2 < i3) + i3 = i2; + String k1 = k.substring(var.length() + 1, i3); + String var1 = k.substring(0, i3); + if (!mm.containsKey(k1)) + { + Object str = createStructure(flatmap, var1); + if (str != null && (!(str instanceof String) || ((String) str).trim().length() > 0)) + mm.put(k1, str); + } + } + if (!mm.isEmpty()) + return mm; + + boolean arrayFound = false; + for (String k : flatmap.keySet()) + if (k.startsWith(var + "[")) + { + arrayFound = true; + break; + } + + if (arrayFound) + { + List ll = new ArrayList<>(); + + int length = Integer.MAX_VALUE; + String lengthStr = flatmap.get(var + "_length"); + if (lengthStr != null) + { + try + { + length = Integer.parseInt(lengthStr); + } + catch (Exception e) + { + log.warn("Invalid number for " + var + "_length:" + lengthStr); + } + } + + for (int i = 0; i < length; i++) + { + Object v = createStructure(flatmap, var + '[' + i + ']'); + if (v == null) + break; + ll.add(v); + } + + if (!ll.isEmpty()) + return ll; + } + + return null; + } + + @SuppressWarnings("unchecked") + private static String generateXml(Object o, int indent) + { + if (o == null) + return null; + + if (o instanceof String) + return (String) o; + + if (o instanceof Map) + { + StringBuilder ss = new StringBuilder(); + Map mm = (Map) o; + for (String k : mm.keySet()) + { + Object v = mm.get(k); + if (v instanceof String) + { + ss.append(pad(indent)).append('<').append(k).append('>'); + ss.append(v); + ss.append("').append('\n'); + } + else if (v instanceof Map) + { + ss.append(pad(indent)).append('<').append(k).append('>').append('\n'); + ss.append(generateXml(v, indent + 1)); + ss.append(pad(indent)).append("').append('\n'); + } + else if (v instanceof List) + { + List ll = (List) v; + for (Object o1 : ll) + { + ss.append(pad(indent)).append('<').append(k).append('>').append('\n'); + ss.append(generateXml(o1, indent + 1)); + ss.append(pad(indent)).append("').append('\n'); + } + } + } + return ss.toString(); + } + + return null; + } + + private static String pad(int n) + { + String s = ""; + for (int i = 0; i < n; i++) + s += '\t'; + return s; + } +} diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/CCAActivator.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/CCAActivator.java deleted file mode 100644 index d9d2b11b0..000000000 --- a/appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/CCAActivator.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.ccadaptor; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.Properties; - -import org.onap.ccsdk.sli.core.sli.ConfigurationException; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class CCAActivator implements BundleActivator -{ - - private static final String CCA_PROP_FILE_VAR = "SDNC_CCA_PROPERTIES"; - private static final String SDNC_CONFIG_DIR_VAR = "APPC_CONFIG_DIR"; - - @SuppressWarnings("rawtypes") - private ServiceRegistration registration = null; - - //private static final Logger log = LoggerFactory.getLogger(CCAActivator.class); - private static final EELFLogger log = EELFManager.getInstance().getLogger(CCAActivator.class); - - @Override - public void start(BundleContext ctx) throws Exception - { - // Read properties - Properties props = new Properties(); - - // Read properties from appc-config-adaptor.properties - String propFileName = System.getenv(CCA_PROP_FILE_VAR); - if (propFileName == null) - { - String propDir = System.getenv(SDNC_CONFIG_DIR_VAR); - if (propDir == null) - throw new ConfigurationException( - "Cannot find config file - " + CCA_PROP_FILE_VAR + " and " + SDNC_CONFIG_DIR_VAR + " unset"); - - propFileName = propDir + "/appc-config-adaptor.properties"; - log.warn("Environment variable " + CCA_PROP_FILE_VAR + " unset - defaulting to " + propFileName); - } - - File propFile = new File(propFileName); - if (!propFile.exists()) - throw new ConfigurationException("Missing configuration properties file: " + propFile); - - try(InputStream in = new FileInputStream(propFile)) { - props.load(in); - log.info("Loaded properties: "); - } - catch (Exception e) - { - throw new ConfigurationException("Could not load properties file " + propFileName, e); - } - - // Advertise adaptor - ConfigComponentAdaptor adaptor = new ConfigComponentAdaptor(props); - if (registration == null) - { - log.info("Registering service " + ConfigComponentAdaptor.class.getName()); - registration = ctx.registerService(ConfigComponentAdaptor.class.getName(), adaptor, null); - } - - } - - @Override - public void stop(BundleContext ctx) throws Exception - { - if (registration != null) - { - registration.unregister(); - registration = null; - } - } -} diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/ConfigComponentAdaptor.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/ConfigComponentAdaptor.java deleted file mode 100644 index 1434b3d93..000000000 --- a/appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/ConfigComponentAdaptor.java +++ /dev/null @@ -1,1064 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property.All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.ccadaptor; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.FileReader; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.StringTokenizer; -import java.util.NoSuchElementException; -import java.io.StringReader; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.core.util.Base64; -import org.jdom.input.SAXBuilder; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class ConfigComponentAdaptor implements SvcLogicAdaptor -{ - - private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class); - - private String configUrl = null; - private String configUser = null; - private String configPassword = null; - private String auditUrl = null; - private String auditUser = null; - private String auditPassword = null; - private String configCallbackUrl = null; - private String auditCallbackUrl = null; - DebugLog debugLog = new DebugLog(); - - public ConfigComponentAdaptor(Properties props) - { - if (props != null) - { - configUrl = props.getProperty("configComponent.url", ""); - configUser = props.getProperty("configComponent.user", ""); - configPassword = props.getProperty("configComponent.passwd", ""); - auditUrl = props.getProperty("auditComponent.url", ""); - auditUser = props.getProperty("auditComponent.user", ""); - auditPassword = props.getProperty("auditComponent.passwd", ""); - configCallbackUrl = props.getProperty("service-configuration-notification-url", ""); - auditCallbackUrl = props.getProperty("audit-configuration-notification-url", ""); - } - else - { - configUrl = ""; - configUser = ""; - configPassword = ""; - auditUrl = ""; - auditUser = ""; - auditPassword = ""; - configCallbackUrl = ""; - auditCallbackUrl = ""; - } - } - - @Override - public ConfigStatus configure(String key, Map parameters, SvcLogicContext ctx) - { - String fnName = "ConfigComponentAdaptor.configure"; - HttpResponse r = new HttpResponse(); - r.code = 200; - log.debug("ConfigComponentAdaptor.configure - key = " + key); - debugLog.printRTAriDebug(fnName, "key = " + key); - log.debug("Parameters:"); - debugLog.printRTAriDebug(fnName, "Parameters:"); - for (String parmName : parameters.keySet()) - { - log.debug(" " + parmName + " = " + parameters.get(parmName)); - debugLog.printRTAriDebug(fnName, " " + parmName + " = " + parameters.get(parmName)); - } - - String parmval = parameters.get("config-component-configUrl"); - if ((parmval != null) && (parmval.length() > 0)) - { - log.debug("Overwriting URL with " + parmval); - configUrl = parmval; - } - - parmval = parameters.get("config-component-configPassword"); - if ((parmval != null) && (parmval.length() > 0)) - { - log.debug("Overwriting configPassword with " + parmval); - configPassword = parmval; - } - - parmval = parameters.get("config-component-configUser"); - if ((parmval != null) && (parmval.length() > 0)) - { - log.debug("Overwriting configUser id with " + parmval); - configUser = parmval; - } - - String action = parameters.get("action"); - - String chg = ctx.getAttribute( - "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name"); - if (chg != null && "prepare".equalsIgnoreCase(action)) - return prepare(ctx, "CHANGE", "change"); - if (chg != null && "activate".equalsIgnoreCase(action)) - return activate(ctx, true); - - String scale = ctx.getAttribute( - "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type"); - if (scale != null && "prepare".equalsIgnoreCase(action)) - return prepare(ctx, "CHANGE", "scale"); - if (scale != null && "activate".equalsIgnoreCase(action)) - return activate(ctx, true); - - if ("prepare".equalsIgnoreCase(action)) - return prepare(ctx, "BASE", "create"); - if ("activate".equalsIgnoreCase(action)) - return activate(ctx, false); - - if ("backup".equalsIgnoreCase(action)) - return prepare(ctx, "BACKUP", "backup"); - if ("restorebackup".equalsIgnoreCase(action)) - return prepare(ctx, "RESTOREBACKUP", "restorebackup"); - if ("deletebackup".equalsIgnoreCase(action)) - return prepare(ctx, "DELETEBACKUP", "deletebackup"); - if ("audit".equalsIgnoreCase(action)) - return audit(ctx, "FULL"); - if ("getrunningconfig".equalsIgnoreCase(action)) - return audit(ctx, "RUNNING"); - - if ((key.equals("put")) || (key.equals("get"))) - { - String loginId = parameters.get("loginId"); - String host = parameters.get("host"); - String password = parameters.get("password"); - password = EncryptionTool.getInstance().decrypt(password); - String fullPathFileName = parameters.get("fullPathFileName"); - String data = null; - - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); - log.debug("SCP: SshJcraftWrapper has been instantiated"); - debugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated"); - try - { - if (key.equals("put")) - { - data = parameters.get("data"); - if (data != null) { - debugLog.printRTAriDebug(fnName, "Command is for put: Length of data is: " + data.length()); - InputStream is = new ByteArrayInputStream(data.getBytes()); - log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName); - debugLog.printRTAriDebug(fnName, "SCP: Doing a put: fullPathFileName=" + fullPathFileName); - sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password); - try - { - debugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds...."); - Thread.sleep(1000 * 180); - debugLog.printRTAriDebug(fnName, "Woke up...."); - } - catch (java.lang.InterruptedException ee) - { - boolean ignore = true; - } - } else { - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - log.debug(fnName + " Command is for put: data is null"); - } - } - else // Must be a get - { - log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName); - debugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName); - String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password); - debugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object"); - ctx.setAttribute("fileContents", response); - log.debug("SCP: Closing the SFTP connection"); - } - sshJcraftWrapper = null; - return (setResponseStatus(ctx, r)); - } - catch (IOException e) - { - DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e); - log.debug(fnName + " : Caught a IOException e=" + e); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - sshJcraftWrapper = null; - return (setResponseStatus(ctx, r)); - } - } - if (key.equals("cli")) - { - String loginId = parameters.get("loginId"); - String host = parameters.get("host"); - String password = parameters.get("password"); - password = EncryptionTool.getInstance().decrypt(password); - String cliCommand = parameters.get("cli"); - String portNumber = parameters.get("portNumber"); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); - try - { - log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId + " password=" + password + - " portNumber=" + portNumber); - debugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId + - " password=" + password + " portNumber=" + portNumber); - sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber)); - - DebugLog.printAriDebug(fnName, "Sending 'sdc'"); - String response = sshJcraftWrapper.send("sdc", ":"); - DebugLog.printAriDebug(fnName, "Sending 1"); - response = sshJcraftWrapper.send("1", ":"); - DebugLog.printAriDebug(fnName, "Sending 1, the second time"); - response = sshJcraftWrapper.send("1", "#"); - DebugLog.printAriDebug(fnName, "Sending paging-options disable"); - response = sshJcraftWrapper.send("paging-options disable", "#"); - DebugLog.printAriDebug(fnName, "Sending show config"); - response = sshJcraftWrapper.send("show config", "#"); - - DebugLog.printAriDebug(fnName, "response is now:'" + response + "'"); - DebugLog.printAriDebug(fnName, "Populating the ctx object with the response"); - ctx.setAttribute("cliOutput", response); - sshJcraftWrapper.closeConnection(); - r.code = 200; - sshJcraftWrapper = null; - return (setResponseStatus(ctx, r)); - } - catch (IOException e) - { - DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e); - log.debug(fnName + " : Caught a IOException e=" + e); - sshJcraftWrapper.closeConnection(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - sshJcraftWrapper = null; - DebugLog.printAriDebug(fnName, "Returning error message"); - return (setResponseStatus(ctx, r)); - } - } - if (key.equals("escapeSql")) - { - String data = parameters.get("artifactContents"); - log.debug("ConfigComponentAdaptor.configure - escapeSql"); - data = escapeMySql(data); - ctx.setAttribute("escapedData", data); - return (setResponseStatus(ctx, r)); - } - if(key.equals("GetCliRunningConfig")) - { - debugLog.printRTAriDebug (fnName, "key was: GetCliRunningConfig: "); - log.debug("key was: GetCliRunningConfig: "); - String User_name = parameters.get("User_name"); - String Host_ip_address = parameters.get("Host_ip_address"); - String Password = parameters.get("Password"); - Password = EncryptionTool.getInstance().decrypt(Password); - String Port_number = parameters.get("Port_number"); - String Get_config_template = parameters.get("Get_config_template"); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); - log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated"); - debugLog.printRTAriDebug (fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated"); - try - { - DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name="+User_name + - " Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number); - log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address="+Host_ip_address + - " User_name="+User_name+" Password="+Password+" Port_number="+Port_number); - StringBuffer sb = new StringBuffer(); - String response = ""; - String CliResponse = ""; - boolean showConfigFlag = false; - sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number)); - DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device"); - StringTokenizer st = new StringTokenizer(Get_config_template, "\n"); - String command = null; - try - { - while (st.hasMoreTokens()) - { - String line = st.nextToken(); - DebugLog.printAriDebug(fnName, "line="+line); - if (line.indexOf("Request:") != -1) - { - DebugLog.printAriDebug(fnName, "Found a Request line: line="+line); - command = getStringBetweenQuotes(line); - DebugLog.printAriDebug(fnName, "Sending command="+command); - sshJcraftWrapper.send(command); - DebugLog.printAriDebug(fnName, "command has been sent"); - if (line.indexOf("show config") != -1) - { - showConfigFlag = true; - DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true"); - log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true"); - } - } - if (line.indexOf("Response: Ends_With") != -1) - { - DebugLog.printAriDebug(fnName, "Found a Response line: line="+line); - String delemeter = getStringBetweenQuotes(line); - DebugLog.printAriDebug(fnName, "The delemeter="+delemeter); - String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, 30*1000, command); - response += tmpResponse; - if (showConfigFlag) - { - showConfigFlag = false; - StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n"); - // Strip off the last line which is the command prompt from the VNF device. - while (st2.hasMoreTokens()) - { - String line2 = st2.nextToken(); - if (line2.indexOf("#") == -1) - CliResponse += line2 +"\n"; - } - } - } - } - } - catch (NoSuchElementException e) - { - DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e="+e); - } - DebugLog.printAriDebug(fnName, "CliResponse=\n"+CliResponse); - ctx.setAttribute("cliOutput", CliResponse); - sshJcraftWrapper.closeConnection(); - r.code = 200; - sshJcraftWrapper = null; - return(setResponseStatus(ctx, r)); - } - catch(IOException e) - { - DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e="+e); - log.debug(fnName +" : GetCliRunningConfig: Caught a IOException e="+e); - sshJcraftWrapper.closeConnection(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - sshJcraftWrapper = null; - DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Returning error message"); - return(setResponseStatus(ctx, r)); - } - } - if(key.equals("xml-download")) - { - log(fnName, "key was: xml-download"); - String User_name = parameters.get("User_name"); - String Host_ip_address = parameters.get("Host_ip_address"); - String Password = parameters.get("Password"); - Password = EncryptionTool.getInstance().decrypt(Password); - String Port_number = parameters.get("Port_number"); - String Contents = parameters.get("Contents"); - String netconfHelloCmd = "\n \n \n urn:ietf:params:netconf:base:1.0\n urn:com:ericsson:ebase:1.1.0 \n "; - String terminateConnectionCmd = "\n \n \n \n ]]>]]>"; - String commitCmd = "\n \n ]]>]]>"; - - log(fnName, "xml-download: User_name="+User_name +" Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); - try - { - sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number), "netconf"); - String NetconfHelloCmd = netconfHelloCmd; - NetconfHelloCmd = NetconfHelloCmd +"]]>]]>"; - log(fnName, "Sending the hello command"); - sshJcraftWrapper.send(NetconfHelloCmd); - String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, ""); - log(fnName, "Sending xmlCmd cmd"); - String xmlCmd = Contents; - String messageId = "1"; - messageId= "\"" +messageId+"\""; - String loadConfigurationString = " merge "+xmlCmd+" "; - loadConfigurationString = loadConfigurationString +"]]>]]>"; - sshJcraftWrapper.send(loadConfigurationString); - DebugLog.printAriDebug(fnName,":After sending loadConfigurationString"); - response = sshJcraftWrapper.receiveUntil("", 600000, ""); - if (response.indexOf("rpc-error") != -1) - { - DebugLog.printAriDebug(fnName,"Error from device: Response from device had 'rpc-error'"); - DebugLog.printAriDebug(fnName,"response=\n"+response +"\n"); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = response; - } - else - { - DebugLog.printAriDebug(fnName,":LoadConfiguration was a success, sending commit cmd"); - sshJcraftWrapper.send(commitCmd); - DebugLog.printAriDebug(fnName,":After sending commitCmd"); - response = sshJcraftWrapper.receiveUntil("", 180000, ""); - if (response.indexOf("rpc-error") != -1) - { - DebugLog.printAriDebug(fnName,"Error from device: Response from device had 'rpc-error'"); - DebugLog.printAriDebug(fnName,"response=\n"+response +"\n"); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = response; - } - else - { - DebugLog.printAriDebug(fnName,":Looks like a success"); - DebugLog.printAriDebug(fnName,"response=\n"+response +"\n"); - r.code = 200; - } - } - sshJcraftWrapper.send(terminateConnectionCmd); - sshJcraftWrapper.closeConnection(); - sshJcraftWrapper = null; - return(setResponseStatus(ctx, r)); - } - catch (Exception e) - { - log(fnName, "Caught an Exception, e="+e); - log(fnName, "StackTrace="+DebugLog.getStackTraceString(e)); - sshJcraftWrapper.closeConnection(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - sshJcraftWrapper = null; - log(fnName, "Returning error message"); - return (setResponseStatus(ctx, r)); - } - } - if(key.equals("xml-getrunningconfig")) - { - log(fnName, "key was: : xml-getrunningconfig"); - String xmlGetRunningConfigCmd = " \n"; - String Host_ip_address = parameters.get("Host_ip_address"); - String User_name = parameters.get("User_name"); - String Password = parameters.get("Password"); - Password = EncryptionTool.getInstance().decrypt(Password); - String Port_number = parameters.get("Port_number"); - String Protocol = parameters.get("Protocol"); - String netconfHelloCmd = "\n \n \n urn:ietf:params:netconf:base:1.0\n urn:com:ericsson:ebase:1.1.0 \n "; - String terminateConnectionCmd = "\n \n \n \n ]]>]]>"; - log(fnName, "xml-getrunningconfig: User_name="+User_name +" Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); - try - { - String NetconfHelloCmd = netconfHelloCmd; - sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number), "netconf"); - NetconfHelloCmd = NetconfHelloCmd +"]]>]]>"; - log(fnName, ":Sending the hello command"); - sshJcraftWrapper.send(NetconfHelloCmd); - String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, ""); - log(fnName, "Sending get running config command"); - sshJcraftWrapper.send(xmlGetRunningConfigCmd +"]]>]]>\n"); - response = sshJcraftWrapper.receiveUntil("", 180000, ""); - DebugLog.printAriDebug(fnName,"Response from getRunningconfigCmd="+response); - response = trimResponse(response); - ctx.setAttribute("xmlRunningConfigOutput", response); - sshJcraftWrapper.send(terminateConnectionCmd); - sshJcraftWrapper.closeConnection(); - r.code = 200; - sshJcraftWrapper = null; - return(setResponseStatus(ctx, r)); - } - catch (Exception e) - { - log(fnName, "Caught an Exception, e="+e); - log(fnName, "StackTrace="+DebugLog.getStackTraceString(e)); - sshJcraftWrapper.closeConnection(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - sshJcraftWrapper = null; - log(fnName, "Returning error message"); - return (setResponseStatus(ctx, r)); - } - } - if(key.equals("DownloadCliConfig")) - { - debugLog.printRTAriDebug (fnName, "key was: DownloadCliConfig: "); - log.debug("key was: DownloadCliConfig: "); - String User_name = parameters.get("User_name"); - String Host_ip_address = parameters.get("Host_ip_address"); - String Password = parameters.get("Password"); - Password = EncryptionTool.getInstance().decrypt(Password); - String Port_number = parameters.get("Port_number"); - String Download_config_template = parameters.get("Download_config_template"); - String Config_contents = parameters.get("Config_contents"); - DebugLog.printAriDebug(fnName, "Contents of the 'Config_contents' are: "+Config_contents); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); - log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated"); - debugLog.printRTAriDebug (fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated"); - int timeout = 4*60*1000; - try - { - DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name="+User_name + - " Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number); - log.debug("DownloadCliConfig: Attempting to login: Host_ip_address="+Host_ip_address + - " User_name="+User_name+" Password="+Password+" Port_number="+Port_number); - StringBuffer sb = new StringBuffer(); - String response = ""; - String CliResponse = ""; - sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number)); - DebugLog.printAriDebug(fnName, "DownloadCliConfig: On the VNF device"); - StringTokenizer st = new StringTokenizer(Download_config_template, "\n"); - String command = null; - String executeConfigContentsDelemeter = null; - try - { - while (st.hasMoreTokens()) - { - String line = st.nextToken(); - DebugLog.printAriDebug(fnName, "line="+line); - if (line.indexOf("Request:") != -1) - { - DebugLog.printAriDebug(fnName, "Found a Request line: line="+line); - command = getStringBetweenQuotes(line); - DebugLog.printAriDebug(fnName, "Sending command="+command); - sshJcraftWrapper.send(command); - DebugLog.printAriDebug(fnName, "command has been sent"); - } - else if ((line.indexOf("Response: Ends_With") != -1) && (line.indexOf("Execute_config_contents Response: Ends_With") == -1)) - { - DebugLog.printAriDebug(fnName, "Found a Response line: line="+line); - String delemeter = getStringBetweenQuotes(line); - DebugLog.printAriDebug(fnName, "The delemeter="+delemeter); - String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, timeout, command); - response += tmpResponse; - CliResponse += tmpResponse; - } - else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) - { - DebugLog.printAriDebug(fnName, "Found a 'Execute_config_contents Response:' line="+line); - executeConfigContentsDelemeter = getStringBetweenQuotes(line); - DebugLog.printAriDebug(fnName, "executeConfigContentsDelemeter="+executeConfigContentsDelemeter); - StringTokenizer st2 = new StringTokenizer(Config_contents, "\n"); - while (st2.hasMoreTokens()) - { - String cmd = st2.nextToken(); - DebugLog.printAriDebug(fnName, "Config_contents: cmd="+cmd); - sshJcraftWrapper.send(cmd); - String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter, timeout, command); - CliResponse += tmpResponse; - } - } - } - } - catch (NoSuchElementException e) - { - DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e="+e); - } - sshJcraftWrapper.closeConnection(); - sshJcraftWrapper = null; - DebugLog.printAriDebug(fnName, ":Escaping all the single and double quotes in the response"); - CliResponse = CliResponse.replaceAll("\"", "\\\\\""); - CliResponse = CliResponse.replaceAll("\'", "\\\\'"); - DebugLog.printAriDebug(fnName, "CliResponse=\n"+CliResponse); - ctx.setAttribute("cliOutput", CliResponse); - r.code = 200; - return(setResponseStatus(ctx, r)); - } - catch(IOException e) - { - DebugLog.printAriDebug(fnName, "DownloadCliConfig: Caught a IOException e="+e); - log.debug(fnName +" : DownloadCliConfig: Caught a IOException e="+e); - sshJcraftWrapper.closeConnection(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - sshJcraftWrapper = null; - DebugLog.printAriDebug(fnName, "DownloadCliConfig: Returning error message"); - return(setResponseStatus(ctx, r)); - } - } - - debugLog.printRTAriDebug (fnName, "Unsupported action - " + action); - log.error("Unsupported action - " + action); - return ConfigStatus.FAILURE; - } - - private void log (String fileName, String messg) - { - debugLog.printRTAriDebug (fileName, messg); - log.debug(fileName +": "+messg); - } - - private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) - { - String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml"; - String ndTemplate = readFile(templateName); - String nd = buildNetworkData2(ctx, ndTemplate, operation); - - String reqTemplate = readFile("/config-request.xml"); - Map param = new HashMap(); - param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id")); - param.put("request-type", requestType); - param.put("callback-url", configCallbackUrl); - if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) - param.put("action", "GenerateOnly"); - param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id")); - param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address")); - param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor")); - param.put("network-data", nd); - - String req = null; - try - { - req = buildXmlRequest(param, reqTemplate); - } - catch (Exception e) - { - log.error("Error building the XML request: ", e); - - HttpResponse r = new HttpResponse(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - return setResponseStatus(ctx, r); - } - - HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword); - return setResponseStatus(ctx, r); - } - - private ConfigStatus activate(SvcLogicContext ctx, boolean change) - { - String reqTemplate = readFile("/config-request.xml"); - Map param = new HashMap(); - param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id")); - param.put("callback-url", configCallbackUrl); - param.put("action", change ? "DownloadChange" : "DownloadBase"); - param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id")); - - String req = null; - try - { - req = buildXmlRequest(param, reqTemplate); - } - catch (Exception e) - { - log.error("Error building the XML request: ", e); - - HttpResponse r = new HttpResponse(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - return setResponseStatus(ctx, r); - } - - HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword); - return setResponseStatus(ctx, r); - } - - private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) - { - String reqTemplate = readFile("/audit-request.xml"); - Map param = new HashMap(); - param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id")); - param.put("callback-url", auditCallbackUrl); - param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id")); - param.put("audit-level", auditLevel); - - String req = null; - try - { - req = buildXmlRequest(param, reqTemplate); - } - catch (Exception e) - { - log.error("Error building the XML request: ", e); - - HttpResponse r = new HttpResponse(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - return setResponseStatus(ctx, r); - } - - HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword); - return setResponseStatus(ctx, r); - } - - @Override - public ConfigStatus activate(String key, SvcLogicContext ctx) - { - return ConfigStatus.SUCCESS; - } - - @Override - public ConfigStatus deactivate(String key, SvcLogicContext ctx) - { - return ConfigStatus.SUCCESS; - } - - private String escapeMySql(String input) - { - if (input == null) - return null; - - input = input.replace("\\", "\\\\"); - input = input.replace("\'", "\\'"); - - return input; - } - - private String readFile(String fileName) - { - InputStream is = getClass().getResourceAsStream(fileName); - InputStreamReader isr = new InputStreamReader(is); - BufferedReader in = new BufferedReader(isr); - StringBuilder ss = new StringBuilder(); - try - { - String s = in.readLine(); - while (s != null) - { - ss.append(s).append('\n'); - s = in.readLine(); - } - } - catch (IOException e) - { - System.out.println("Error reading " + fileName + ": " + e.getMessage()); - throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e); - } - finally - { - try - { - in.close(); - } - catch (Exception e) - { - log.warn("Could not close BufferedReader", e); - } - try - { - isr.close(); - } - catch (Exception e) - { - log.warn("Could not close InputStreamReader", e); - } - try - { - is.close(); - } - catch (Exception e) - { - log.warn("Could not close InputStream", e); - } - } - return ss.toString(); - } - - private String buildXmlRequest(Map param, String template) - { - StringBuilder ss = new StringBuilder(); - int i = 0; - while (i < template.length()) - { - int i1 = template.indexOf("${", i); - if (i1 < 0) - { - ss.append(template.substring(i)); - break; - } - - int i2 = template.indexOf('}', i1 + 2); - if (i2 < 0) - throw new RuntimeException("Template error: Matching } not found"); - - String var1 = template.substring(i1 + 2, i2); - String value1 = param.get(var1); - if (value1 == null || value1.trim().length() == 0) - { - // delete the whole element (line) - int i3 = template.lastIndexOf('\n', i1); - if (i3 < 0) - i3 = 0; - int i4 = template.indexOf('\n', i1); - if (i4 < 0) - i4 = template.length(); - - if (i < i3) - ss.append(template.substring(i, i3)); - i = i4; - } - else - { - ss.append(template.substring(i, i1)).append(value1); - i = i2 + 1; - } - } - - return ss.toString(); - } - - private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) - { - log.info("Building XML started"); - long t1 = System.currentTimeMillis(); - - template = expandRepeats(ctx, template, 1); - - Map mm = new HashMap<>(); - for (String s : ctx.getAttributeKeySet()) - mm.put(s, ctx.getAttribute(s)); - mm.put("operation", operation); - - StringBuilder ss = new StringBuilder(); - int i = 0; - while (i < template.length()) - { - int i1 = template.indexOf("${", i); - if (i1 < 0) - { - ss.append(template.substring(i)); - break; - } - - int i2 = template.indexOf('}', i1 + 2); - if (i2 < 0) - throw new RuntimeException("Template error: Matching } not found"); - - String var1 = template.substring(i1 + 2, i2); - String value1 = XmlUtil.getXml(mm, var1); - if (value1 == null || value1.trim().length() == 0) - { - // delete the whole element (line) - int i3 = template.lastIndexOf('\n', i1); - if (i3 < 0) - i3 = 0; - int i4 = template.indexOf('\n', i1); - if (i4 < 0) - i4 = template.length(); - - if (i < i3) - ss.append(template.substring(i, i3)); - i = i4; - } - else - { - ss.append(template.substring(i, i1)).append(value1); - i = i2 + 1; - } - } - - long t2 = System.currentTimeMillis(); - log.info("Building XML completed. Time: " + (t2 - t1)); - - return ss.toString(); - } - - private String expandRepeats(SvcLogicContext ctx, String template, int level) - { - StringBuilder newTemplate = new StringBuilder(); - int k = 0; - while (k < template.length()) - { - int i1 = template.indexOf("${repeat:", k); - if (i1 < 0) - { - newTemplate.append(template.substring(k)); - break; - } - - int i2 = template.indexOf(':', i1 + 9); - if (i2 < 0) - throw new RuntimeException( - "Template error: Context variable name followed by : is required after repeat"); - - // Find the closing }, store in i3 - int nn = 1; - int i3 = -1; - int i = i2; - while (nn > 0 && i < template.length()) - { - i3 = template.indexOf('}', i); - if (i3 < 0) - throw new RuntimeException("Template error: Matching } not found"); - int i32 = template.indexOf('{', i); - if (i32 >= 0 && i32 < i3) - { - nn++; - i = i32 + 1; - } - else - { - nn--; - i = i3 + 1; - } - } - - String var1 = template.substring(i1 + 9, i2); - String value1 = ctx.getAttribute(var1); - log.info(" " + var1 + ": " + value1); - int n = 0; - try - { - n = Integer.parseInt(value1); - } - catch (Exception e) - { - n = 0; - } - - newTemplate.append(template.substring(k, i1)); - - String rpt = template.substring(i2 + 1, i3); - - for (int ii = 0; ii < n; ii++) - { - String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]"); - newTemplate.append(ss); - } - - k = i3 + 1; - } - - if (k == 0) - return newTemplate.toString(); - - return expandRepeats(ctx, newTemplate.toString(), level + 1); - } - - private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) - { - try - { - Client client = Client.create(); - client.setConnectTimeout(5000); - WebResource webResource = client.resource(url); - - log.info("SENDING..............."); - log.info(xmlRequest); - - String authString = user + ":" + password; - byte[] authEncBytes = Base64.encode(authString); - String authStringEnc = new String(authEncBytes); - authString = "Basic " + authStringEnc; - - ClientResponse response = - webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post( - ClientResponse.class, xmlRequest); - - int code = response.getStatus(); - String message = null; - - log.info("RESPONSE..............."); - log.info("HTTP response code: " + code); - log.info("HTTP response message: " + message); - log.info(""); - - HttpResponse r = new HttpResponse(); - r.code = code; - r.message = message; - return r; - - } - catch (Exception e) - { - log.error("Error sending the request: ", e); - - HttpResponse r = new HttpResponse(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - return r; - } - } - - private static class HttpResponse - { - - public int code; - public String message; - } - - private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) - { - ctx.setAttribute("error-code", String.valueOf(r.code)); - ctx.setAttribute("error-message", r.message); - - return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS; - } - - private String getStringBetweenQuotes(String string) - { - String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes"; - DebugLog.printAriDebug(fnName, "string="+string); - String retString = null; - int start = string.indexOf("\""); - int end = string.lastIndexOf("\""); - retString = string.substring(start+1, end); - DebugLog.printAriDebug(fnName, "retString="+retString); - return(retString); - } - - public static String _readFile(String fileName) - { - StringBuffer strBuff = new StringBuffer(); - String line; - try (BufferedReader in = new BufferedReader(new FileReader(fileName))) - { - while ((line = in.readLine()) != null) - { - strBuff.append(line+"\n"); - } - } - catch (IOException e) - { - System.out.println("Caught an IOException in method readFile(): e="+e.toString()); - } - return (strBuff.toString()); - } - - private String trimResponse(String response) - { - StringTokenizer line = new StringTokenizer(response, "\n"); - StringBuffer sb = new StringBuffer(); - boolean captureText = false; - while (line.hasMoreTokens()) - { - String token = line.nextToken(); - if (token.indexOf("") != -1) - captureText = false; - } - return(sb.toString()); - } - - public static void main (String args[]) throws Exception - { - Properties props = null; - System.out.println("*************************Hello*****************************"); - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String Get_config_template = _readFile ("/home/userID/data/Get_config_template"); - String Download_config_template = _readFile ("/home/userID/data/Download_config_template_2"); - String key = "GetCliRunningConfig"; - Map parameters = new HashMap(); - parameters.put("Host_ip_address", "000.00.000.00"); - parameters.put("User_name", "root"); - parameters.put("Password", "!bootstrap"); - parameters.put("Port_number", "22"); - parameters.put("Get_config_template", Get_config_template); - - SvcLogicContext ctx = null; - System.out.println("*************************TRACE 1*****************************"); - cca.configure(key, parameters, ctx); - } - -} - diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/DebugLog.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/DebugLog.java deleted file mode 100644 index 15db56c90..000000000 --- a/appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/DebugLog.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.ccadaptor; - -import java.io.*; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; - - -public class DebugLog -{ - private static String fileName = "/tmp/rt.log"; - - public static void main (String args[]) - { - DebugLog debugLog = new DebugLog(); - debugLog.printAriDebug("DebugLog", "The Message"); - } - - public static void printAriDebug(String fn, String messg) - { - String logMessg = getDateTime() +" " +fn +" " + messg; - appendToFile(logMessg +"\n"); - - } - - public static void printRTAriDebug(String fn, String messg) - { - // System.out.println (getDateTime() +" " +fn +" " + messg); - String logMessg = getDateTime() +" " +fn +" " + messg; - appendToFile(logMessg +"\n"); - } - public static String getDateTime() - { - DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); - // DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); - Date date = new Date(); - return dateFormat.format(date); - } - - public static void appendToFile (String dataToWrite) - { - String fn = "DebugLog.appendToFile"; - try - { - // First check to see if a file 'fileName' exist, if it does - // write to it. If it does not exist, don't write to it. - File tmpFile = new File(fileName); - if (tmpFile.exists()) - { - BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true)); - out.write(dataToWrite); - out.close(); - } - } - catch (IOException e) - { - DebugLog.printRTAriDebug (fn, "writeToFile() exception: " + e); - //System.err.println("writeToFile() exception: " + e); - e.printStackTrace(); - } - } - - public void outputStackTrace(Exception e) - { - String fn = "DebugLog.outputStackTrace"; - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw)); - String stackTrace = sw.toString(); - DebugLog.printRTAriDebug(fn, "Stack trace::: "+stackTrace); - } - - public static String getStackTraceString(Exception e) - { - String fn = "DebugLog.outputStackTrace"; - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw)); - String stackTrace = sw.toString(); - return(stackTrace); - } - -} - diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/EncryptionTool.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/EncryptionTool.java deleted file mode 100644 index ad09d7faf..000000000 --- a/appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/EncryptionTool.java +++ /dev/null @@ -1,214 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.ccadaptor; - -import java.security.Provider; -import java.security.Provider.Service; -import java.security.Security; - -import javax.crypto.Cipher; - -import org.jasypt.contrib.org.apache.commons.codec_1_3.binary.Base64; -import org.jasypt.util.text.BasicTextEncryptor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class is used to encapsulate the encryption and decryption support in one place and to provide a utility to - * encrypt and decrypt data. - */ -public class EncryptionTool { - - /** - * This lock object is used ONLY if the singleton has not been set up. - */ - private static final Object lock = new Object(); - - /** - * The salt is used to initialize the PBE (password Based Encrpytion) algorithm. - */ - private static final byte[] DEFAULT_SALT = { - (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 - }; - - /** - * The prefix we insert onto any data we encrypt so that we can tell if it is encrpyted later and therefore decrypt - * it - */ - @SuppressWarnings("nls") - public static final String ENCRYPTED_VALUE_PREFIX = "enc:"; - - /** - * The instance of the encryption utility object - */ - private static EncryptionTool instance = null; - - /** - * The iteration count used to initialize the PBE algorithm and to generate the key spec - */ - private static final int ITERATION_COUNT = 20; - - /** - * The logger for this class. - */ - private static final Logger LOG = LoggerFactory.getLogger(EncryptionTool.class); - - /** - * The secret passphrase (PBE) that we use to perform encryption and decryption. The algorithm we are using is a - * symmetrical cipher. - */ - private static char[] secret = { - 'C', '_', 'z', 'l', '!', 'K', '!', '4', '?', 'O', 'z', 'E', 'K', 'E', '>', 'U', 'R', '/', '%', 'Y', '\\', 'f', - 'b', '"', 'e', 'n', '{', '"', 'l', 'U', 'F', '+', 'E', '\'', 'R', 'T', 'p', '1', 'V', '4', 'l', 'a', '9', 'w', - 'v', '5', 'Z', '#', 'i', 'V', '"', 'd', 'l', '!', 'L', 'M', 'g', 'L', 'Q', '{', 'v', 'v', 'K', 'V' - }; - - /** - * The algorithm to encrypt and decrpyt data is "Password (or passphrase) Based Encryption with Message Digest #5 - * and the Data Encryption Standard", i.e., PBEWithMD5AndDES. - */ - @SuppressWarnings("nls") - private static final String SECURITY_ALGORITHM = "PBEWITHMD5AND256BITAES";// "PBEWithMD5AndDES"; - - /** - * The decryption cipher object - */ - private Cipher decryptCipher = null; - - /** - * The encryption cipher object - */ - private Cipher encryptCipher = null; - - private BasicTextEncryptor encryptor; - - /** - * Get an instance of the EncryptionTool - * - * @return The encryption tool to be used - */ - public static final EncryptionTool getInstance() { - if (instance == null) { - synchronized (lock) { - if (instance == null) { - instance = new EncryptionTool(); - } - } - } - return instance; - } - - /** - * Create the EncryptionTool instance - */ - @SuppressWarnings("nls") - private EncryptionTool() { - // encryptor = new BasicTextEncryptor(); - // encryptor.setPassword(secret.toString()); - String out = "Found the following security algorithms:"; - for (Provider p : Security.getProviders()) { - for (Service s : p.getServices()) { - String algo = s.getAlgorithm(); - out += - String.format("\n -Algorithm [ %s ] in provider [ %s ] and service [ %s ]", algo, p.getName(), - s.getClassName()); - } - } - LOG.debug(out); - } - - /** - * Decrypt the provided encrypted text - * - * @param cipherText - * THe cipher text to be decrypted. If the ciphertext is not encrypted, then it is returned as is. - * @return the clear test of the (possibly) encrypted value. The original value if the string is not encrypted. - */ - @SuppressWarnings("nls") - public synchronized String decrypt(String cipherText) { - if (isEncrypted(cipherText)) { - String encValue = cipherText.substring(ENCRYPTED_VALUE_PREFIX.length()); - // return encryptor.decrypt(encValue); - byte[] plainByte = Base64.decodeBase64(encValue.getBytes()); - byte[] decryptByte = xorWithSecret(plainByte); - return new String(decryptByte); - } else { - return cipherText; - } - - } - - /** - * Encrypt the provided clear text - * - * @param clearText - * The clear text to be encrypted - * @return the encrypted text. If the clear text is empty (null or zero length), then an empty string is returned. - * If the clear text is already encrypted, it is not encrypted again and is returned as is. Otherwise, the - * clear text is encrypted and returned. - */ - @SuppressWarnings("nls") - public synchronized String encrypt(String clearText) { - if (clearText != null) { - byte[] encByte = xorWithSecret(clearText.getBytes()); - String encryptedValue = new String(Base64.encodeBase64(encByte)); - return ENCRYPTED_VALUE_PREFIX + encryptedValue; - } else { - return null; - } - } - - /** - * Is a value encrypted? A value is considered to be encrypted if it begins with the - * {@linkplain #ENCRYPTED_VALUE_PREFIX encrypted value prefix}. - * - * @param value - * the value to check. - * @return true/false; - */ - private static boolean isEncrypted(final String value) { - return value != null && value.startsWith(ENCRYPTED_VALUE_PREFIX); - } - - /** - * XORs the input byte array with the secret key, padding 0x0 to the end of the secret key if the input is longer - * and returns a byte array the same size as input - * - * @param inp - * The byte array to be XORed with secret - * @return A byte array the same size as inp or null if input is null. - */ - private byte[] xorWithSecret(byte[] inp) { - if (inp == null) { - return null; - } - - byte[] secretBytes = new String(secret).getBytes(); - int size = inp.length; - - byte[] out = new byte[size]; - for (int i = 0; i < size; i++) { - out[i] = (byte) ((inp[i]) ^ (secretBytes[i % secretBytes.length])); - } - return out; - } - -} diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/SshJcraftWrapper.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/SshJcraftWrapper.java deleted file mode 100644 index eb9e28fa2..000000000 --- a/appc-config/appc-config-adaptor/provider/src/main/java/org/openecomp/appc/ccadaptor/SshJcraftWrapper.java +++ /dev/null @@ -1,1277 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.ccadaptor; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.*; -import java.util.*; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import com.jcraft.jsch.*; - -public class SshJcraftWrapper -{ - - private String debugLogFileName = "/tmp/sshJcraftWrapperDebug"; - InputStream inputStream = null; - OutputStream outputStream = null; - private TelnetListener listener = null; - private String routerLogFileName = null; - DebugLog debugLog = new DebugLog(); - private String host = null; - private String RouterName = null; - private int BUFFER_SIZE = 512000; - // private int BUFFER_SIZE = 4000000; - private DataInputStream dis = null; - private BufferedReader reader = null; - char[] charBuffer = new char[BUFFER_SIZE]; - private BufferedWriter out = null; - private File _tmpFile = null; - private JSch jsch = null; - private Session session = null; - private Channel channel = null; - private String tId = ""; - private String aggregatedReceivedString = ""; - private File extraDebugFile = new File("/tmp/sshJcraftWrapperDEBUG"); - private String routerCmdType = "XML"; - private String routerFileName = null; - private File jcraftReadSwConfigFileFromDisk = new File("/tmp/jcraftReadSwConfigFileFromDisk"); - private String equipNameCode = null; - private String hostName = null; - private String userName = null; - private String passWord = null; - private StringBuffer charactersFromBufferFlush = new StringBuffer(); - private Runtime runtime = Runtime.getRuntime(); - private DebugLog dbLog = new DebugLog(); - - public void SshJcraftWrapper() - { - String fn = "SshJcraftWrapper.SshJcraftWrapper"; - debugLog.printRTAriDebug (fn, "SshJcraftWrapper has been instantated"); - routerLogFileName = "/tmp/" +host; - this.host = host; - } - - public void connect (String hostname, String username, String password, String prompt, int timeOut) throws IOException - { - String fn = "SshJcraftWrapper.connect"; - jsch = new JSch(); - debugLog.printRTAriDebug (fn, "Attempting to connect to "+hostname +" username="+username +" password="+password + " prompt='"+prompt +"' timeOut="+timeOut); - debugLog.printRTAriDebug (fn, "Trace A"); - RouterName = hostname; - hostName = hostname; - userName = username; - passWord = password; - try - { - session = jsch.getSession(username, hostname, 22); - UserInfo ui = new MyUserInfo(); - session.setPassword(password); - session.setUserInfo(ui); - session.connect(timeOut); - channel = session.openChannel("shell"); - session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!! - ((ChannelShell)channel).setPtyType("vt102"); - inputStream = channel.getInputStream(); - dis = new DataInputStream(inputStream); - reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE); - channel.connect(); - debugLog.printRTAriDebug (fn, "Successfully connected."); - debugLog.printRTAriDebug (fn, "Flushing input buffer"); - try - { - receiveUntil(prompt, 3000, "No cmd was sent, just waiting"); - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception: Nothing to flush out."); - } - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception. e="+e); - // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e); - throw new IOException(e.toString()); - } - } - - // User specifies the port number. - public void connect (String hostname, String username, String password, String prompt, int timeOut, int portNum) throws IOException - { - String fn = "SshJcraftWrapper.connect"; - debugLog.printRTAriDebug (fn, ":Attempting to connect to "+hostname +" username="+username +" password="+password + " prompt='"+prompt +"' timeOut="+timeOut +" portNum="+portNum); - RouterName = hostname; - hostName = hostname; - userName = username; - passWord = password; - RouterName = hostname; - jsch = new JSch(); - try - { - session = jsch.getSession(username, hostname, portNum); - UserInfo ui = new MyUserInfo(); - session.setPassword(password); - session.setUserInfo(ui); - session.setConfig("StrictHostKeyChecking", "no"); - debugLog.printRTAriDebug (fn, ":StrictHostKeyChecking set to 'no'"); - - session.connect(timeOut); - session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!! - channel = session.openChannel("shell"); - ((ChannelShell)channel).setPtyType("vt102"); - inputStream = channel.getInputStream(); - dis = new DataInputStream(inputStream); - reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE); - channel.connect(); - debugLog.printRTAriDebug (fn, ":Successfully connected."); - debugLog.printRTAriDebug (fn, ":Flushing input buffer"); - try - { - if (prompt.equals("]]>]]>")) - receiveUntil("]]>]]>", 10000, "No cmd was sent, just waiting"); - else - receiveUntil(":~#", 5000, "No cmd was sent, just waiting"); - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception::: Nothing to flush out."); - } - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, ":Caught an Exception. e="+e); - dbLog.outputStackTrace(e); - - // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e); - throw new IOException(e.toString()); - } - } - - - public String receiveUntil (String delimeters, int timeout, String cmdThatWasSent) throws TimedOutException, IOException - { - String fn = "SshJcraftWrapper.receiveUntil"; - boolean match = false; - boolean cliPromptCmd = false; - StringBuffer sb2 = new StringBuffer(); - StringBuffer sbReceive = new StringBuffer(); - debugLog.printRTAriDebug (fn, "delimeters='"+delimeters +"' timeout="+timeout +" cmdThatWasSent='"+cmdThatWasSent +"'"); - appendToFile(debugLogFileName, fn +" delimeters='"+delimeters +"' timeout="+timeout +" cmdThatWasSent='"+cmdThatWasSent +"'\n"); - String CmdThatWasSent = removeWhiteSpaceAndNewLineCharactersAroundString(cmdThatWasSent); - int readCounts = 0; - aggregatedReceivedString = ""; - - long deadline = new Date().getTime() + timeout; - try - { - session.setTimeout(timeout); // This is the socket timeout value. - while (!match) - { - if(new Date().getTime() > deadline) - { - debugLog.printRTAriDebug (fn, "Throwing a TimedOutException: time in routine has exceed our deadline: RouterName:"+RouterName +" CmdThatWasSent="+ CmdThatWasSent); - throw new TimedOutException("Timeout: time in routine has exceed our deadline"); - } - try - { - Thread.sleep(500); - } - catch (java.lang.InterruptedException ee) - { - boolean ignore = true; - } - int len = reader.read(charBuffer, 0, BUFFER_SIZE); - appendToFile(debugLogFileName, fn +" After reader.read cmd: len="+len +"\n"); - if (len <= 0) - { - debugLog.printRTAriDebug (fn, "Reader read "+len +" bytes. Looks like we timed out, router="+RouterName); - throw new TimedOutException ("Received a SocketTimeoutException router="+RouterName); - } - if (!cliPromptCmd) - { - if (cmdThatWasSent.indexOf("IOS_XR_uploadedSwConfigCmd") != -1) - { - if (out == null) - { - // This is a IOS XR sw config file. We will write it to the disk. - timeout = timeout * 2; - deadline = new Date().getTime() + timeout; - debugLog.printRTAriDebug (fn, "IOS XR upload for software config: timeout="+timeout); - StringTokenizer st = new StringTokenizer(cmdThatWasSent); - st.nextToken(); - routerFileName = st.nextToken(); - out = new BufferedWriter(new FileWriter(routerFileName)); - routerLogFileName = "/tmp/"+RouterName; - _tmpFile = new File(routerLogFileName); - debugLog.printRTAriDebug (fn, "Will write the swConfigFile to disk, routerFileName="+routerFileName); - } - int c; - out.write(charBuffer, 0, len); - out.flush(); - appendToFile(debugLogFileName, fn +" Wrote "+len +" bytes to the disk\n"); - if (_tmpFile.exists()) - appendToRouterFile(routerLogFileName, len); - match = checkIfReceivedStringMatchesDelimeter(len, "\nXML>"); - if (match == true) - { - out.flush(); - out.close(); - out = null; - return null; - } - } - else - { - readCounts ++; - appendToFile(debugLogFileName, fn +" readCounts="+readCounts +" Reader read "+len +" of data\n"); - int c; - sb2.setLength(0); - for(int i=0; i") != -1) - { - debugLog.printRTAriDebug (fn, "Found our prompt"); - match = true; - break; - } - } - } - } - catch (JSchException e) - { - debugLog.printRTAriDebug (fn, "Caught an JSchException e="+e.toString()); - dbLog.outputStackTrace(e); - throw new TimedOutException (e.toString()); - } - catch (IOException ee) - { - debugLog.printRTAriDebug (fn, "Caught an IOException: ee="+ee.toString()); - dbLog.outputStackTrace(ee); - throw new TimedOutException (ee.toString()); - } - String result = stripOffCmdFromRouterResponse(sbReceive.toString()); - debugLog.printRTAriDebug (fn, "Leaving method successfully"); - return (result); - } - - public boolean checkIfReceivedStringMatchesDelimeter(String delimeters, String receivedString, String cmdThatWasSent) - { - // The delimeters are in a '|' seperated string. Return true on the first match. - String fn = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter"; - appendToFile(debugLogFileName, fn +" Entered: delimeters='"+delimeters +" cmdThatWasSent='"+cmdThatWasSent +"' receivedString='"+receivedString +"'\n"); - StringTokenizer st = new StringTokenizer(delimeters, "|"); - - if ((delimeters.indexOf("#$") != -1) || (routerCmdType.equals("CLI"))) // This would be an IOS XR, CLI command. - { - int x = receivedString.lastIndexOf("#"); - int y = receivedString.length() - 1; - appendToFile(debugLogFileName, fn +" IOS XR, CLI command\n"); - if (extraDebugFile.exists()) - appendToFile(debugLogFileName, fn +" :::cmdThatWasSent='"+cmdThatWasSent +"' x="+x +" y="+y +"\n"); - if ((x != -1) && (y == x)) - return(true); - else - return(false); - } - if (cmdThatWasSent.indexOf("show config") != -1) - { - appendToFile(debugLogFileName, fn +"In the block for 'show config'\n"); - while (st.hasMoreTokens()) - { - String delimeter = st.nextToken(); - // Make sure we don't get faked out by a response of " #". - // Proc #0 - // # signaling-local-address ipv6 FD00:F4D5:EA06:1::110:136:254 - // LAAR2# - int x = receivedString.lastIndexOf(delimeter); - if ((receivedString.lastIndexOf(delimeter) != -1) && (receivedString.lastIndexOf(" #") != x-1)) - { - appendToFile(debugLogFileName, fn +"receivedString=\n'" +receivedString +"'\n"); - appendToFile(debugLogFileName, fn +"Returning true for the 'show config' command. We found our real delmeter. \n\n"); - return (true); - } - } - } - else - { - aggregatedReceivedString = aggregatedReceivedString + receivedString; - _appendToFile ("/tmp/aggregatedReceivedString.debug", aggregatedReceivedString); - - while (st.hasMoreTokens()) - { - String delimeter = st.nextToken(); - appendToFile(debugLogFileName, fn +" Looking for an delimeter of:'"+delimeter+"'\n"); - appendToFile(debugLogFileName, fn +" receivedString='"+receivedString); - if (aggregatedReceivedString.indexOf(delimeter) != -1) - { - debugLog.printRTAriDebug (fn, "Found our delimeter, which was: '"+delimeter +"'"); - aggregatedReceivedString = ""; - return (true); - } - } - } - return (false); - } - - public boolean checkIfReceivedStringMatchesDelimeter(int len, String delimeter) - { - String fnName = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter:::"; - int x; - int c; - String str = null; - - if (jcraftReadSwConfigFileFromDisk()) - { - DebugLog.printAriDebug(fnName, "jcraftReadSwConfigFileFromDisk block"); - File fileName = new File(routerFileName); - appendToFile(debugLogFileName, fnName +" jcraftReadSwConfigFileFromDisk::: Will read the tail end of the file from the disk"); - try - { - str = getLastFewLinesOfFile(fileName, 3); - } - catch (IOException e) - { - DebugLog.printAriDebug(fnName, "Caught an Exception, e="+e); - dbLog.outputStackTrace(e); - e.printStackTrace(); - } - } - else - { - // DebugLog.printAriDebug(fnName, "TRACE 1: ******************************"); - // When looking at the end of the charBuffer, don't include any linefeeds or spaces. We only want to make the smallest string possible. - for(x=len-1; x>=0; x--) - { - c = charBuffer[x]; - if (extraDebugFile.exists()) - appendToFile(debugLogFileName, fnName +" x="+x +" c="+c +"\n"); - if ((c != 10) && (c != 32)) // Not a line feed nor a space. - break; - } - if ((x+1 - 13) >= 0) - { - str = new String (charBuffer, (x+1-13), 13); - appendToFile(debugLogFileName, fnName +" str:'"+str +"'\n"); - } - else - { - File fileName = new File(routerFileName); - appendToFile(debugLogFileName, fnName +" Will read the tail end of the file from the disk, x="+x +" len="+len +" str::'"+str +"' routerFileName='" +routerFileName +"'\n"); - DebugLog.printAriDebug(fnName, "Will read the tail end of the file from the disk, x="+x +" len="+len +" str::'"+str +"' routerFileName='" +routerFileName +"'"); - try - { - str = getLastFewLinesOfFile(fileName, 3); - } - catch (IOException e) - { - DebugLog.printAriDebug(fnName, "Caught an Exception, e="+e); - dbLog.outputStackTrace(e); - e.printStackTrace(); - } - } - } - - if (str.indexOf(delimeter) != -1) - { - DebugLog.printAriDebug(fnName, "str in break is:'"+str +"'" +" delimeter='" +delimeter +"'"); - appendToFile(debugLogFileName, fnName +" str in break is:'"+str +" delimeter='" +delimeter +"'" +"'\n"); - return(true); - } - else - { - appendToFile(debugLogFileName, fnName +" Returning false"); - return(false); - } - - } - - public void closeConnection() - { - String fn = "SshJcraftWrapper.closeConnection"; - debugLog.printRTAriDebug (fn, "Executing the closeConnection...."); - inputStream = null; - outputStream = null; - dis = null; - charBuffer = null; - session.disconnect(); - session = null; - } - - public void send (String cmd) throws IOException - { - String fn = "SshJcraftWrapper.send"; - OutputStream out = channel.getOutputStream(); - DataOutputStream dos = new DataOutputStream(out); - - if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r')) - cmd += "\n"; - int length = cmd.length(); - int i = -1; - int nchars = 300000; - int ncharsTotalSent = 0; - int ncharsSent = 0; - - appendToFile(debugLogFileName, fn+": Sending: '"+cmd ); - // debugLog.printRTAriDebug (fn, "cmd = "+cmd); - debugLog.printRTAriDebug (fn, "Length of cmd is:" +length); // 2,937,706 - try - { - if (length > 600000) - { - int timeout = 9000; - for (i=0; i\n"); - out.write(dataToWrite.toString()); - out.close(); - } - } - } - catch (IOException e) - { - System.err.println("writeToFile() exception: " + e); - e.printStackTrace(); - } - } - - public void appendToRouterFile (String fileName, int len) - { - String fnName = "SshJcraftWrapper.appendToFile"; - // debugLog.printRTAriDebug (fnName, "Entered.... len="+len); - try - { - // First check to see if a file 'fileName' exist, if it does - // write to it. If it does not exist, don't write to it. - File tmpFile = new File(fileName); - // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true))) - if (tmpFile.exists()) - { - BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true)); - // out.write("\n"); - out.write(charBuffer, 0, len); - out.close(); - } - } - catch (IOException e) - { - System.err.println("writeToFile() exception: " + e); - e.printStackTrace(); - } - } - - public String removeWhiteSpaceAndNewLineCharactersAroundString(String str) - { - if (str != null) - { - StringTokenizer strTok = new StringTokenizer(str, "\n"); - StringBuffer sb = new StringBuffer(); - - while (strTok.hasMoreTokens()) - { - String line = strTok.nextToken(); - sb.append(line); - } - return (sb.toString().trim()); - } - else - return(str); - } - - public String stripOffCmdFromRouterResponse(String routerResponse) - { - String fn = "SshJcraftWrapper.stripOffCmdFromRouterResponse"; - // appendToFile(debugLogFileName, fn+": routerResponse='"+routerResponse +"'\n"); - - // The session of SSH will echo the command sent to the router, in the router's response. - // Since all our commands are terminated by a '\n', strip off the first line - // of the response from the router. This first line contains the orginal command. - - StringTokenizer rr = new StringTokenizer(routerResponse, "\n"); - StringBuffer sb = new StringBuffer(); - - int numTokens = rr.countTokens(); - // debugLog.printRTAriDebug (fn, "Number of lines in the response from the router is:" +numTokens); - if (numTokens > 1) - { - rr.nextToken(); //Skip the first line. - while (rr.hasMoreTokens()) - { - sb.append(rr.nextToken()+'\n'); - } - } - return (sb.toString()); - } - - public void setRouterCommandType(String type) - { - String fn = "SshJcraftWrapper.setRouterCommandType"; - this.routerCmdType = type; - debugLog.printRTAriDebug (fn, "Setting routerCmdType to a value of '"+type +"'"); - } - - public String getLastFewLinesOfFile(File file, int linesToRead) throws FileNotFoundException, IOException - { - String fn = "SshJcraftWrapper.getLastFewLinesOfFile"; - RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); - int lines = 0; - StringBuilder builder = new StringBuilder(); - String tail = ""; - long length = file.length(); - length--; - randomAccessFile.seek(length); - for(long seek = length; seek >= 0; --seek) - { - randomAccessFile.seek(seek); - char c = (char)randomAccessFile.read(); - builder.append(c); - if(c == '\n') - { - builder = builder.reverse(); - // System.out.println(builder.toString()); - tail = builder.toString() + tail; - lines++; - builder.setLength(0); - if (lines == linesToRead) - { - break; - } - } - } - randomAccessFile.close(); - if(!jcraftReadSwConfigFileFromDisk()) - debugLog.printRTAriDebug (fn, "tail='"+tail +"'"); - appendToFile(debugLogFileName, "tail='"+tail +"'\n"); - return tail; - } - - public boolean jcraftReadSwConfigFileFromDisk() - { - if (jcraftReadSwConfigFileFromDisk.exists()) - return(true); - else - return(false); - } - - public String getEquipNameCode() - { - return (equipNameCode); - - } - - public void setEquipNameCode(String equipNameCode) - { - this.equipNameCode = equipNameCode; - } - - public String getRouterName() - { - return(RouterName); - } - - // Routine does reads until it has read 'nchars' or times out. - public void receiveUntilBufferFlush (int ncharsSent, int timeout, String message) throws TimedOutException, IOException - { - String fn = "SshJcraftWrapper.receiveUntilBufferFlush"; - StringBuffer sb2 = new StringBuffer(); - StringBuffer sbReceive = new StringBuffer(); - debugLog.printRTAriDebug (fn, "ncharsSent="+ncharsSent+" timeout="+timeout +" "+message); - int ncharsTotalReceived = 0; - int ncharsRead = 0; - boolean flag = false; - charactersFromBufferFlush.setLength(0); - - long deadline = new Date().getTime() + timeout; - logMemoryUsage(); - try - { - session.setTimeout(timeout); // This is the socket timeout value. - while (true) - { - if(new Date().getTime() > deadline) - { - debugLog.printRTAriDebug (fn, "Throwing a TimedOutException: time in routine has exceed our deadline: ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived); - flag = true; - throw new TimedOutException("Timeout: time in routine has exceed our deadline"); - } - ncharsRead = reader.read(charBuffer, 0, BUFFER_SIZE); - if (listener != null) - listener.receivedString(String.copyValueOf(charBuffer,0,ncharsRead)); - appendToRouterFile("/tmp/"+RouterName, ncharsRead); - ncharsTotalReceived = ncharsTotalReceived + ncharsRead; - // debugLog.printRTAriDebug (fn, "::ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived +" ncharsRead="+ncharsRead); - if (ncharsTotalReceived >= ncharsSent) - { - debugLog.printRTAriDebug (fn, "Received the correct number of characters, ncharsSent="+ncharsSent +" ncharsTotalReceived="+ncharsTotalReceived); - logMemoryUsage(); - return; - } - } - } - catch (JSchException e) - { - debugLog.printRTAriDebug (fn, "Caught an JSchException e="+e.toString()); - debugLog.printRTAriDebug (fn, "ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived +" ncharsRead="+ncharsRead); - throw new TimedOutException (e.toString()); - } - } - - public String getHostName() - { - return(hostName); - } - - public String getUserName() - { - return(userName); - } - - public String getPassWord() - { - return(passWord); - } - - public void sftpPut(String sourcePath, String destDirectory) throws IOException - { - String fn = "SshJcraftWrapper.sftp"; - try - { - Session sftpSession = jsch.getSession(userName, hostName, 22); - UserInfo ui = new MyUserInfo(); - sftpSession.setPassword(passWord); - sftpSession.setUserInfo(ui); - sftpSession.connect(30*1000); - debugLog.printRTAriDebug (fn, "Opening up an sftp channel...."); - ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp"); - debugLog.printRTAriDebug (fn, "Connecting...."); - sftp.connect(); - debugLog.printRTAriDebug (fn, "Sending "+sourcePath +" --> "+destDirectory); - sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE); - debugLog.printRTAriDebug (fn, "Sent successfully"); - sftpSession.disconnect(); - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e); - // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); - throw new IOException(e.toString()); - } - } - - - - public void SftpPut(String stringOfData, String fullPathDest) throws IOException - { - String fn = "SshJcraftWrapper.Sftp"; - try - { - Session sftpSession = jsch.getSession(userName, hostName, 22); - UserInfo ui = new MyUserInfo(); - sftpSession.setPassword(passWord); - sftpSession.setUserInfo(ui); - sftpSession.connect(30*1000); - debugLog.printRTAriDebug (fn, "Opening up an sftp channel...."); - ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp"); - debugLog.printRTAriDebug (fn, "Connecting...."); - sftp.connect(); - InputStream is = new ByteArrayInputStream(stringOfData.getBytes()); - debugLog.printRTAriDebug (fn, "Sending stringOfData --> "+fullPathDest); - sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE); - debugLog.printRTAriDebug (fn, "Sent successfully"); - sftpSession.disconnect(); - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e); - // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); - throw new IOException(e.toString()); - } - } - - public String sftpGet(String fullFilePathName) throws IOException - { - String fn = "SshJcraftWrapper.Sftp"; - try - { - Session sftpSession = jsch.getSession(userName, hostName, 22); - UserInfo ui = new MyUserInfo(); - sftpSession.setPassword(passWord); - sftpSession.setUserInfo(ui); - sftpSession.connect(30*1000); - debugLog.printRTAriDebug (fn, "Opening up an sftp channel...."); - ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp"); - debugLog.printRTAriDebug (fn, "Connecting...."); - sftp.connect(); - InputStream in = null; - in = sftp.get(fullFilePathName); - String sftpFileString = readInputStreamAsString(in); - debugLog.printRTAriDebug (fn, "Retreived successfully"); - // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString); - sftpSession.disconnect(); - return(sftpFileString); - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e); - // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); - throw new IOException(e.toString()); - } - } - - public static String readInputStreamAsString(InputStream in) throws IOException - { - BufferedInputStream bis = new BufferedInputStream(in); - ByteArrayOutputStream buf = new ByteArrayOutputStream(); - int result = bis.read(); - while(result != -1) - { - byte b = (byte)result; - buf.write(b); - result = bis.read(); - } - return buf.toString(); - } - - - public void logMemoryUsage() - { - String fn = "SshJcraftWrapper.logMemoryUsage"; - int mb = 1024*1024; - long usedMemory; - long maxMemoryAdvailable; - long memoryLetfOnHeap; - maxMemoryAdvailable = (runtime.maxMemory() / mb); - usedMemory = ((runtime.totalMemory()/mb) - (runtime.freeMemory()/mb)); - memoryLetfOnHeap = maxMemoryAdvailable - usedMemory; - DebugLog.printAriDebug(fn, "maxMemoryAdvailable="+maxMemoryAdvailable +" usedMemory="+usedMemory +" memoryLetfOnHeap="+memoryLetfOnHeap); - } - - // ---------------------------------------------------------------------------- - // ---------------------------------------------------------------------------- - // ---------------------------------------------------------------------------- - // ---------------------------------------------------------------------------- - - - // User specifies the port number, and the subsystem - public void connect (String hostname, String username, String password, String prompt, int timeOut, int portNum, String subsystem) throws IOException - { - String fn = "SshJcraftWrapper.connect"; - - debugLog.printRTAriDebug (fn, ":::Attempting to connect to "+hostname +" username="+username +" password="+password + " prompt='"+prompt +"' timeOut="+timeOut +" portNum="+portNum +" subsystem="+subsystem); - RouterName = hostname; - jsch = new JSch(); - try - { - session = jsch.getSession(username, hostname, portNum); - UserInfo ui = new MyUserInfo(); - session.setPassword(password); - session.setUserInfo(ui); - session.setConfig("StrictHostKeyChecking", "no"); - session.connect(timeOut); - session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!! - channel = session.openChannel("subsystem"); - ((ChannelSubsystem)channel).setSubsystem(subsystem); - // ((ChannelSubsystem)channel).setPtyType("vt102"); - ((ChannelSubsystem)channel).setPty(true); - - inputStream = channel.getInputStream(); - dis = new DataInputStream(inputStream); - reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE); - channel.connect(); - debugLog.printRTAriDebug (fn, "Successfully connected."); - debugLog.printRTAriDebug (fn, "Five second sleep...."); - try { Thread.sleep(5000); } catch (java.lang.InterruptedException ee) { boolean ignore = true; } - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception. e="+e); - throw new IOException(e.toString()); - } - } - - public void connect (String hostName, String username, String password, int portNumber) throws IOException - { - String fn = "SshJcraftWrapper.connect"; - jsch = new JSch(); - debugLog.printRTAriDebug (fn, "::Attempting to connect to "+hostName +" username="+username +" password="+password +" portNumber="+portNumber); - debugLog.printRTAriDebug (fn, "Trace C"); - RouterName = hostName; - this.hostName = hostName; - userName = username; - passWord = password; - try - { - java.util.Properties config = new java.util.Properties(); - config.put("StrictHostKeyChecking", "no"); - session = jsch.getSession(username, hostName, 22); - // session = jsch.getSession(username, hostName, portNumber); - UserInfo ui = new MyUserInfo(); - session.setConfig(config); - session.setPassword(password); - session.setUserInfo(ui); - session.connect(30000); - channel = session.openChannel("shell"); - session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!! - ((ChannelShell)channel).setPtyType("vt102"); - inputStream = channel.getInputStream(); - dis = new DataInputStream(inputStream); - reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE); - channel.connect(); - debugLog.printRTAriDebug (fn, "::Successfully connected."); - debugLog.printRTAriDebug (fn, "::Flushing input buffer"); - try - { - receiveUntil(":~#", 9000, "No cmd was sent, just waiting, but we can stop on a '~#'"); - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception::: Nothing to flush out."); - } - - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception. e="+e); - // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostName +" "+e); - throw new IOException(e.toString()); - } - } - - - public void put(String sourcePath, String destDirectory) throws IOException - { - String fn = "SshJcraftWrapper.sftp"; - try - { - Session sftpSession = jsch.getSession(userName, hostName, 22); - UserInfo ui = new MyUserInfo(); - sftpSession.setPassword(passWord); - sftpSession.setUserInfo(ui); - sftpSession.connect(30*1000); - debugLog.printRTAriDebug (fn, "Opening up an sftp channel...."); - ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp"); - debugLog.printRTAriDebug (fn, "Connecting...."); - sftp.connect(); - debugLog.printRTAriDebug (fn, "Sending "+sourcePath +" --> "+destDirectory); - sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE); - debugLog.printRTAriDebug (fn, "Sent successfully"); - sftpSession.disconnect(); - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e); - // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); - throw new IOException(e.toString()); - } - } - - public void put(InputStream is, String fullPathDest, String hostName, String userName, String passWord) throws IOException - { - String fn = "SshJcraftWrapper.put"; - Session sftpSession = null; - try - { - debugLog.printRTAriDebug (fn, "userName="+userName +" hostName="+hostName +" passWord="+passWord); - jsch = new JSch(); - java.util.Properties config = new java.util.Properties(); - config.put("StrictHostKeyChecking", "no"); - sftpSession = jsch.getSession(userName, hostName, 22); - UserInfo ui = new MyUserInfo(); - sftpSession.setPassword(passWord); - sftpSession.setUserInfo(ui); - sftpSession.setConfig(config); - sftpSession.connect(30*1000); - debugLog.printRTAriDebug (fn, "Opening up an sftp channel...."); - ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp"); - debugLog.printRTAriDebug (fn, "Connecting...."); - sftp.connect(); - String oldFiles = fullPathDest +"*"; - debugLog.printRTAriDebug (fn, "Deleting old files --> "+oldFiles); - try{ - sftp.rm(oldFiles); - debugLog.printRTAriDebug (fn, "Sending stringOfData --> "+fullPathDest); - } - catch(SftpException sft){ - String exp = "No such file"; - if(sft.getMessage()!=null && sft.getMessage().contains(exp)) - debugLog.printRTAriDebug (fn, "No files found -- Continue"); - else{ - debugLog.printRTAriDebug (fn, "Exception while sftp.rm " + sft.getMessage()); - sft.printStackTrace(); - throw sft; - } - } - sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE); - debugLog.printRTAriDebug (fn, "Sent successfully"); - sftpSession.disconnect(); - sftpSession = null; - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e); - sftpSession.disconnect(); - sftpSession = null; - // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); - throw new IOException(e.toString()); - } - } - - - public String get(String fullFilePathName, String hostName, String userName, String passWord) throws IOException - { - String fn = "SshJcraftWrapper.get"; - Session sftpSession = null; - try - { - debugLog.printRTAriDebug (fn, "userName="+userName +" hostName="+hostName +" passWord="+passWord); - jsch = new JSch(); - sftpSession = jsch.getSession(userName, hostName, 22); - java.util.Properties config = new java.util.Properties(); - config.put("StrictHostKeyChecking", "no"); - UserInfo ui = new MyUserInfo(); - sftpSession.setPassword(passWord); - sftpSession.setUserInfo(ui); - sftpSession.setConfig(config); - sftpSession.connect(30*1000); - debugLog.printRTAriDebug (fn, "Opening up an sftp channel...."); - ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp"); - debugLog.printRTAriDebug (fn, "Connecting...."); - sftp.connect(); - InputStream in = null; - in = sftp.get(fullFilePathName); - String sftpFileString = readInputStreamAsString(in); - debugLog.printRTAriDebug (fn, "Retreived successfully"); - // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString); - sftpSession.disconnect(); - sftpSession = null; - return(sftpFileString); - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e); - sftpSession.disconnect(); - sftpSession = null; - // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); - throw new IOException(e.toString()); - } - } - - public String send(String cmd, String delimiter) throws IOException - { - String fn = "SshJcraftWrapper.send"; - OutputStream out = channel.getOutputStream(); - DataOutputStream dos = new DataOutputStream(out); - - if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r')) - cmd += "\n"; - int length = cmd.length(); - int i = -1; - int nchars = 300000; - int ncharsTotalSent = 0; - int ncharsSent = 0; - - debugLog.printRTAriDebug (fn, "Length of cmd is:" +length); // 2,937,706 - debugLog.printRTAriDebug (fn, "Length of cmd is:" +length); // 2,937,706 - try - { - if (length > 600000) - { - int timeout = 9000; - for (i=0; i varmap, String var) - { - Object o = createStructure(varmap, var); - return generateXml(o, 0); - } - - private static Object createStructure(Map flatmap, String var) - { - if (flatmap.containsKey(var)) - return flatmap.get(var); - - Map mm = new HashMap<>(); - for (String k : flatmap.keySet()) - if (k.startsWith(var + ".")) - { - int i1 = k.indexOf('.', var.length() + 1); - int i2 = k.indexOf('[', var.length() + 1); - int i3 = k.length(); - if (i1 > 0 && i1 < i3) - i3 = i1; - if (i2 > 0 && i2 < i3) - i3 = i2; - String k1 = k.substring(var.length() + 1, i3); - String var1 = k.substring(0, i3); - if (!mm.containsKey(k1)) - { - Object str = createStructure(flatmap, var1); - if (str != null && (!(str instanceof String) || ((String) str).trim().length() > 0)) - mm.put(k1, str); - } - } - if (!mm.isEmpty()) - return mm; - - boolean arrayFound = false; - for (String k : flatmap.keySet()) - if (k.startsWith(var + "[")) - { - arrayFound = true; - break; - } - - if (arrayFound) - { - List ll = new ArrayList<>(); - - int length = Integer.MAX_VALUE; - String lengthStr = flatmap.get(var + "_length"); - if (lengthStr != null) - { - try - { - length = Integer.parseInt(lengthStr); - } - catch (Exception e) - { - log.warn("Invalid number for " + var + "_length:" + lengthStr); - } - } - - for (int i = 0; i < length; i++) - { - Object v = createStructure(flatmap, var + '[' + i + ']'); - if (v == null) - break; - ll.add(v); - } - - if (!ll.isEmpty()) - return ll; - } - - return null; - } - - @SuppressWarnings("unchecked") - private static String generateXml(Object o, int indent) - { - if (o == null) - return null; - - if (o instanceof String) - return (String) o; - - if (o instanceof Map) - { - StringBuilder ss = new StringBuilder(); - Map mm = (Map) o; - for (String k : mm.keySet()) - { - Object v = mm.get(k); - if (v instanceof String) - { - ss.append(pad(indent)).append('<').append(k).append('>'); - ss.append(v); - ss.append("').append('\n'); - } - else if (v instanceof Map) - { - ss.append(pad(indent)).append('<').append(k).append('>').append('\n'); - ss.append(generateXml(v, indent + 1)); - ss.append(pad(indent)).append("').append('\n'); - } - else if (v instanceof List) - { - List ll = (List) v; - for (Object o1 : ll) - { - ss.append(pad(indent)).append('<').append(k).append('>').append('\n'); - ss.append(generateXml(o1, indent + 1)); - ss.append(pad(indent)).append("').append('\n'); - } - } - } - return ss.toString(); - } - - return null; - } - - private static String pad(int n) - { - String s = ""; - for (int i = 0; i < n; i++) - s += '\t'; - return s; - } -} diff --git a/appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestConfigComponentAdaptor.java b/appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestConfigComponentAdaptor.java new file mode 100644 index 000000000..2a258f187 --- /dev/null +++ b/appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestConfigComponentAdaptor.java @@ -0,0 +1,132 @@ +package org.onap.appc.ccadaptor; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.junit.Test; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class TestConfigComponentAdaptor { + + + @Test + public void testGetCliRunningConfig(){ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String Get_config_template = ("get_config_template"); + String key = "GetCliRunningConfig"; + Map parameters = new HashMap(); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", Get_config_template); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); + cca.configure(key, parameters, ctx); + + } + + @Test + public void testDownloadCliConfig(){ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String Get_config_template = ("get_config_template"); + String key = "DownloadCliConfig"; + Map parameters = new HashMap(); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", Get_config_template); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); + cca.configure(key, parameters, ctx); + + } + + @Test + public void testXmlDownload(){ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String Get_config_template = ("get_config_template"); + String key = "xml-download"; + Map parameters = new HashMap(); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", Get_config_template); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); + cca.configure(key, parameters, ctx); + } + + @Test + public void testXmlGetrunningconfig(){ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String Get_config_template = ("get_config_template"); + String key = "xml-getrunningconfig"; + Map parameters = new HashMap(); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", Get_config_template); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); + cca.configure(key, parameters, ctx); + + } + + @Test + public void testEscapeSql(){ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String Get_config_template = ("get_config_template"); + String key = "escapeSql"; + Map parameters = new HashMap(); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", Get_config_template); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); + cca.configure(key, parameters, ctx); + } + + @Test + public void testAll(){ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String Get_config_template = ("test"); + String Download_config_template = ("test"); + String key = "GetCliRunningConfig"; + Map parameters = new HashMap(); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Protocol", "netconf"); + parameters.put("Contents", "Contents"); + parameters.put("Get_config_template", Get_config_template); + parameters.put("Download_config_template", Download_config_template); + parameters.put("Config_contents", "config\nsystem\nservice-interface serv1\nipv4\ngateway-ip-address 192.168.30.44"); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); + cca.configure(key, parameters, ctx); + + + } + + +} diff --git a/appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestDebugLog.java b/appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestDebugLog.java new file mode 100644 index 000000000..c7a7953bd --- /dev/null +++ b/appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestDebugLog.java @@ -0,0 +1,19 @@ +package org.onap.appc.ccadaptor; + +import org.junit.Test; + +public class TestDebugLog { + + @Test + public void testAppendToFile() { + DebugLog.appendToFile("appendData"); + } + + @Test + public void TestGetDateTime() { + String DateTime = DebugLog.getDateTime(); + System.out.println(DateTime); + + } + +} diff --git a/appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestEncryptionTool.java b/appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestEncryptionTool.java new file mode 100644 index 000000000..a4a092e23 --- /dev/null +++ b/appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestEncryptionTool.java @@ -0,0 +1,24 @@ +package org.onap.appc.ccadaptor; + +import org.junit.Assert; +import org.junit.Test; + +public class TestEncryptionTool { + + @Test + public void testEncrypt() { + EncryptionTool tool = EncryptionTool.getInstance(); + String value = tool.encrypt("encrypt"); + Assert.assertEquals("enc:JjEZHlg7VQ==", value); + System.out.println(value); + } + + @Test + public void testDecrypt() { + EncryptionTool tool = EncryptionTool.getInstance(); + String value = tool.decrypt("enc:JjEZHlg7VQ=="); + Assert.assertEquals("encrypt", value); + System.out.println(value); + } + +} diff --git a/appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestSshJcraftWrapper.java b/appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestSshJcraftWrapper.java new file mode 100644 index 000000000..2a2adb75e --- /dev/null +++ b/appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestSshJcraftWrapper.java @@ -0,0 +1,23 @@ +package org.onap.appc.ccadaptor; + +import org.junit.Assert; +import org.junit.Test; + +public class TestSshJcraftWrapper { + + @Test + public void TestCheckIfReceivedStringMatchesDelimeter(){ + SshJcraftWrapper wrapper = new SshJcraftWrapper(); + wrapper.getTheDate(); + boolean result = wrapper.checkIfReceivedStringMatchesDelimeter("#", "config#", "config#"); + System.out.println(result); + } + + @Test + public void testRemoveWhiteSpaceAndNewLineCharactersAroundString(){ + SshJcraftWrapper wrapper = new SshJcraftWrapper(); + String nameSpace = wrapper.removeWhiteSpaceAndNewLineCharactersAroundString("namespace"); + Assert.assertEquals("namespace", nameSpace); + } + +} diff --git a/appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestXmlUtil.java b/appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestXmlUtil.java new file mode 100644 index 000000000..f3e7a1004 --- /dev/null +++ b/appc-config/appc-config-adaptor/provider/src/main/test/org/onap/appc/ccadaptor/TestXmlUtil.java @@ -0,0 +1,19 @@ +package org.onap.appc.ccadaptor; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + +public class TestXmlUtil { + + @Test + public void testXml() { + Map varmap = new HashMap(); + varmap.put("network.data", "ipv4"); + String xmlData = XmlUtil.getXml(varmap, "network"); + Assert.assertEquals("ipv4\n", xmlData); + System.out.println(xmlData); + } +} diff --git a/appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestConfigComponentAdaptor.java b/appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestConfigComponentAdaptor.java deleted file mode 100644 index 2a258f187..000000000 --- a/appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestConfigComponentAdaptor.java +++ /dev/null @@ -1,132 +0,0 @@ -package org.onap.appc.ccadaptor; - -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import org.junit.Test; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class TestConfigComponentAdaptor { - - - @Test - public void testGetCliRunningConfig(){ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String Get_config_template = ("get_config_template"); - String key = "GetCliRunningConfig"; - Map parameters = new HashMap(); - parameters.put("Host_ip_address", "test"); - parameters.put("User_name", "test"); - parameters.put("Password", "password"); - parameters.put("Port_number", "22"); - parameters.put("Get_config_template", Get_config_template); - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); - cca.configure(key, parameters, ctx); - - } - - @Test - public void testDownloadCliConfig(){ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String Get_config_template = ("get_config_template"); - String key = "DownloadCliConfig"; - Map parameters = new HashMap(); - parameters.put("Host_ip_address", "test"); - parameters.put("User_name", "test"); - parameters.put("Password", "password"); - parameters.put("Port_number", "22"); - parameters.put("Get_config_template", Get_config_template); - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); - cca.configure(key, parameters, ctx); - - } - - @Test - public void testXmlDownload(){ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String Get_config_template = ("get_config_template"); - String key = "xml-download"; - Map parameters = new HashMap(); - parameters.put("Host_ip_address", "test"); - parameters.put("User_name", "test"); - parameters.put("Password", "password"); - parameters.put("Port_number", "22"); - parameters.put("Get_config_template", Get_config_template); - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); - cca.configure(key, parameters, ctx); - } - - @Test - public void testXmlGetrunningconfig(){ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String Get_config_template = ("get_config_template"); - String key = "xml-getrunningconfig"; - Map parameters = new HashMap(); - parameters.put("Host_ip_address", "test"); - parameters.put("User_name", "test"); - parameters.put("Password", "password"); - parameters.put("Port_number", "22"); - parameters.put("Get_config_template", Get_config_template); - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); - cca.configure(key, parameters, ctx); - - } - - @Test - public void testEscapeSql(){ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String Get_config_template = ("get_config_template"); - String key = "escapeSql"; - Map parameters = new HashMap(); - parameters.put("Host_ip_address", "test"); - parameters.put("User_name", "test"); - parameters.put("Password", "password"); - parameters.put("Port_number", "22"); - parameters.put("Get_config_template", Get_config_template); - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); - cca.configure(key, parameters, ctx); - } - - @Test - public void testAll(){ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String Get_config_template = ("test"); - String Download_config_template = ("test"); - String key = "GetCliRunningConfig"; - Map parameters = new HashMap(); - parameters.put("Host_ip_address", "test"); - parameters.put("User_name", "test"); - parameters.put("Password", "password"); - parameters.put("Port_number", "22"); - parameters.put("Protocol", "netconf"); - parameters.put("Contents", "Contents"); - parameters.put("Get_config_template", Get_config_template); - parameters.put("Download_config_template", Download_config_template); - parameters.put("Config_contents", "config\nsystem\nservice-interface serv1\nipv4\ngateway-ip-address 192.168.30.44"); - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); - cca.configure(key, parameters, ctx); - - - } - - -} diff --git a/appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestDebugLog.java b/appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestDebugLog.java deleted file mode 100644 index c7a7953bd..000000000 --- a/appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestDebugLog.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.onap.appc.ccadaptor; - -import org.junit.Test; - -public class TestDebugLog { - - @Test - public void testAppendToFile() { - DebugLog.appendToFile("appendData"); - } - - @Test - public void TestGetDateTime() { - String DateTime = DebugLog.getDateTime(); - System.out.println(DateTime); - - } - -} diff --git a/appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestEncryptionTool.java b/appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestEncryptionTool.java deleted file mode 100644 index a4a092e23..000000000 --- a/appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestEncryptionTool.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.onap.appc.ccadaptor; - -import org.junit.Assert; -import org.junit.Test; - -public class TestEncryptionTool { - - @Test - public void testEncrypt() { - EncryptionTool tool = EncryptionTool.getInstance(); - String value = tool.encrypt("encrypt"); - Assert.assertEquals("enc:JjEZHlg7VQ==", value); - System.out.println(value); - } - - @Test - public void testDecrypt() { - EncryptionTool tool = EncryptionTool.getInstance(); - String value = tool.decrypt("enc:JjEZHlg7VQ=="); - Assert.assertEquals("encrypt", value); - System.out.println(value); - } - -} diff --git a/appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestSshJcraftWrapper.java b/appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestSshJcraftWrapper.java deleted file mode 100644 index 2a2adb75e..000000000 --- a/appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestSshJcraftWrapper.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.onap.appc.ccadaptor; - -import org.junit.Assert; -import org.junit.Test; - -public class TestSshJcraftWrapper { - - @Test - public void TestCheckIfReceivedStringMatchesDelimeter(){ - SshJcraftWrapper wrapper = new SshJcraftWrapper(); - wrapper.getTheDate(); - boolean result = wrapper.checkIfReceivedStringMatchesDelimeter("#", "config#", "config#"); - System.out.println(result); - } - - @Test - public void testRemoveWhiteSpaceAndNewLineCharactersAroundString(){ - SshJcraftWrapper wrapper = new SshJcraftWrapper(); - String nameSpace = wrapper.removeWhiteSpaceAndNewLineCharactersAroundString("namespace"); - Assert.assertEquals("namespace", nameSpace); - } - -} diff --git a/appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestXmlUtil.java b/appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestXmlUtil.java deleted file mode 100644 index f3e7a1004..000000000 --- a/appc-config/appc-config-adaptor/provider/src/main/test/org/openecomp/appc/ccadaptor/TestXmlUtil.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.onap.appc.ccadaptor; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Assert; -import org.junit.Test; - -public class TestXmlUtil { - - @Test - public void testXml() { - Map varmap = new HashMap(); - varmap.put("network.data", "ipv4"); - String xmlData = XmlUtil.getXml(varmap, "network"); - Assert.assertEquals("ipv4\n", xmlData); - System.out.println(xmlData); - } -} diff --git a/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/ConfigComponentAdaptorTest.java b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/ConfigComponentAdaptorTest.java new file mode 100644 index 000000000..4cd3934ae --- /dev/null +++ b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/ConfigComponentAdaptorTest.java @@ -0,0 +1,251 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.ccadaptor; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.powermock.reflect.Whitebox; + +public class ConfigComponentAdaptorTest { + + + @Test + public void testGetCliRunningConfig(){ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String Get_config_template = ("get_config_template"); + String key = "GetCliRunningConfig"; + Map parameters = new HashMap(); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", Get_config_template); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); + cca.configure(key, parameters, ctx); + } + + @Test + public void testDownloadCliConfig(){ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String Get_config_template = ("get_config_template"); + String key = "DownloadCliConfig"; + Map parameters = new HashMap(); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", Get_config_template); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); + cca.configure(key, parameters, ctx); + } + + @Test + public void testXmlDownload(){ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String Get_config_template = ("get_config_template"); + String key = "xml-download"; + Map parameters = new HashMap(); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", Get_config_template); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); + cca.configure(key, parameters, ctx); + } + + @Test + public void testXmlGetrunningconfig(){ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String Get_config_template = ("get_config_template"); + String key = "xml-getrunningconfig"; + Map parameters = new HashMap(); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", Get_config_template); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); + cca.configure(key, parameters, ctx); + } + + @Test + public void testEscapeSql(){ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String Get_config_template = ("get_config_template"); + String key = "escapeSql"; + Map parameters = new HashMap(); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", Get_config_template); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); + cca.configure(key, parameters, ctx); + } + + @Test + public void testAll(){ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String Get_config_template = ("test"); + String Download_config_template = ("test"); + String key = "GetCliRunningConfig"; + Map parameters = new HashMap(); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Protocol", "netconf"); + parameters.put("Contents", "Contents"); + parameters.put("Get_config_template", Get_config_template); + parameters.put("Download_config_template", Download_config_template); + parameters.put("Config_contents", "test"); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); + cca.configure(key, parameters, ctx); + } + + @Test(expected=Exception.class) + public void testAll1(){ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String key = "get"; + Map parameters = new HashMap(); + parameters.put("Host_ip_address", "test"); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); + cca.configure(key, parameters, ctx); + } + + @Test(expected=Exception.class) + public void testAll2(){ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String key = "cli"; + Map parameters = new HashMap(); + parameters.put("Host_ip_address", "test"); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); + cca.configure(key, parameters, ctx); + } + + @Test + public void testGetStringBetweenQuotes() throws Exception{ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String result =Whitebox.invokeMethod(cca, "getStringBetweenQuotes","\"testvalue\""); + Assert.assertEquals("testvalue", result); + } + + @Test + public void testBuildXmlRequest() throws Exception{ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + Map param = new HashMap(); + Whitebox.invokeMethod(cca, "buildXmlRequest",param,"template"); + } + + @Test + public void testTrimResponse() throws Exception{ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String result =Whitebox.invokeMethod(cca, "trimResponse","testData"); + Assert.assertEquals("", result); + } + + @Test + public void testBuildNetworkData2() throws Exception{ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + SvcLogicContext ctx = new SvcLogicContext(); + String result =Whitebox.invokeMethod(cca, "buildNetworkData2",ctx,"template","operation"); + Assert.assertEquals("template", result); + } + + //@Test + public void testGetLastFewLinesOfFile() throws Exception{ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + Whitebox.invokeMethod(cca, "readFile","test"); + } + + @Test + public void testConnect() throws Exception{ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + SvcLogicContext ctx = new SvcLogicContext(); + cca.activate("key", ctx); + + } + + @Test(expected=Exception.class) + public void testActivate() throws Exception{ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + SvcLogicContext ctx = new SvcLogicContext(); + String result =Whitebox.invokeMethod(cca, "activate",ctx,true); + Assert.assertEquals("template", result); + } + + @Test(expected=Exception.class) + public void testAudit() throws Exception{ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + SvcLogicContext ctx = new SvcLogicContext(); + String result =Whitebox.invokeMethod(cca, "audit",ctx,"test"); + Assert.assertEquals("template", result); + } + + @Test(expected=Exception.class) + public void testPrepare() throws Exception{ + Properties props = null; + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + SvcLogicContext ctx = new SvcLogicContext(); + String result =Whitebox.invokeMethod(cca, "prepare",ctx,"test","test"); + Assert.assertEquals("template", result); + } +} diff --git a/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/DebugLogTest.java b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/DebugLogTest.java new file mode 100644 index 000000000..6fcb62675 --- /dev/null +++ b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/DebugLogTest.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.ccadaptor; + +import org.junit.Assert; +import org.junit.Test; + +public class DebugLogTest { + + @Test + public void TestGetDateTime() { + String DateTime = DebugLog.getDateTime(); + Assert.assertNotNull(DateTime); + } + +} \ No newline at end of file diff --git a/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/EncryptionToolTest.java b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/EncryptionToolTest.java new file mode 100644 index 000000000..afa9137db --- /dev/null +++ b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/EncryptionToolTest.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.ccadaptor; + +import org.junit.Assert; +import org.junit.Test; + +public class EncryptionToolTest { + + @Test + public void testEncrypt() { + EncryptionTool tool = EncryptionTool.getInstance(); + String value = tool.encrypt("encrypt"); + Assert.assertEquals("enc:JjEZHlg7VQ==", value); + } + + @Test + public void testDecrypt() { + EncryptionTool tool = EncryptionTool.getInstance(); + String value = tool.decrypt("enc:JjEZHlg7VQ=="); + Assert.assertEquals("encrypt", value); + } + +} \ No newline at end of file diff --git a/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/SshJcraftWrapperTest.java b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/SshJcraftWrapperTest.java new file mode 100644 index 000000000..ef1bf7d7f --- /dev/null +++ b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/SshJcraftWrapperTest.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.ccadaptor; + + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.URL; + +import org.junit.Assert; +import org.junit.Test; + +public class SshJcraftWrapperTest { + + @Test + public void TestCheckIfReceivedStringMatchesDelimeter(){ + SshJcraftWrapper wrapper = new SshJcraftWrapper(); + wrapper.getTheDate(); + boolean result = wrapper.checkIfReceivedStringMatchesDelimeter("#", "test#", "test#"); + Assert.assertEquals(true, result); + } + + @Test + public void testRemoveWhiteSpaceAndNewLineCharactersAroundString(){ + SshJcraftWrapper wrapper = new SshJcraftWrapper(); + String nameSpace = wrapper.removeWhiteSpaceAndNewLineCharactersAroundString("namespace "); + Assert.assertEquals("namespace", nameSpace); + } + + @Test + public void testStripOffCmdFromRouterResponse(){ + SshJcraftWrapper wrapper = new SshJcraftWrapper(); + String result = wrapper.stripOffCmdFromRouterResponse("test\nsuccess"); + Assert.assertEquals("success\n", result); + } + + //@Test + public void testGetLastFewLinesOfFile() throws FileNotFoundException, IOException{ + SshJcraftWrapper wrapper = new SshJcraftWrapper(); + URL path = SshJcraftWrapperTest.class.getResource("Test"); + File file = new File(path.getFile()); + String value = wrapper.getLastFewLinesOfFile(file,1); + Assert.assertEquals("\nTest data 3", value); + } + + @Test(expected=Exception.class) + public void testSetRouterCommandType() throws IOException{ + SshJcraftWrapper wrapper = new SshJcraftWrapper(); + wrapper.setRouterCommandType("test"); + wrapper.receiveUntil("test", 2, "test"); + } + + @Test + public void testValues() throws IOException{ + SshJcraftWrapper wrapper = new SshJcraftWrapper(); + wrapper.setEquipNameCode("testcode"); + wrapper.setRouterCommandType("testcommand"); + String equipName =wrapper.getEquipNameCode(); + wrapper.getHostName(); + wrapper.getPassWord(); + wrapper.getRouterName(); + wrapper.getUserName(); + wrapper.getTheDate(); + Assert.assertEquals("testcode", equipName); + } + + @Test(expected=Exception.class) + public void testSetRouterCommandType2() throws IOException{ + SshJcraftWrapper wrapper = new SshJcraftWrapper(); + wrapper.appendToRouterFile("test", 2); + StringBuffer buffer = new StringBuffer(); + buffer.append("test"); + wrapper.appendToRouterFile("Test.txt", buffer); + wrapper.receiveUntilBufferFlush(3, 4, "test"); + } + + @Test(expected=Exception.class) + public void testSetRouterCommandType3() throws IOException{ + SshJcraftWrapper wrapper = new SshJcraftWrapper(); + wrapper.checkIfReceivedStringMatchesDelimeter(3, "test"); + } +} diff --git a/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/XmlUtilTest.java b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/XmlUtilTest.java new file mode 100644 index 000000000..59cabc26f --- /dev/null +++ b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/XmlUtilTest.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.ccadaptor; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + +public class XmlUtilTest { + + @Test + public void testXml() { + Map varmap = new HashMap(); + varmap.put("network.data", "test"); + String xmlData = XmlUtil.getXml(varmap, "network"); + Assert.assertEquals("test\n", xmlData); + } +} \ No newline at end of file diff --git a/appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/ConfigComponentAdaptorTest.java b/appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/ConfigComponentAdaptorTest.java deleted file mode 100644 index 4cd3934ae..000000000 --- a/appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/ConfigComponentAdaptorTest.java +++ /dev/null @@ -1,251 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.ccadaptor; - -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.powermock.reflect.Whitebox; - -public class ConfigComponentAdaptorTest { - - - @Test - public void testGetCliRunningConfig(){ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String Get_config_template = ("get_config_template"); - String key = "GetCliRunningConfig"; - Map parameters = new HashMap(); - parameters.put("Host_ip_address", "test"); - parameters.put("User_name", "test"); - parameters.put("Password", "password"); - parameters.put("Port_number", "22"); - parameters.put("Get_config_template", Get_config_template); - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); - cca.configure(key, parameters, ctx); - } - - @Test - public void testDownloadCliConfig(){ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String Get_config_template = ("get_config_template"); - String key = "DownloadCliConfig"; - Map parameters = new HashMap(); - parameters.put("Host_ip_address", "test"); - parameters.put("User_name", "test"); - parameters.put("Password", "password"); - parameters.put("Port_number", "22"); - parameters.put("Get_config_template", Get_config_template); - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); - cca.configure(key, parameters, ctx); - } - - @Test - public void testXmlDownload(){ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String Get_config_template = ("get_config_template"); - String key = "xml-download"; - Map parameters = new HashMap(); - parameters.put("Host_ip_address", "test"); - parameters.put("User_name", "test"); - parameters.put("Password", "password"); - parameters.put("Port_number", "22"); - parameters.put("Get_config_template", Get_config_template); - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); - cca.configure(key, parameters, ctx); - } - - @Test - public void testXmlGetrunningconfig(){ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String Get_config_template = ("get_config_template"); - String key = "xml-getrunningconfig"; - Map parameters = new HashMap(); - parameters.put("Host_ip_address", "test"); - parameters.put("User_name", "test"); - parameters.put("Password", "password"); - parameters.put("Port_number", "22"); - parameters.put("Get_config_template", Get_config_template); - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); - cca.configure(key, parameters, ctx); - } - - @Test - public void testEscapeSql(){ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String Get_config_template = ("get_config_template"); - String key = "escapeSql"; - Map parameters = new HashMap(); - parameters.put("Host_ip_address", "test"); - parameters.put("User_name", "test"); - parameters.put("Password", "password"); - parameters.put("Port_number", "22"); - parameters.put("Get_config_template", Get_config_template); - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); - cca.configure(key, parameters, ctx); - } - - @Test - public void testAll(){ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String Get_config_template = ("test"); - String Download_config_template = ("test"); - String key = "GetCliRunningConfig"; - Map parameters = new HashMap(); - parameters.put("Host_ip_address", "test"); - parameters.put("User_name", "test"); - parameters.put("Password", "password"); - parameters.put("Port_number", "22"); - parameters.put("Protocol", "netconf"); - parameters.put("Contents", "Contents"); - parameters.put("Get_config_template", Get_config_template); - parameters.put("Download_config_template", Download_config_template); - parameters.put("Config_contents", "test"); - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); - cca.configure(key, parameters, ctx); - } - - @Test(expected=Exception.class) - public void testAll1(){ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String key = "get"; - Map parameters = new HashMap(); - parameters.put("Host_ip_address", "test"); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); - cca.configure(key, parameters, ctx); - } - - @Test(expected=Exception.class) - public void testAll2(){ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String key = "cli"; - Map parameters = new HashMap(); - parameters.put("Host_ip_address", "test"); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name", "test"); - cca.configure(key, parameters, ctx); - } - - @Test - public void testGetStringBetweenQuotes() throws Exception{ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String result =Whitebox.invokeMethod(cca, "getStringBetweenQuotes","\"testvalue\""); - Assert.assertEquals("testvalue", result); - } - - @Test - public void testBuildXmlRequest() throws Exception{ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - Map param = new HashMap(); - Whitebox.invokeMethod(cca, "buildXmlRequest",param,"template"); - } - - @Test - public void testTrimResponse() throws Exception{ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String result =Whitebox.invokeMethod(cca, "trimResponse","testData"); - Assert.assertEquals("", result); - } - - @Test - public void testBuildNetworkData2() throws Exception{ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - SvcLogicContext ctx = new SvcLogicContext(); - String result =Whitebox.invokeMethod(cca, "buildNetworkData2",ctx,"template","operation"); - Assert.assertEquals("template", result); - } - - //@Test - public void testGetLastFewLinesOfFile() throws Exception{ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - Whitebox.invokeMethod(cca, "readFile","test"); - } - - @Test - public void testConnect() throws Exception{ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - SvcLogicContext ctx = new SvcLogicContext(); - cca.activate("key", ctx); - - } - - @Test(expected=Exception.class) - public void testActivate() throws Exception{ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - SvcLogicContext ctx = new SvcLogicContext(); - String result =Whitebox.invokeMethod(cca, "activate",ctx,true); - Assert.assertEquals("template", result); - } - - @Test(expected=Exception.class) - public void testAudit() throws Exception{ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - SvcLogicContext ctx = new SvcLogicContext(); - String result =Whitebox.invokeMethod(cca, "audit",ctx,"test"); - Assert.assertEquals("template", result); - } - - @Test(expected=Exception.class) - public void testPrepare() throws Exception{ - Properties props = null; - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - SvcLogicContext ctx = new SvcLogicContext(); - String result =Whitebox.invokeMethod(cca, "prepare",ctx,"test","test"); - Assert.assertEquals("template", result); - } -} diff --git a/appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/DebugLogTest.java b/appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/DebugLogTest.java deleted file mode 100644 index 6fcb62675..000000000 --- a/appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/DebugLogTest.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.ccadaptor; - -import org.junit.Assert; -import org.junit.Test; - -public class DebugLogTest { - - @Test - public void TestGetDateTime() { - String DateTime = DebugLog.getDateTime(); - Assert.assertNotNull(DateTime); - } - -} \ No newline at end of file diff --git a/appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/EncryptionToolTest.java b/appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/EncryptionToolTest.java deleted file mode 100644 index afa9137db..000000000 --- a/appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/EncryptionToolTest.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.ccadaptor; - -import org.junit.Assert; -import org.junit.Test; - -public class EncryptionToolTest { - - @Test - public void testEncrypt() { - EncryptionTool tool = EncryptionTool.getInstance(); - String value = tool.encrypt("encrypt"); - Assert.assertEquals("enc:JjEZHlg7VQ==", value); - } - - @Test - public void testDecrypt() { - EncryptionTool tool = EncryptionTool.getInstance(); - String value = tool.decrypt("enc:JjEZHlg7VQ=="); - Assert.assertEquals("encrypt", value); - } - -} \ No newline at end of file diff --git a/appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/SshJcraftWrapperTest.java b/appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/SshJcraftWrapperTest.java deleted file mode 100644 index ef1bf7d7f..000000000 --- a/appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/SshJcraftWrapperTest.java +++ /dev/null @@ -1,105 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.ccadaptor; - - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.net.URL; - -import org.junit.Assert; -import org.junit.Test; - -public class SshJcraftWrapperTest { - - @Test - public void TestCheckIfReceivedStringMatchesDelimeter(){ - SshJcraftWrapper wrapper = new SshJcraftWrapper(); - wrapper.getTheDate(); - boolean result = wrapper.checkIfReceivedStringMatchesDelimeter("#", "test#", "test#"); - Assert.assertEquals(true, result); - } - - @Test - public void testRemoveWhiteSpaceAndNewLineCharactersAroundString(){ - SshJcraftWrapper wrapper = new SshJcraftWrapper(); - String nameSpace = wrapper.removeWhiteSpaceAndNewLineCharactersAroundString("namespace "); - Assert.assertEquals("namespace", nameSpace); - } - - @Test - public void testStripOffCmdFromRouterResponse(){ - SshJcraftWrapper wrapper = new SshJcraftWrapper(); - String result = wrapper.stripOffCmdFromRouterResponse("test\nsuccess"); - Assert.assertEquals("success\n", result); - } - - //@Test - public void testGetLastFewLinesOfFile() throws FileNotFoundException, IOException{ - SshJcraftWrapper wrapper = new SshJcraftWrapper(); - URL path = SshJcraftWrapperTest.class.getResource("Test"); - File file = new File(path.getFile()); - String value = wrapper.getLastFewLinesOfFile(file,1); - Assert.assertEquals("\nTest data 3", value); - } - - @Test(expected=Exception.class) - public void testSetRouterCommandType() throws IOException{ - SshJcraftWrapper wrapper = new SshJcraftWrapper(); - wrapper.setRouterCommandType("test"); - wrapper.receiveUntil("test", 2, "test"); - } - - @Test - public void testValues() throws IOException{ - SshJcraftWrapper wrapper = new SshJcraftWrapper(); - wrapper.setEquipNameCode("testcode"); - wrapper.setRouterCommandType("testcommand"); - String equipName =wrapper.getEquipNameCode(); - wrapper.getHostName(); - wrapper.getPassWord(); - wrapper.getRouterName(); - wrapper.getUserName(); - wrapper.getTheDate(); - Assert.assertEquals("testcode", equipName); - } - - @Test(expected=Exception.class) - public void testSetRouterCommandType2() throws IOException{ - SshJcraftWrapper wrapper = new SshJcraftWrapper(); - wrapper.appendToRouterFile("test", 2); - StringBuffer buffer = new StringBuffer(); - buffer.append("test"); - wrapper.appendToRouterFile("Test.txt", buffer); - wrapper.receiveUntilBufferFlush(3, 4, "test"); - } - - @Test(expected=Exception.class) - public void testSetRouterCommandType3() throws IOException{ - SshJcraftWrapper wrapper = new SshJcraftWrapper(); - wrapper.checkIfReceivedStringMatchesDelimeter(3, "test"); - } -} diff --git a/appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/XmlUtilTest.java b/appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/XmlUtilTest.java deleted file mode 100644 index 59cabc26f..000000000 --- a/appc-config/appc-config-adaptor/provider/src/test/java/org/openecomp/appc/ccadaptor/XmlUtilTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.ccadaptor; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Assert; -import org.junit.Test; - -public class XmlUtilTest { - - @Test - public void testXml() { - Map varmap = new HashMap(); - varmap.put("network.data", "test"); - String xmlData = XmlUtil.getXml(varmap, "network"); - Assert.assertEquals("test\n", xmlData); - } -} \ No newline at end of file diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/SliAuditActivator.java b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/SliAuditActivator.java new file mode 100644 index 000000000..648d8ea86 --- /dev/null +++ b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/SliAuditActivator.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.audit; + +import java.util.LinkedList; +import java.util.List; + +import org.openecomp.sdnc.config.audit.node.CompareNode; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.ConfigurationException; + +public class SliAuditActivator implements BundleActivator{ + + private List registrations = new LinkedList(); + + + private static final EELFLogger log = EELFManager.getInstance().getLogger(SliAuditActivator.class); + + @Override + public void start(BundleContext ctx) throws Exception + { + + CompareNode compareNodePlugin = new CompareNode(); + log.info("Registering service "+ compareNodePlugin.getClass().getName()); + registrations.add(ctx.registerService(compareNodePlugin.getClass().getName(), compareNodePlugin, null)); + + } + @Override + public void stop(BundleContext arg0) throws Exception + { + for (ServiceRegistration registration: registrations) + { + registration.unregister(); + registration = null; + } + + } + +} diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/SliAuditConstant.java b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/SliAuditConstant.java new file mode 100644 index 000000000..0bfaa1e36 --- /dev/null +++ b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/SliAuditConstant.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.audit; + +public class SliAuditConstant { + + public static String STRING_ENCODING = "utf-8"; + public static String Y = "Y"; + public static String N = "N"; + public static String DATA_TYPE_TEXT = "TEXT"; + public static String DATA_TYPE_JSON = "JSON"; + public static String DATA_TYPE_XML = "XML"; + public static String DATA_TYPE_SQL = "SQL"; + + public static String INPUT_PARAM_JSON_DATA = "jsonData"; + public static String INPUT_PARAM_IS_ESCAPED = "isEscaped"; + public static String INPUT_PARAM_BLOCK_KEYS = "blockKeys"; + public static String INPUT_PARAM_LOG_DATA = "logData"; + public static String INPUT_PARAM_CHECK_DATA = "checkData"; + public static String INPUT_PARAM_ESCAPE_DATA = "escapeData"; + public static String INPUT_PARAM_UNESCAPE_DATA = "unEscapeData"; + public static String INPUT_PARAM_DATA_TYPE = "dataType"; + public static String INPUT_PARAM_FILE_NAME = "fileName"; + + public static String INPUT_PARAM_TEMPLATE_DATA = "templateData"; + public static String INPUT_PARAM_TEMPLATE_FILE = "templateFile"; + public static String INPUT_PARAM_TEMPLATE_TYPE = "templateType"; + public static String INPUT_PARAM_DO_PRETTY_OUTPUT = "doPrettyOutput"; + public static String INPUT_PARAM_REQUEST_DATA = "requestData"; + public static String INPUT_PARAM_RESPONSE_PRIFIX = "responsePrefix"; + + + public static String OUTPUT_PARAM_MERGED_DATA = "mergedData"; + public static String OUTPUT_PARAM_TRANSFORMED_DATA = "transformedData"; + public static String OUTPUT_PARAM_FILE_DATA = "fileData"; + public static String OUTPUT_PARAM_PARSED_ERROR = "parsedError"; + public static String OUTPUT_PARAM_DATA_TYPE = "dataType"; + public static String OUTPUT_PARAM_STATUS = "status"; + public static String OUTPUT_PARAM_ERROR_MESSAGE = "error-message"; + public static String OUTPUT_PARAM_ESCAPE_DATA = "escapeData"; + public static String OUTPUT_PARAM_UNESCAPE_DATA = "unEscapeData"; + + public static String OUTPUT_STATUS_SUCCESS = "success"; + public static String OUTPUT_STATUS_FAILURE = "failure"; + +} diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareCliData.java b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareCliData.java new file mode 100644 index 000000000..969d126bb --- /dev/null +++ b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareCliData.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.audit.node; + +public class CompareCliData implements CompareDataInterface{ + + String payloadX; + String payloadY; + + public CompareCliData(String payloadX, String payloadY) + { + super(); + this.payloadX = payloadX; + this.payloadY = payloadY; + } + + @Override + public boolean compare() throws Exception + { + if(payloadX != null && payloadX.equals(payloadY)) + return true; + else + return false; + } +} diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareConstants.java b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareConstants.java new file mode 100644 index 000000000..42b18d5c3 --- /dev/null +++ b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareConstants.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.audit.node; + +public class CompareConstants { + + + public static final String FORMAT_JSON = "RESTCONF"; + public static final String FORMAT_XML = "XML"; + public static final String FORMAT_CLI = "CLI"; + public static final String NETCONF_XML = "NETCONF-XML"; + public static final String RESTCONF_XML = "RESTCONF-XML"; + + + public static final String STATUS_FAILURE = "FAILURE"; + public static final String RESPONSE_STATUS = "STATUS"; + public static final String STATUS_SUCCESS = "SUCCESS"; + + public static final String ERROR_CODE = "Error-code"; + + public static final String ERROR_MESSAGE = "Error-Message"; + public static final String ERROR_MESSAGE_DEATIL = "Compare Node Failed-Internal Error.See karaf log file"; + + public static final String NO_MATCH_MESSAGE = "The configurations do not match"; +} diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareDataInterface.java b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareDataInterface.java new file mode 100644 index 000000000..95f154e2e --- /dev/null +++ b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareDataInterface.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.audit.node; + + +public interface CompareDataInterface +{ + boolean compare() throws Exception; +} diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareJsonData.java b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareJsonData.java new file mode 100644 index 000000000..422ac30ac --- /dev/null +++ b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareJsonData.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.audit.node; + +import java.io.IOException; +import java.util.Map; + + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + + +public class CompareJsonData implements CompareDataInterface { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(CompareJsonData.class); + + String payloadX; + String payloadY; + + public CompareJsonData(String payloadX, String payloadY) + { + this.payloadX = payloadX; + this.payloadY = payloadY; + } + + @Override + public boolean compare() throws Exception + { + + ObjectMapper dataMapper = new ObjectMapper(); + boolean match = false; + try + { + Map controlData = (Map)(dataMapper.readValue(payloadX, Map.class)); + Map testData = (Map)(dataMapper.readValue(payloadY, Map.class)); + + log.debug("Control Data :" + controlData); + log.debug("testData Data :" + testData); + + if(controlData.equals(testData)) + match=true; + } + catch(JsonParseException e) + { + throw new Exception(e.getMessage()); + } + catch(JsonMappingException e) + { + throw new Exception(e.getMessage()); + } + catch(IOException ioe) + { + throw new Exception(ioe.getMessage()); + } + + return match; + } + + + +} diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareNode.java b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareNode.java new file mode 100644 index 000000000..710b5ffd1 --- /dev/null +++ b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareNode.java @@ -0,0 +1,138 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.audit.node; + + +import java.util.HashMap; +import java.util.Map; + + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +public class CompareNode implements SvcLogicJavaPlugin +{ + + private static final EELFLogger log = EELFManager.getInstance().getLogger(CompareNode.class); + + public void compare( Map inParams, SvcLogicContext ctx) throws SvcLogicException + { + log.debug("Starting Compare Node Analysis"); + + HashMap status = new HashMap(); + Parameters params = new Parameters(inParams); + try + { + if(params.getCompareDataType() != null) + { + if(params.getPayloadX() !=null && params.getPayloadY() !=null) + { + status = getCompareResults(params); + log.debug("Compare Result : " + status); + } + else + { + status.put(CompareConstants.RESPONSE_STATUS, CompareConstants.STATUS_FAILURE); + status.put(CompareConstants.ERROR_CODE, "200"); + status.put(CompareConstants.ERROR_MESSAGE, "One of the Data Received by CompareNode is Empty"); + } + } + else + { + status.put(CompareConstants.RESPONSE_STATUS, CompareConstants.STATUS_FAILURE); + status.put(CompareConstants.ERROR_CODE, "200"); + status.put(CompareConstants.ERROR_MESSAGE, "Missing compareDataType value in input request: Expecting at least one of CLI/RESTCONF/XML"); + } + + } + catch(Exception e) + { + status.put(CompareConstants.RESPONSE_STATUS, CompareConstants.STATUS_FAILURE); + status.put(CompareConstants.ERROR_CODE, "200"); + status.put(CompareConstants.ERROR_MESSAGE, CompareConstants.ERROR_MESSAGE_DEATIL); + log.debug("Error in Comapre Node Execution " + e.getMessage()); + + } + + createContextReposne(status, ctx, params.getRequestIdentifier()); + } + + private HashMap getCompareResults(Parameters params) throws Exception + { + HashMap resultMap = new HashMap(); + boolean cmpResult = false; + CompareDataInterface handler; + + + + if(params.getCompareDataType().equalsIgnoreCase(CompareConstants.FORMAT_JSON)) + handler = new CompareJsonData(params.getPayloadX(), params.getPayloadY()); + else if((params.getCompareDataType().equalsIgnoreCase(CompareConstants.FORMAT_XML)) + || (params.getCompareDataType().equalsIgnoreCase(CompareConstants.NETCONF_XML)) + || (params.getCompareDataType().equalsIgnoreCase(CompareConstants.RESTCONF_XML))) + handler = new CompareXmlData(params.getPayloadX(), params.getPayloadY()); + else if (params.getCompareDataType().equalsIgnoreCase(CompareConstants.FORMAT_CLI)) + handler = new CompareCliData(params.getPayloadX(), params.getPayloadY()); + else + { + throw new Exception("Format " + params.getCompareDataType() + " not supported"); + } + try + { + log.debug("Received Format to compare : " + params.getCompareDataType()); + + cmpResult = handler.compare(); + if(cmpResult) + { + resultMap.put(CompareConstants.RESPONSE_STATUS, CompareConstants.STATUS_SUCCESS); + + } + else + { + resultMap.put(CompareConstants.RESPONSE_STATUS, CompareConstants.STATUS_FAILURE); + resultMap.put(CompareConstants.ERROR_CODE, "500"); + resultMap.put(CompareConstants.ERROR_MESSAGE, CompareConstants.NO_MATCH_MESSAGE); + } + } + catch (Exception e) + { + throw e; + } + + return resultMap; + } + + private void createContextReposne(HashMap status, SvcLogicContext ctx, String requestIdentifier ) + { + if(requestIdentifier == null) + requestIdentifier = ""; + else + requestIdentifier = requestIdentifier + "."; + + ctx.setAttribute(requestIdentifier.concat( CompareConstants.RESPONSE_STATUS), (String) status.get(CompareConstants.RESPONSE_STATUS)); + ctx.setAttribute(requestIdentifier.concat(CompareConstants.ERROR_CODE), (String) status.get(CompareConstants.ERROR_CODE)); + ctx.setAttribute(requestIdentifier.concat(CompareConstants.ERROR_MESSAGE), (String) status.get(CompareConstants.ERROR_MESSAGE)); + } + +} diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareXmlData.java b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareXmlData.java new file mode 100644 index 000000000..00837092f --- /dev/null +++ b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/CompareXmlData.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.audit.node; + + +import java.io.IOException; +import java.io.StringReader; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.XMLUnit; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +public class CompareXmlData implements CompareDataInterface +{ + private static final EELFLogger log = EELFManager.getInstance().getLogger(CompareXmlData.class); + + + String controlXml; + String testXml; + + Document doc; + + public CompareXmlData(String controlXml, String testXml) { + super(); + this.controlXml = controlXml; + this.testXml = testXml; + } + + @Override + public boolean compare() throws Exception + { + + log.debug("controlXml : " + controlXml); + log.debug("testXml : " + testXml); + + doSetup(); + + try + { + Diff diff = new Diff(getCompareDoc(controlXml), getCompareDoc(testXml)); + if(diff.similar()) + return true; + else + return false; + } + catch(SAXException se) + { + se.printStackTrace(); + throw new Exception(se.getMessage()); + } + catch(Exception e) + { + e.printStackTrace(); + throw new Exception(e.getMessage()); + } + } + + private void doSetup() throws ParserConfigurationException, SAXException, IOException + { + + XMLUnit.setIgnoreAttributeOrder(true); + XMLUnit.setIgnoreComments(true); + XMLUnit.setIgnoreWhitespace(true); + } + + public Document getCompareDoc(String inXml) throws ParserConfigurationException, SAXException, IOException + { + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); + StringReader reader = new StringReader(inXml); + InputSource inputSource = new InputSource(reader); + Document doc = dBuilder.parse(inputSource); + doc.getDocumentElement().normalize(); + + return doc; + } +} diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/Parameters.java b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/Parameters.java new file mode 100644 index 000000000..e3358df11 --- /dev/null +++ b/appc-config/appc-config-audit/provider/src/main/java/org/onap/sdnc/config/audit/node/Parameters.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.audit.node; + + +import java.util.Map; + +public class Parameters +{ + + String payloadX ; + + public String getPayloadX() { + return payloadX; + } + public void setPayloadX(String payloadX) { + this.payloadX = payloadX; + } + + String payloadXtype; + + public String getPayloadXtype() { + return payloadXtype; + } + public void setPayloadXtype(String payloadXtype) { + this.payloadXtype = payloadXtype; + } + + String payloadY ; + + public String getPayloadY() { + return payloadY; + } + public void setPayloadY(String payloadY) { + this.payloadY = payloadY; + } + + String payloadYtype; + + public String getPayloadYtype() { + return payloadYtype; + } + public void setPayloadYtype(String payloadYtype) { + this.payloadYtype = payloadYtype; + } + + String compareDataType; + + public String getCompareDataType() { + return compareDataType; + } + public void setCompareDataType(String compareDataType) { + this.compareDataType = compareDataType; + } + + String compareType; + + public String getCompareType() { + return compareType; + } + public void setCompareType(String compareType) { + this.compareType = compareType; + } + + String requestIdentifier; + + public String getRequestIdentifier() { + return requestIdentifier; + } + public void setRequestIdentifier(String requestIdentifier) { + this.requestIdentifier = requestIdentifier; + } + public Parameters(Map inParams) + { + this.compareType = inParams.get("compareType"); + this.compareDataType = inParams.get("compareDataType"); + this.payloadX= inParams.get("sourceData"); + this.payloadY= inParams.get("targetData"); + this.payloadXtype = inParams.get("sourceDataType"); + this.payloadYtype = inParams.get("targetDataType"); + this.requestIdentifier = inParams.get("requestIdentifier"); + + } +} diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/SliAuditActivator.java b/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/SliAuditActivator.java deleted file mode 100644 index 648d8ea86..000000000 --- a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/SliAuditActivator.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.audit; - -import java.util.LinkedList; -import java.util.List; - -import org.openecomp.sdnc.config.audit.node.CompareNode; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.ConfigurationException; - -public class SliAuditActivator implements BundleActivator{ - - private List registrations = new LinkedList(); - - - private static final EELFLogger log = EELFManager.getInstance().getLogger(SliAuditActivator.class); - - @Override - public void start(BundleContext ctx) throws Exception - { - - CompareNode compareNodePlugin = new CompareNode(); - log.info("Registering service "+ compareNodePlugin.getClass().getName()); - registrations.add(ctx.registerService(compareNodePlugin.getClass().getName(), compareNodePlugin, null)); - - } - @Override - public void stop(BundleContext arg0) throws Exception - { - for (ServiceRegistration registration: registrations) - { - registration.unregister(); - registration = null; - } - - } - -} diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/SliAuditConstant.java b/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/SliAuditConstant.java deleted file mode 100644 index 0bfaa1e36..000000000 --- a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/SliAuditConstant.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.audit; - -public class SliAuditConstant { - - public static String STRING_ENCODING = "utf-8"; - public static String Y = "Y"; - public static String N = "N"; - public static String DATA_TYPE_TEXT = "TEXT"; - public static String DATA_TYPE_JSON = "JSON"; - public static String DATA_TYPE_XML = "XML"; - public static String DATA_TYPE_SQL = "SQL"; - - public static String INPUT_PARAM_JSON_DATA = "jsonData"; - public static String INPUT_PARAM_IS_ESCAPED = "isEscaped"; - public static String INPUT_PARAM_BLOCK_KEYS = "blockKeys"; - public static String INPUT_PARAM_LOG_DATA = "logData"; - public static String INPUT_PARAM_CHECK_DATA = "checkData"; - public static String INPUT_PARAM_ESCAPE_DATA = "escapeData"; - public static String INPUT_PARAM_UNESCAPE_DATA = "unEscapeData"; - public static String INPUT_PARAM_DATA_TYPE = "dataType"; - public static String INPUT_PARAM_FILE_NAME = "fileName"; - - public static String INPUT_PARAM_TEMPLATE_DATA = "templateData"; - public static String INPUT_PARAM_TEMPLATE_FILE = "templateFile"; - public static String INPUT_PARAM_TEMPLATE_TYPE = "templateType"; - public static String INPUT_PARAM_DO_PRETTY_OUTPUT = "doPrettyOutput"; - public static String INPUT_PARAM_REQUEST_DATA = "requestData"; - public static String INPUT_PARAM_RESPONSE_PRIFIX = "responsePrefix"; - - - public static String OUTPUT_PARAM_MERGED_DATA = "mergedData"; - public static String OUTPUT_PARAM_TRANSFORMED_DATA = "transformedData"; - public static String OUTPUT_PARAM_FILE_DATA = "fileData"; - public static String OUTPUT_PARAM_PARSED_ERROR = "parsedError"; - public static String OUTPUT_PARAM_DATA_TYPE = "dataType"; - public static String OUTPUT_PARAM_STATUS = "status"; - public static String OUTPUT_PARAM_ERROR_MESSAGE = "error-message"; - public static String OUTPUT_PARAM_ESCAPE_DATA = "escapeData"; - public static String OUTPUT_PARAM_UNESCAPE_DATA = "unEscapeData"; - - public static String OUTPUT_STATUS_SUCCESS = "success"; - public static String OUTPUT_STATUS_FAILURE = "failure"; - -} diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareCliData.java b/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareCliData.java deleted file mode 100644 index 969d126bb..000000000 --- a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareCliData.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.audit.node; - -public class CompareCliData implements CompareDataInterface{ - - String payloadX; - String payloadY; - - public CompareCliData(String payloadX, String payloadY) - { - super(); - this.payloadX = payloadX; - this.payloadY = payloadY; - } - - @Override - public boolean compare() throws Exception - { - if(payloadX != null && payloadX.equals(payloadY)) - return true; - else - return false; - } -} diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareConstants.java b/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareConstants.java deleted file mode 100644 index 42b18d5c3..000000000 --- a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareConstants.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.audit.node; - -public class CompareConstants { - - - public static final String FORMAT_JSON = "RESTCONF"; - public static final String FORMAT_XML = "XML"; - public static final String FORMAT_CLI = "CLI"; - public static final String NETCONF_XML = "NETCONF-XML"; - public static final String RESTCONF_XML = "RESTCONF-XML"; - - - public static final String STATUS_FAILURE = "FAILURE"; - public static final String RESPONSE_STATUS = "STATUS"; - public static final String STATUS_SUCCESS = "SUCCESS"; - - public static final String ERROR_CODE = "Error-code"; - - public static final String ERROR_MESSAGE = "Error-Message"; - public static final String ERROR_MESSAGE_DEATIL = "Compare Node Failed-Internal Error.See karaf log file"; - - public static final String NO_MATCH_MESSAGE = "The configurations do not match"; -} diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareDataInterface.java b/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareDataInterface.java deleted file mode 100644 index 95f154e2e..000000000 --- a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareDataInterface.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.audit.node; - - -public interface CompareDataInterface -{ - boolean compare() throws Exception; -} diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareJsonData.java b/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareJsonData.java deleted file mode 100644 index 422ac30ac..000000000 --- a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareJsonData.java +++ /dev/null @@ -1,82 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.audit.node; - -import java.io.IOException; -import java.util.Map; - - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - - -public class CompareJsonData implements CompareDataInterface { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(CompareJsonData.class); - - String payloadX; - String payloadY; - - public CompareJsonData(String payloadX, String payloadY) - { - this.payloadX = payloadX; - this.payloadY = payloadY; - } - - @Override - public boolean compare() throws Exception - { - - ObjectMapper dataMapper = new ObjectMapper(); - boolean match = false; - try - { - Map controlData = (Map)(dataMapper.readValue(payloadX, Map.class)); - Map testData = (Map)(dataMapper.readValue(payloadY, Map.class)); - - log.debug("Control Data :" + controlData); - log.debug("testData Data :" + testData); - - if(controlData.equals(testData)) - match=true; - } - catch(JsonParseException e) - { - throw new Exception(e.getMessage()); - } - catch(JsonMappingException e) - { - throw new Exception(e.getMessage()); - } - catch(IOException ioe) - { - throw new Exception(ioe.getMessage()); - } - - return match; - } - - - -} diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareNode.java b/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareNode.java deleted file mode 100644 index 710b5ffd1..000000000 --- a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareNode.java +++ /dev/null @@ -1,138 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.audit.node; - - -import java.util.HashMap; -import java.util.Map; - - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -public class CompareNode implements SvcLogicJavaPlugin -{ - - private static final EELFLogger log = EELFManager.getInstance().getLogger(CompareNode.class); - - public void compare( Map inParams, SvcLogicContext ctx) throws SvcLogicException - { - log.debug("Starting Compare Node Analysis"); - - HashMap status = new HashMap(); - Parameters params = new Parameters(inParams); - try - { - if(params.getCompareDataType() != null) - { - if(params.getPayloadX() !=null && params.getPayloadY() !=null) - { - status = getCompareResults(params); - log.debug("Compare Result : " + status); - } - else - { - status.put(CompareConstants.RESPONSE_STATUS, CompareConstants.STATUS_FAILURE); - status.put(CompareConstants.ERROR_CODE, "200"); - status.put(CompareConstants.ERROR_MESSAGE, "One of the Data Received by CompareNode is Empty"); - } - } - else - { - status.put(CompareConstants.RESPONSE_STATUS, CompareConstants.STATUS_FAILURE); - status.put(CompareConstants.ERROR_CODE, "200"); - status.put(CompareConstants.ERROR_MESSAGE, "Missing compareDataType value in input request: Expecting at least one of CLI/RESTCONF/XML"); - } - - } - catch(Exception e) - { - status.put(CompareConstants.RESPONSE_STATUS, CompareConstants.STATUS_FAILURE); - status.put(CompareConstants.ERROR_CODE, "200"); - status.put(CompareConstants.ERROR_MESSAGE, CompareConstants.ERROR_MESSAGE_DEATIL); - log.debug("Error in Comapre Node Execution " + e.getMessage()); - - } - - createContextReposne(status, ctx, params.getRequestIdentifier()); - } - - private HashMap getCompareResults(Parameters params) throws Exception - { - HashMap resultMap = new HashMap(); - boolean cmpResult = false; - CompareDataInterface handler; - - - - if(params.getCompareDataType().equalsIgnoreCase(CompareConstants.FORMAT_JSON)) - handler = new CompareJsonData(params.getPayloadX(), params.getPayloadY()); - else if((params.getCompareDataType().equalsIgnoreCase(CompareConstants.FORMAT_XML)) - || (params.getCompareDataType().equalsIgnoreCase(CompareConstants.NETCONF_XML)) - || (params.getCompareDataType().equalsIgnoreCase(CompareConstants.RESTCONF_XML))) - handler = new CompareXmlData(params.getPayloadX(), params.getPayloadY()); - else if (params.getCompareDataType().equalsIgnoreCase(CompareConstants.FORMAT_CLI)) - handler = new CompareCliData(params.getPayloadX(), params.getPayloadY()); - else - { - throw new Exception("Format " + params.getCompareDataType() + " not supported"); - } - try - { - log.debug("Received Format to compare : " + params.getCompareDataType()); - - cmpResult = handler.compare(); - if(cmpResult) - { - resultMap.put(CompareConstants.RESPONSE_STATUS, CompareConstants.STATUS_SUCCESS); - - } - else - { - resultMap.put(CompareConstants.RESPONSE_STATUS, CompareConstants.STATUS_FAILURE); - resultMap.put(CompareConstants.ERROR_CODE, "500"); - resultMap.put(CompareConstants.ERROR_MESSAGE, CompareConstants.NO_MATCH_MESSAGE); - } - } - catch (Exception e) - { - throw e; - } - - return resultMap; - } - - private void createContextReposne(HashMap status, SvcLogicContext ctx, String requestIdentifier ) - { - if(requestIdentifier == null) - requestIdentifier = ""; - else - requestIdentifier = requestIdentifier + "."; - - ctx.setAttribute(requestIdentifier.concat( CompareConstants.RESPONSE_STATUS), (String) status.get(CompareConstants.RESPONSE_STATUS)); - ctx.setAttribute(requestIdentifier.concat(CompareConstants.ERROR_CODE), (String) status.get(CompareConstants.ERROR_CODE)); - ctx.setAttribute(requestIdentifier.concat(CompareConstants.ERROR_MESSAGE), (String) status.get(CompareConstants.ERROR_MESSAGE)); - } - -} diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareXmlData.java b/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareXmlData.java deleted file mode 100644 index 00837092f..000000000 --- a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/CompareXmlData.java +++ /dev/null @@ -1,105 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.audit.node; - - -import java.io.IOException; -import java.io.StringReader; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.custommonkey.xmlunit.Diff; -import org.custommonkey.xmlunit.XMLUnit; -import org.w3c.dom.Document; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -public class CompareXmlData implements CompareDataInterface -{ - private static final EELFLogger log = EELFManager.getInstance().getLogger(CompareXmlData.class); - - - String controlXml; - String testXml; - - Document doc; - - public CompareXmlData(String controlXml, String testXml) { - super(); - this.controlXml = controlXml; - this.testXml = testXml; - } - - @Override - public boolean compare() throws Exception - { - - log.debug("controlXml : " + controlXml); - log.debug("testXml : " + testXml); - - doSetup(); - - try - { - Diff diff = new Diff(getCompareDoc(controlXml), getCompareDoc(testXml)); - if(diff.similar()) - return true; - else - return false; - } - catch(SAXException se) - { - se.printStackTrace(); - throw new Exception(se.getMessage()); - } - catch(Exception e) - { - e.printStackTrace(); - throw new Exception(e.getMessage()); - } - } - - private void doSetup() throws ParserConfigurationException, SAXException, IOException - { - - XMLUnit.setIgnoreAttributeOrder(true); - XMLUnit.setIgnoreComments(true); - XMLUnit.setIgnoreWhitespace(true); - } - - public Document getCompareDoc(String inXml) throws ParserConfigurationException, SAXException, IOException - { - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); - StringReader reader = new StringReader(inXml); - InputSource inputSource = new InputSource(reader); - Document doc = dBuilder.parse(inputSource); - doc.getDocumentElement().normalize(); - - return doc; - } -} diff --git a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/Parameters.java b/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/Parameters.java deleted file mode 100644 index e3358df11..000000000 --- a/appc-config/appc-config-audit/provider/src/main/java/org/openecomp/sdnc/config/audit/node/Parameters.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.audit.node; - - -import java.util.Map; - -public class Parameters -{ - - String payloadX ; - - public String getPayloadX() { - return payloadX; - } - public void setPayloadX(String payloadX) { - this.payloadX = payloadX; - } - - String payloadXtype; - - public String getPayloadXtype() { - return payloadXtype; - } - public void setPayloadXtype(String payloadXtype) { - this.payloadXtype = payloadXtype; - } - - String payloadY ; - - public String getPayloadY() { - return payloadY; - } - public void setPayloadY(String payloadY) { - this.payloadY = payloadY; - } - - String payloadYtype; - - public String getPayloadYtype() { - return payloadYtype; - } - public void setPayloadYtype(String payloadYtype) { - this.payloadYtype = payloadYtype; - } - - String compareDataType; - - public String getCompareDataType() { - return compareDataType; - } - public void setCompareDataType(String compareDataType) { - this.compareDataType = compareDataType; - } - - String compareType; - - public String getCompareType() { - return compareType; - } - public void setCompareType(String compareType) { - this.compareType = compareType; - } - - String requestIdentifier; - - public String getRequestIdentifier() { - return requestIdentifier; - } - public void setRequestIdentifier(String requestIdentifier) { - this.requestIdentifier = requestIdentifier; - } - public Parameters(Map inParams) - { - this.compareType = inParams.get("compareType"); - this.compareDataType = inParams.get("compareDataType"); - this.payloadX= inParams.get("sourceData"); - this.payloadY= inParams.get("targetData"); - this.payloadXtype = inParams.get("sourceDataType"); - this.payloadYtype = inParams.get("targetDataType"); - this.requestIdentifier = inParams.get("requestIdentifier"); - - } -} diff --git a/appc-config/appc-config-audit/provider/src/test/java/org/onap/sdnc/config/audit/node/TestCompareNodeCli.java b/appc-config/appc-config-audit/provider/src/test/java/org/onap/sdnc/config/audit/node/TestCompareNodeCli.java new file mode 100644 index 000000000..a35b08632 --- /dev/null +++ b/appc-config/appc-config-audit/provider/src/test/java/org/onap/sdnc/config/audit/node/TestCompareNodeCli.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.audit.node; + +import java.util.HashMap; + +import org.junit.Test; +import org.openecomp.sdnc.config.audit.node.CompareNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +public class TestCompareNodeCli { + private static final Logger log = LoggerFactory.getLogger(TestCompareNodeCli.class); + + @Test + public void TestCompareCliForSamePayload() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + HashMap testMap = new HashMap(); + CompareNode cmp = new CompareNode(); + testMap.put("compareDataType", "Cli"); + testMap.put("sourceData", "This is a Text Configuration of Device"); + testMap.put("targetData", "This is a Text Configuration of Device"); + cmp.compare(testMap, ctx); + assert (ctx.getAttribute("STATUS").equals("SUCCESS")); + } + + @Test + public void TestCompareCliFordifferentPayload() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + HashMap testMap = new HashMap(); + CompareNode cmp = new CompareNode(); + testMap.put("compareDataType", "Cli"); + testMap.put("sourceData", "This is a Text Negative test Configuration of Device"); + testMap.put("targetData", "This is a Text Configuration of Device"); + cmp.compare(testMap, ctx); + assert (ctx.getAttribute("STATUS").equals("FAILURE")); + } + + @Test + public void TestCompareForMissingInput() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + HashMap testMap = new HashMap(); + CompareNode cmp = new CompareNode(); + testMap.put("sourceData", "This is a Text Negative test Configuration of Device"); + testMap.put("targetData.configuration-data", "This is a Text Configuration of Device"); + cmp.compare(testMap, ctx); + assert (ctx.getAttribute("STATUS").equals("FAILURE")); + } +} diff --git a/appc-config/appc-config-audit/provider/src/test/java/org/onap/sdnc/config/audit/node/TestCompareNodeJson.java b/appc-config/appc-config-audit/provider/src/test/java/org/onap/sdnc/config/audit/node/TestCompareNodeJson.java new file mode 100644 index 000000000..aa819dffc --- /dev/null +++ b/appc-config/appc-config-audit/provider/src/test/java/org/onap/sdnc/config/audit/node/TestCompareNodeJson.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.audit.node; + +import java.util.HashMap; + +import org.junit.Test; +import org.openecomp.sdnc.config.audit.node.CompareNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +public class TestCompareNodeJson { + private static final Logger log = LoggerFactory.getLogger(TestCompareNodeJson.class); + + @Test + public void TestCompareJsonForSamePayload() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + HashMap testMap = new HashMap(); + CompareNode cmp = new CompareNode(); + String controlJson = "{\n\"input\": {\n \"appc-request-header\": {\n \"svc-request-id\": \"000000000\", \n \"svc-action\": \"prepare\" \n }, \n\"request-information\": {\n \"request-id\": \"000000000\", \n\"request-action\": \"VsbgServiceActivateRequest\", \n\"request-sub-action\": \"PREPARE\", \n \"source\": \"Version2\" \n} \n} \n}"; + String testJson = "{\n\"input\": {\n \"appc-request-header\": {\n \"svc-request-id\": \"000000000\", \n \"svc-action\": \"prepare\" \n }, \n\"request-information\": {\n \"request-id\": \"000000000\", \n\"request-action\": \"VsbgServiceActivateRequest\", \n\"request-sub-action\": \"PREPARE\", \n \"source\": \"Version2\" \n} \n} \n}"; + testMap.put("compareDataType", "RestConf"); + testMap.put("sourceData", controlJson); + testMap.put("targetData", testJson); + cmp.compare(testMap, ctx); + assert (ctx.getAttribute("STATUS").equals("SUCCESS")); + } + + @Test + public void TestCompareJsonFordifferentPayload() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + HashMap testMap = new HashMap(); + CompareNode cmp = new CompareNode(); + String controlJson = "{\n\"input\": {\n \"appc-request-header\": {\n \"svc-request-id\": \"000000000\", \n \"svc-action\": \"prepare\" \n }, \n\"request-information\": {\n \"request-id\": \"000000000\", \n\"request-action\": \"VsbgServiceActivateRequest\", \n\"request-sub-action\": \"PREPARE\", \n \"source\": \"Version2\" \n} \n} \n}"; + String testJson = "{\n\"input\": {\n \"appc-request-header\": { \n \"svc-action\": \"prepare\" \n }, \n\"request-information\": {\n \"request-id\": \"0000000000\", \n\"request-action\": \"VsbgServiceActivateRequest\", \n\"request-sub-action\": \"PREPARE\", \n \"source\": \"Version2\" \n} \n} \n}"; + testMap.put("compareDataType", "RestConf"); + testMap.put("sourceData", controlJson); + testMap.put("targetData", testJson); + cmp.compare(testMap, ctx); + assert (ctx.getAttribute("STATUS").equals("FAILURE")); + } +} diff --git a/appc-config/appc-config-audit/provider/src/test/java/org/onap/sdnc/config/audit/node/TestCompareNodeXml.java b/appc-config/appc-config-audit/provider/src/test/java/org/onap/sdnc/config/audit/node/TestCompareNodeXml.java new file mode 100644 index 000000000..ed82da83a --- /dev/null +++ b/appc-config/appc-config-audit/provider/src/test/java/org/onap/sdnc/config/audit/node/TestCompareNodeXml.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.audit.node; + +import java.io.IOException; +import java.util.HashMap; +import org.junit.Test; +import org.openecomp.sdnc.config.audit.node.CompareNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +public class TestCompareNodeXml { + private static final Logger log = LoggerFactory.getLogger(TestCompareNodeXml.class); + + @Test + public void TestCompareExtactXML() throws SvcLogicException { + log.debug("TestCompareNode.TestCompareExtactXML()"); + SvcLogicContext ctx = new SvcLogicContext(); + HashMap testMap = new HashMap(); + CompareNode cmp = new CompareNode(); + String s = "Test"; + + String t = "Test"; + testMap.put("compareDataType", "RESTCONF-XML"); + testMap.put("requestIdentifier", "123"); + testMap.put("sourceData", s); + testMap.put("targetData", t); + cmp.compare(testMap, ctx); + assert (ctx.getAttribute("123." + "STATUS").equals("SUCCESS")); + } + + @Test + public void TestCompareforAttributeOrder() throws IOException, SvcLogicException { + log.debug("TestCompareNode.TestCompareforAttributeOrder()"); + SvcLogicContext ctx = new SvcLogicContext(); + HashMap testMap = new HashMap(); + CompareNode cmp = new CompareNode(); + testMap.put("compareDataType", "XML"); + testMap.put("sourceData", + "2true5060true5060"); + testMap.put("targetData", + "true5060true50602"); + cmp.compare(testMap, ctx); + assert (ctx.getAttribute("STATUS").equals("SUCCESS")); + } + + @Test + public void TestCompareForComments() throws SvcLogicException { + log.debug("TestCompareNode.TestCompareForComments()"); + SvcLogicContext ctx = new SvcLogicContext(); + HashMap testMap = new HashMap(); + CompareNode cmp = new CompareNode(); + testMap.put("compareDataType", "XML"); + testMap.put("sourceData", "2"); + testMap.put("targetData", "2"); + cmp.compare(testMap, ctx); + assert (ctx.getAttribute("STATUS").equals("SUCCESS")); + } + +} diff --git a/appc-config/appc-config-audit/provider/src/test/java/org/openecomp/sdnc/config/audit/node/TestCompareNodeCli.java b/appc-config/appc-config-audit/provider/src/test/java/org/openecomp/sdnc/config/audit/node/TestCompareNodeCli.java deleted file mode 100644 index a35b08632..000000000 --- a/appc-config/appc-config-audit/provider/src/test/java/org/openecomp/sdnc/config/audit/node/TestCompareNodeCli.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.audit.node; - -import java.util.HashMap; - -import org.junit.Test; -import org.openecomp.sdnc.config.audit.node.CompareNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; - -public class TestCompareNodeCli { - private static final Logger log = LoggerFactory.getLogger(TestCompareNodeCli.class); - - @Test - public void TestCompareCliForSamePayload() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - HashMap testMap = new HashMap(); - CompareNode cmp = new CompareNode(); - testMap.put("compareDataType", "Cli"); - testMap.put("sourceData", "This is a Text Configuration of Device"); - testMap.put("targetData", "This is a Text Configuration of Device"); - cmp.compare(testMap, ctx); - assert (ctx.getAttribute("STATUS").equals("SUCCESS")); - } - - @Test - public void TestCompareCliFordifferentPayload() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - HashMap testMap = new HashMap(); - CompareNode cmp = new CompareNode(); - testMap.put("compareDataType", "Cli"); - testMap.put("sourceData", "This is a Text Negative test Configuration of Device"); - testMap.put("targetData", "This is a Text Configuration of Device"); - cmp.compare(testMap, ctx); - assert (ctx.getAttribute("STATUS").equals("FAILURE")); - } - - @Test - public void TestCompareForMissingInput() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - HashMap testMap = new HashMap(); - CompareNode cmp = new CompareNode(); - testMap.put("sourceData", "This is a Text Negative test Configuration of Device"); - testMap.put("targetData.configuration-data", "This is a Text Configuration of Device"); - cmp.compare(testMap, ctx); - assert (ctx.getAttribute("STATUS").equals("FAILURE")); - } -} diff --git a/appc-config/appc-config-audit/provider/src/test/java/org/openecomp/sdnc/config/audit/node/TestCompareNodeJson.java b/appc-config/appc-config-audit/provider/src/test/java/org/openecomp/sdnc/config/audit/node/TestCompareNodeJson.java deleted file mode 100644 index aa819dffc..000000000 --- a/appc-config/appc-config-audit/provider/src/test/java/org/openecomp/sdnc/config/audit/node/TestCompareNodeJson.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.audit.node; - -import java.util.HashMap; - -import org.junit.Test; -import org.openecomp.sdnc.config.audit.node.CompareNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; - -public class TestCompareNodeJson { - private static final Logger log = LoggerFactory.getLogger(TestCompareNodeJson.class); - - @Test - public void TestCompareJsonForSamePayload() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - HashMap testMap = new HashMap(); - CompareNode cmp = new CompareNode(); - String controlJson = "{\n\"input\": {\n \"appc-request-header\": {\n \"svc-request-id\": \"000000000\", \n \"svc-action\": \"prepare\" \n }, \n\"request-information\": {\n \"request-id\": \"000000000\", \n\"request-action\": \"VsbgServiceActivateRequest\", \n\"request-sub-action\": \"PREPARE\", \n \"source\": \"Version2\" \n} \n} \n}"; - String testJson = "{\n\"input\": {\n \"appc-request-header\": {\n \"svc-request-id\": \"000000000\", \n \"svc-action\": \"prepare\" \n }, \n\"request-information\": {\n \"request-id\": \"000000000\", \n\"request-action\": \"VsbgServiceActivateRequest\", \n\"request-sub-action\": \"PREPARE\", \n \"source\": \"Version2\" \n} \n} \n}"; - testMap.put("compareDataType", "RestConf"); - testMap.put("sourceData", controlJson); - testMap.put("targetData", testJson); - cmp.compare(testMap, ctx); - assert (ctx.getAttribute("STATUS").equals("SUCCESS")); - } - - @Test - public void TestCompareJsonFordifferentPayload() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - HashMap testMap = new HashMap(); - CompareNode cmp = new CompareNode(); - String controlJson = "{\n\"input\": {\n \"appc-request-header\": {\n \"svc-request-id\": \"000000000\", \n \"svc-action\": \"prepare\" \n }, \n\"request-information\": {\n \"request-id\": \"000000000\", \n\"request-action\": \"VsbgServiceActivateRequest\", \n\"request-sub-action\": \"PREPARE\", \n \"source\": \"Version2\" \n} \n} \n}"; - String testJson = "{\n\"input\": {\n \"appc-request-header\": { \n \"svc-action\": \"prepare\" \n }, \n\"request-information\": {\n \"request-id\": \"0000000000\", \n\"request-action\": \"VsbgServiceActivateRequest\", \n\"request-sub-action\": \"PREPARE\", \n \"source\": \"Version2\" \n} \n} \n}"; - testMap.put("compareDataType", "RestConf"); - testMap.put("sourceData", controlJson); - testMap.put("targetData", testJson); - cmp.compare(testMap, ctx); - assert (ctx.getAttribute("STATUS").equals("FAILURE")); - } -} diff --git a/appc-config/appc-config-audit/provider/src/test/java/org/openecomp/sdnc/config/audit/node/TestCompareNodeXml.java b/appc-config/appc-config-audit/provider/src/test/java/org/openecomp/sdnc/config/audit/node/TestCompareNodeXml.java deleted file mode 100644 index ed82da83a..000000000 --- a/appc-config/appc-config-audit/provider/src/test/java/org/openecomp/sdnc/config/audit/node/TestCompareNodeXml.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.audit.node; - -import java.io.IOException; -import java.util.HashMap; -import org.junit.Test; -import org.openecomp.sdnc.config.audit.node.CompareNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; - -public class TestCompareNodeXml { - private static final Logger log = LoggerFactory.getLogger(TestCompareNodeXml.class); - - @Test - public void TestCompareExtactXML() throws SvcLogicException { - log.debug("TestCompareNode.TestCompareExtactXML()"); - SvcLogicContext ctx = new SvcLogicContext(); - HashMap testMap = new HashMap(); - CompareNode cmp = new CompareNode(); - String s = "Test"; - - String t = "Test"; - testMap.put("compareDataType", "RESTCONF-XML"); - testMap.put("requestIdentifier", "123"); - testMap.put("sourceData", s); - testMap.put("targetData", t); - cmp.compare(testMap, ctx); - assert (ctx.getAttribute("123." + "STATUS").equals("SUCCESS")); - } - - @Test - public void TestCompareforAttributeOrder() throws IOException, SvcLogicException { - log.debug("TestCompareNode.TestCompareforAttributeOrder()"); - SvcLogicContext ctx = new SvcLogicContext(); - HashMap testMap = new HashMap(); - CompareNode cmp = new CompareNode(); - testMap.put("compareDataType", "XML"); - testMap.put("sourceData", - "2true5060true5060"); - testMap.put("targetData", - "true5060true50602"); - cmp.compare(testMap, ctx); - assert (ctx.getAttribute("STATUS").equals("SUCCESS")); - } - - @Test - public void TestCompareForComments() throws SvcLogicException { - log.debug("TestCompareNode.TestCompareForComments()"); - SvcLogicContext ctx = new SvcLogicContext(); - HashMap testMap = new HashMap(); - CompareNode cmp = new CompareNode(); - testMap.put("compareDataType", "XML"); - testMap.put("sourceData", "2"); - testMap.put("targetData", "2"); - cmp.compare(testMap, ctx); - assert (ctx.getAttribute("STATUS").equals("SUCCESS")); - } - -} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/ConfigGeneratorActivator.java b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/ConfigGeneratorActivator.java new file mode 100644 index 000000000..f2987d2f4 --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/ConfigGeneratorActivator.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator; + +import java.util.LinkedList; +import java.util.List; + +import org.openecomp.sdnc.config.generator.convert.ConvertNode; +import org.openecomp.sdnc.config.generator.merge.MergeNode; +import org.openecomp.sdnc.config.generator.pattern.PatternNode; +import org.openecomp.sdnc.config.generator.reader.ReaderNode; +import org.openecomp.sdnc.config.generator.writer.FileWriterNode; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ConfigGeneratorActivator implements BundleActivator{ + + private List registrations = new LinkedList(); + + + private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigGeneratorActivator.class); + + @Override + public void start(BundleContext ctx) throws Exception + { + + ConvertNode convertNode = new ConvertNode(); + log.info("Registering service "+ convertNode.getClass().getName()); + registrations.add(ctx.registerService(convertNode.getClass().getName(), convertNode, null)); + log.info("Registering service sccessful for "+ convertNode.getClass().getName()); + + MergeNode mergeNode = new MergeNode(); + log.info("Registering service "+ mergeNode.getClass().getName()); + registrations.add(ctx.registerService(mergeNode.getClass().getName(), mergeNode, null)); + log.info("Registering service sccessful for "+ mergeNode.getClass().getName()); + + PatternNode patternNode = new PatternNode(); + log.info("Registering service "+ patternNode.getClass().getName()); + registrations.add(ctx.registerService(patternNode.getClass().getName(), patternNode, null)); + log.info("Registering service sccessful for "+ patternNode.getClass().getName()); + + ReaderNode readerNode = new ReaderNode(); + log.info("Registering service "+ readerNode.getClass().getName()); + registrations.add(ctx.registerService(readerNode.getClass().getName(), readerNode, null)); + log.info("Registering service sccessful for "+ readerNode.getClass().getName()); + + FileWriterNode writerNode = new FileWriterNode(); + log.info("Registering service "+ writerNode.getClass().getName()); + registrations.add(ctx.registerService(writerNode.getClass().getName(), writerNode, null)); + log.info("Registering service sccessful for "+ writerNode.getClass().getName()); + + } + @Override + public void stop(BundleContext arg0) throws Exception + { + for (ServiceRegistration registration: registrations) + { + registration.unregister(); + registration = null; + } + + } + +} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/ConfigGeneratorConstant.java b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/ConfigGeneratorConstant.java new file mode 100644 index 000000000..cdfc34229 --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/ConfigGeneratorConstant.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator; + +public class ConfigGeneratorConstant { + + + public static String STRING_ENCODING = "utf-8"; + public static String Y = "Y"; + public static String N = "N"; + public static String DATA_TYPE_TEXT = "TEXT"; + public static String DATA_TYPE_JSON = "JSON"; + public static String DATA_TYPE_XML = "XML"; + public static String DATA_TYPE_SQL = "SQL"; + + public static String INPUT_PARAM_JSON_DATA = "jsonData"; + public static String INPUT_PARAM_IS_ESCAPED = "isEscaped"; + public static String INPUT_PARAM_BLOCK_KEYS = "blockKeys"; + public static String INPUT_PARAM_LOG_DATA = "logData"; + public static String INPUT_PARAM_CHECK_DATA = "checkData"; + public static String INPUT_PARAM_ESCAPE_DATA = "escapeData"; + public static String INPUT_PARAM_UNESCAPE_DATA = "unEscapeData"; + public static String INPUT_PARAM_DATA_TYPE = "dataType"; + public static String INPUT_PARAM_FILE_NAME = "fileName"; + + public static String INPUT_PARAM_TEMPLATE_DATA = "templateData"; + public static String INPUT_PARAM_TEMPLATE_FILE = "templateFile"; + public static String INPUT_PARAM_TEMPLATE_TYPE = "templateType"; + public static String INPUT_PARAM_DO_PRETTY_OUTPUT = "doPrettyOutput"; + public static String INPUT_PARAM_REQUEST_DATA = "requestData"; + public static String INPUT_PARAM_RESPONSE_PRIFIX = "responsePrefix"; + + + public static String OUTPUT_PARAM_MERGED_DATA = "mergedData"; + public static String OUTPUT_PARAM_TRANSFORMED_DATA = "transformedData"; + public static String OUTPUT_PARAM_FILE_DATA = "fileData"; + public static String OUTPUT_PARAM_PARSED_ERROR = "parsedError"; + public static String OUTPUT_PARAM_DATA_TYPE = "dataType"; + public static String OUTPUT_PARAM_STATUS = "status"; + public static String OUTPUT_PARAM_ERROR_MESSAGE = "error-message"; + public static String OUTPUT_PARAM_ESCAPE_DATA = "escapeData"; + public static String OUTPUT_PARAM_UNESCAPE_DATA = "unEscapeData"; + + public static String OUTPUT_STATUS_SUCCESS = "success"; + public static String OUTPUT_STATUS_FAILURE = "failure"; + + public static final Object INPUT_PARAM_CONTEXT_KEY = "contextKey"; + public static final Object INPUT_PARAM_JSON_CONTENT = "jsonContent"; + +} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/convert/ConvertNode.java b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/convert/ConvertNode.java new file mode 100644 index 000000000..f6a9043b1 --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/convert/ConvertNode.java @@ -0,0 +1,189 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.convert; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; +import org.openecomp.sdnc.config.generator.tool.EscapeUtils; +import org.openecomp.sdnc.config.generator.tool.JSONTool; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +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.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +public class ConvertNode implements SvcLogicJavaPlugin { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(ConvertNode.class); + + public void convertJson2DGContext( Map inParams, SvcLogicContext ctx) throws SvcLogicException { + log.trace("Received convertJson2DGContext call with params : " + inParams); + String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); + try { + String jsonData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_JSON_DATA); + String isEscaped = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_IS_ESCAPED); + String blockKey = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_BLOCK_KEYS); + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + + if(StringUtils.isNotBlank(jsonData)){ + if(StringUtils.isNotBlank(isEscaped) && isEscaped.equalsIgnoreCase("Y")){ + jsonData = StringEscapeUtils.unescapeJavaScript(jsonData); + } + + List blockKeys = new ArrayList(); + if(blockKey != null){ + blockKeys = Arrays.asList(blockKey.split(",")); + } + + Map dgContext = JSONTool.convertToProperties(jsonData, blockKeys); + log.trace("DG Context Populated:"+dgContext); + + for (Map.Entry entry : dgContext.entrySet()) { + if(entry != null && entry.getKey() != null){ + ctx.setAttribute(entry.getKey(), entry.getValue()); + } + } + } + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + + } catch (Exception e) { + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); + log.error("Failed in JSON to DGContext Conversion" + e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + } + + + public void escapeData( Map inParams, SvcLogicContext ctx) throws SvcLogicException { + log.trace("Received escapeData call with params : " + inParams); + String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); + try { + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + String unEscapeData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_UNESCAPE_DATA); + String dataType = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_DATA_TYPE); + + if(StringUtils.isBlank(unEscapeData)){ + throw new Exception("Unescape ("+ConfigGeneratorConstant.INPUT_PARAM_UNESCAPE_DATA +") param is missing for escapeData conversion." + unEscapeData); + } + + if(StringUtils.isBlank(dataType)){ + throw new Exception(" Datatype ("+ConfigGeneratorConstant.INPUT_PARAM_DATA_TYPE+")param is missing for escapeData conversion."); + } + + String escapedData = null; + if(ConfigGeneratorConstant.DATA_TYPE_JSON.equalsIgnoreCase(dataType)){ + escapedData = StringEscapeUtils.escapeJavaScript(unEscapeData); + }else if(ConfigGeneratorConstant.DATA_TYPE_XML.equalsIgnoreCase(dataType)){ + escapedData = StringEscapeUtils.escapeXml(unEscapeData); + }else if(ConfigGeneratorConstant.DATA_TYPE_SQL.equalsIgnoreCase(dataType)){ + escapedData = EscapeUtils.escapeSql(unEscapeData); + }else{ + throw new Exception(" Datatype ("+ConfigGeneratorConstant.INPUT_PARAM_DATA_TYPE+") param value ("+dataType+")is not supported for escapeData conversion."); + } + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ESCAPE_DATA, escapedData); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + log.trace("Data escapeData Successfully :" + ctx.getAttributeKeySet()); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); + log.error("Failed in escapeData Conversion" + e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + } + + public void unEscapeData( Map inParams, SvcLogicContext ctx) throws SvcLogicException { + log.trace("Received unEscapeData call with params : " + inParams); + String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); + try { + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + String escapeData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_ESCAPE_DATA); + String dataType = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_DATA_TYPE); + + if(StringUtils.isBlank(escapeData)){ + throw new Exception("Escape ("+ConfigGeneratorConstant.INPUT_PARAM_ESCAPE_DATA +") param is missing for escapeData conversion."); + } + + if(StringUtils.isBlank(dataType)){ + throw new Exception(" Datatype ("+ConfigGeneratorConstant.INPUT_PARAM_DATA_TYPE+")param is missing for escapeData conversion."); + } + + String unEscapedData = null; + if(ConfigGeneratorConstant.DATA_TYPE_JSON.equalsIgnoreCase(dataType)){ + unEscapedData = StringEscapeUtils.unescapeJavaScript(escapeData); + }else if(ConfigGeneratorConstant.DATA_TYPE_XML.equalsIgnoreCase(dataType)){ + unEscapedData = StringEscapeUtils.unescapeXml(escapeData); + }else{ + throw new Exception(" Datatype ("+ConfigGeneratorConstant.INPUT_PARAM_DATA_TYPE+") param value ("+dataType+")is not supported for unEscapeData conversion."); + } + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_UNESCAPE_DATA, unEscapedData); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + log.trace("Converted unEscapeData Successfully :" + ctx.getAttributeKeySet()); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); + log.error("Failed in unEscapeData Conversion" + e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + } + + + public void convertContextToJson(Map inParams, SvcLogicContext ctx) throws SvcLogicException{ + log.trace("Received convertContextToJson call with params : " + inParams); + String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); + String contextKey = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_CONTEXT_KEY); + try { + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + + ObjectMapper mapper = new ObjectMapper(); + ObjectNode objectNode = mapper.createObjectNode(); + + Set keys = ctx.getAttributeKeySet(); + for (String key : keys) { + if(key.startsWith(contextKey +".")){ + String objkey= key.replaceFirst(contextKey + ".", ""); + objectNode.put(objkey, ctx.getAttribute(key)); + + } + } + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.INPUT_PARAM_JSON_CONTENT, objectNode.toString()); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + log.trace("convertContextToJson Successful" ); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); + log.error("Failed in convertContextToJson" + e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + } + +} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/merge/MergeNode.java b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/merge/MergeNode.java new file mode 100644 index 000000000..3369f7588 --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/merge/MergeNode.java @@ -0,0 +1,132 @@ + +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +i * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.merge; + +import java.nio.charset.Charset; +import java.util.Map; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; +import org.openecomp.sdnc.config.generator.tool.JSONTool; +import org.openecomp.sdnc.config.generator.tool.MergeTool; +import org.openecomp.sdnc.config.generator.tool.EscapeUtils; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +public class MergeNode implements SvcLogicJavaPlugin { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(MergeNode.class); + + public void mergeDataOnTemplate(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + } + + public void mergeJsonDataOnTemplate(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + log.info("Received mergeJsonDataOnTemplate call with params : " + inParams); + String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); + try{ + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + String jsonData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_JSON_DATA); + if(StringUtils.isBlank(jsonData)){ + throw new Exception("JSON Data is missing"); + } + + String templateData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_DATA); + String templateFile = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_FILE); + + if(StringUtils.isBlank(templateData) && StringUtils.isBlank(templateFile)){ + throw new Exception("Template data or Template file is missing"); + } + if(StringUtils.isBlank(templateData)){ + String path = MergeNode.class.getClassLoader().getResource(".").toString(); + templateData = IOUtils.toString(MergeNode.class.getClassLoader().getResourceAsStream(templateFile)); + } + + String templateType = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_TYPE); + + Map dataMap = JSONTool.convertToProperties(jsonData); + log.info("Data Maps created :" + dataMap); + if(dataMap != null){ + String mergedData = MergeTool.mergeMap2TemplateData(templateData, dataMap); + if(mergedData != null){ + // ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_MERGED_DATA,mergedData); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_MERGED_DATA,EscapeUtils.unescapeSql(mergedData)); + + } + } + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + log.info("Data Merge Successful :" + ctx); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); + log.error("Failed in merging data to template " + e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + } + + public void mergeComplexJsonDataOnTemplate(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + //log.info("Received mergeJsonComplexDataOnTemplate call with params : " + inParams); + String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); + try{ + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + String jsonData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_JSON_DATA); + if(StringUtils.isBlank(jsonData)){ + throw new Exception("JSON Data is missing"); + } + + String templateData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_DATA); + String templateFile = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_FILE); + + if(StringUtils.isBlank(templateData) && StringUtils.isBlank(templateFile)){ + throw new Exception("Template data or Template file is missing"); + } + if(StringUtils.isBlank(templateData)){ + //String path = MergeNode.class.getClassLoader().getResource(".").toString(); + templateData = IOUtils.toString(MergeNode.class.getClassLoader().getResourceAsStream(templateFile), Charset.defaultCharset()); + } + + String templateType = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_TYPE); + String doPrettyOutput = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_DO_PRETTY_OUTPUT); + + String mergedData = MergeTool.mergeJson2TemplateData(templateData, jsonData, templateType, doPrettyOutput); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_MERGED_DATA,mergedData); + + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + //log.info("Data Merge Successful :" + ctx); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); + log.error("Failed in merging data to template " + e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + } + + public void mergeYamlDataOnTemplate(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + } + +} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/pattern/PatternNode.java b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/pattern/PatternNode.java new file mode 100644 index 000000000..67a5d2cc7 --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/pattern/PatternNode.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.pattern; + +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; +import org.openecomp.sdnc.config.generator.tool.CheckDataTool; +import org.openecomp.sdnc.config.generator.tool.LogParserTool; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +public class PatternNode implements SvcLogicJavaPlugin { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(PatternNode.class); + + public void parseErrorLog(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + log.info("Received parseErroLog call with params : " + inParams); + String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); + try{ + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + String logData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_LOG_DATA); + if(StringUtils.isBlank(logData)){ + throw new Exception("Log Data is missing"); + } + LogParserTool logParserTool = new LogParserTool(); + String parsedError = logParserTool.parseErrorLog(logData); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_PARSED_ERROR, parsedError); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); + log.error("Failed in parsing error log " + e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + } + + public void checkDataType(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + log.info("Received checkDataType call with params : " + inParams); + String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); + try{ + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + String checkData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_CHECK_DATA); + if(StringUtils.isBlank(checkData)){ + throw new Exception("Check Data is missing"); + } + String dataType = CheckDataTool.checkData(checkData); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_DATA_TYPE, dataType); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); + log.error("Failed in checkDataType " + e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + } + +} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/reader/ReaderNode.java b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/reader/ReaderNode.java new file mode 100644 index 000000000..379b7c769 --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/reader/ReaderNode.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.reader; + +import java.io.File; +import java.util.Map; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; +import org.openecomp.sdnc.config.generator.merge.MergeNode; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +public class ReaderNode implements SvcLogicJavaPlugin { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(MergeNode.class); + + + public void getFileData(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + log.info("Received getFileData call with params : " + inParams); + String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); + try{ + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + String fileName = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_FILE_NAME); + + String fileData = FileUtils.readFileToString(new File(fileName), ConfigGeneratorConstant.STRING_ENCODING); + + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_FILE_DATA,fileData); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); + log.error("Failed in merging data to template " + e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + } + + +} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/CheckDataTool.java b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/CheckDataTool.java new file mode 100644 index 000000000..316e821df --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/CheckDataTool.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.tool; + +import java.io.StringReader; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; +import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +public class CheckDataTool { + + public static String checkData(String data){ + boolean isJSON = isJSON(data); + if(isJSON){ + return ConfigGeneratorConstant.DATA_TYPE_JSON; + } + + boolean isXML = isXML(data); + if(isXML){ + return ConfigGeneratorConstant.DATA_TYPE_XML; + } + + return ConfigGeneratorConstant.DATA_TYPE_TEXT; + } + + public static boolean isJSON(String data) { + try { + new JSONObject(data); + } catch (JSONException ex) { + try { + new JSONArray(data); + } catch (JSONException ex1) { + return false; + } + } + return true; + + // try { + // final ObjectMapper mapper = new ObjectMapper(); + // mapper.readTree(data); + // return true; + // } catch (IOException e) { + // return false; + // } + } + + public static boolean isXML(String data) { + try { + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); + Document doc = dBuilder.parse(new InputSource(new StringReader(data))); + return true; + } catch (Exception ex) { + return false; + } + + } + +} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/Constants.java b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/Constants.java new file mode 100644 index 000000000..d8af571e8 --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/Constants.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.tool; + +public class Constants +{ + + public static final String DBLIB_SERVICE = "org.openecomp.sdnc.sli.resource.dblib.DBResourceManager"; + public static final String DEVICE_AUTHENTICATION="DEVICE_AUTHENTICATION"; + public static final String SCHEMA_SDNCTL="SDNCTL"; + + public static final String APPC_CONFIG_DIR="/opt/app/bvc/properties"; + +} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/CustomJsonNodeFactory.java b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/CustomJsonNodeFactory.java new file mode 100644 index 000000000..5820cea7a --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/CustomJsonNodeFactory.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.tool; + +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.TextNode; + +public class CustomJsonNodeFactory extends JsonNodeFactory { + + public TextNode textNode(String text) { + return new CustomTextNode(text); + } + +} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/CustomTextNode.java b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/CustomTextNode.java new file mode 100644 index 000000000..93e252a6d --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/CustomTextNode.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.tool; + + +import com.fasterxml.jackson.core.io.CharTypes; +import com.fasterxml.jackson.databind.node.TextNode; + +public class CustomTextNode extends TextNode{ + + public CustomTextNode(String v) { + super(v); + } + + @Override + public String toString() + { + int len = textValue().length(); + len = len + 2 + (len >> 4); + StringBuilder sb = new StringBuilder(len); + appendQuoted(sb, textValue()); + return sb.toString(); + } + + protected static void appendQuoted(StringBuilder sb, String content) + { + // sb.append('"'); + CharTypes.appendQuoted(sb, content); + // sb.append('"'); + } + +} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/DbServiceUtil.java b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/DbServiceUtil.java new file mode 100644 index 000000000..c8340816e --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/DbServiceUtil.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.tool; + +import java.io.File; +import java.net.URL; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Properties; + +import javax.sql.rowset.CachedRowSet; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.onap.ccsdk.sli.core.dblib.DBResourceManager; +import org.onap.ccsdk.sli.core.dblib.DbLibService; + +public class DbServiceUtil +{ + private static final Logger log = LoggerFactory + .getLogger(DbServiceUtil.class); + + private static Properties props; + private static DBResourceManager jdbcDataSource = null; + + + public static boolean updateDB(String tableName, ArrayList inputArgs, String scema, String whereClause, String setCluase) throws SQLException + { + String updatePasswordString = "update " + tableName + " set " + setCluase + " where " + whereClause ; + boolean result = jdbcDataSource.writeData(updatePasswordString, inputArgs,Constants.SCHEMA_SDNCTL); + return result; + } + + + public static CachedRowSet getData(String tableName, ArrayList argList, String schema, String getselectData, String getDataClasue ) throws SQLException + { + String selectQuery = "select " + getselectData + "from " + tableName + " where " + getDataClasue ; + CachedRowSet data = jdbcDataSource.getData(selectQuery, argList, schema); + return data; + } + + + public static DBResourceManager initDbLibService() throws Exception + { + props = new Properties(); + File file = new File("/opt/app/bvc/properties/dblib.properties"); + URL propURL = file.toURI().toURL(); + props.load(propURL.openStream()); + jdbcDataSource = new DBResourceManager(props); + return jdbcDataSource; + + } + + + +} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/EscapeUtils.java b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/EscapeUtils.java new file mode 100644 index 000000000..36afe76ae --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/EscapeUtils.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.tool; + +import org.apache.commons.lang3.StringUtils; + +public class EscapeUtils { + + public EscapeUtils() { + // TODO Auto-generated constructor stub + } + + public static String escapeSql(String str) { + if (str == null) { + return null; + } + String searchList[] = new String[]{"'","\\"}; + String replacementList[] = new String[]{ "''","\\\\"}; + return StringUtils.replaceEach(str,searchList, replacementList); + } + + public static String unescapeSql(String str) { + if (str == null) { + return null; + } + + String searchList[] = new String[] {"''"}; + String replacementList[] = new String[] {"'"}; + return StringUtils.replaceEach(str, searchList, replacementList); + } + + + // For Generic Purpose + public static String escapeSQL(String s) { + if (s == null) { + return null; + } + + int length = s.length(); + int newLength = length; + for (int i = 0; i < length; i++) { + char c = s.charAt(i); + switch (c) { + case '\\': + case '\"': + case '\'': + case '\0': { + newLength += 1; + } + break; + } + } + if (length == newLength) { + // nothing to escape in the string + return s; + } + StringBuffer sb = new StringBuffer(newLength); + for (int i = 0; i < length; i++) { + char c = s.charAt(i); + switch (c) { + case '\\': { + sb.append("\\\\"); + } + break; + case '\"': { + sb.append("\\\""); + } + break; + case '\'': { + sb.append("\\\'"); + } + break; + case '\0': { + sb.append("\\0"); + } + break; + default: { + sb.append(c); + } + } + } + return sb.toString(); + } +} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/JSONTool.java b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/JSONTool.java new file mode 100644 index 000000000..63fd7006e --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/JSONTool.java @@ -0,0 +1,157 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.tool; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + + + +public class JSONTool { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(JSONTool.class); + + public static Map convertToProperties(String s) throws JSONException { + return convertToProperties(s, null); + } + + public static Map convertToProperties(String s,List blockKeys) throws JSONException { + JSONObject json = new JSONObject(s); + Map mm = new HashMap(); + + Map wm = new HashMap(); + Iterator ii = json.keys(); + while (ii.hasNext()) { + String key1 = ii.next(); + wm.put(key1, json.get(key1)); + + + } + + while (!wm.isEmpty()) + for (String key : new ArrayList<>(wm.keySet())) { + Object o = wm.get(key); + wm.remove(key); + + + if(blockKeys != null && blockKeys.contains(key) && o != null){ + //log.info("Adding JSON Block Keys : " + key + "=" + o.toString()); + mm.put("block_" +key,o.toString()); + } + + if (o instanceof Boolean || o instanceof Number || o instanceof String) { + mm.put(key, o.toString()); + //log.info("Added property: " + key + ": " + o.toString()); + } + + else if (o instanceof JSONObject) { + JSONObject jo = (JSONObject) o; + Iterator i = jo.keys(); + while (i.hasNext()) { + String key1 = i.next(); + wm.put(key + "." + key1, jo.get(key1)); + } + } + + else if (o instanceof JSONArray) { + JSONArray ja = (JSONArray) o; + mm.put("size_"+key, String.valueOf(ja.length())); + + //log.info("Added property: " + key + "_length" + ": " + String.valueOf(ja.length())); + + for (int i = 0; i < ja.length(); i++) + wm.put(key + '[' + i + ']', ja.get(i)); + } + } + + return mm; + } + + /* + public static Map convertToProperties1(String s,List blockKeys) throws Exception { + ObjectMapper objectMapper = new ObjectMapper(); + + JsonNode rootNode = objectMapper.readTree(s); + + Map mm = new HashMap(); + + Map wm = new HashMap(); + Iterator ii = rootNode.fieldNames(); + while (ii.hasNext()) { + String key1 = ii.next(); + wm.put(key1, rootNode.get(key1)); + + + } + + while (!wm.isEmpty()) + for (String key : new ArrayList<>(wm.keySet())) { + Object o = wm.get(key); + wm.remove(key); + + + if(blockKeys != null && blockKeys.contains(key) && o != null){ + //log.info("Adding JSON Block Keys : " + key + "=" + o.toString()); + mm.put("block_" +key,o.toString()); + } + + if (o instanceof Boolean || o instanceof Number || o instanceof String) { + mm.put(key, o.toString()); + //log.info("Added property: " + key + ": " + o.toString()); + } + + else if (o instanceof JSONObject) { + JSONObject jo = (JSONObject) o; + Iterator i = jo.keys(); + while (i.hasNext()) { + String key1 = i.next(); + wm.put(key + "." + key1, jo.get(key1)); + } + } + + else if (o instanceof JSONArray) { + JSONArray ja = (JSONArray) o; + mm.put("size_"+key, String.valueOf(ja.length())); + + //log.info("Added property: " + key + "_length" + ": " + String.valueOf(ja.length())); + + for (int i = 0; i < ja.length(); i++) + wm.put(key + '[' + i + ']', ja.get(i)); + } + } + + return mm; + } +*/ + +} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/LogParserTool.java b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/LogParserTool.java new file mode 100644 index 000000000..54823bc17 --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/LogParserTool.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.tool; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class LogParserTool { + private static final EELFLogger log = EELFManager.getInstance().getLogger(JSONTool.class); + + private String[] singleLines; + private List recentErrors = new ArrayList ();; + private Date todaysDate = new Date(); + private SimpleDateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + private final int minMilli = 60000; + private final int IN_TIME = 0; + private final int NOT_IN_TIME = 1; + private final int NO_DATE = 2; + + public String parseErrorLog(String data){ + singleLines = data.split("\\r?\\n"); + try { + getNearestDates(); + + } catch (Exception e) { + e.printStackTrace(); + } + if(recentErrors.size() == 0){ + recentErrors.clear(); + return "Did not find the string 'Starting orchestration of file backed up to /var/opt/MetaSwitch/orch/orch_conf.json' in the log file with timestamp within the last 5 minutes"; + }else if(recentErrors.size() == 1){ + recentErrors.clear(); + return "Did not find the string ‘Error parsing orchestration file’ in the log file with timestamp within the last 5 minutes"; + }else{ + String error = recentErrors.get(0); + recentErrors.clear(); + return "Error: "+ error.substring(error.indexOf("Error parsing orchestration file:")+34); + } + } + + public void getNearestDates() throws ParseException{ + int result; + for( int i = singleLines.length-1; i >= 0 ; i--){ + if(singleLines[i].contains("Starting orchestration of file backed up to") || singleLines[i].contains("Error parsing orchestration file:")){ + result = checkDateTime(singleLines[i]); + if( result == IN_TIME) + recentErrors.add(singleLines[i]); + else if(result == NOT_IN_TIME){ + return; + } + } + } + } + + private int checkDateTime(String line){ + Date newDate; + try { + newDate = dFormat.parse(line.substring(0, 19)); + if((todaysDate.getTime() - newDate.getTime()) <= 5*minMilli){ + return IN_TIME; + }else + return NOT_IN_TIME; + } catch (ParseException e) { + e.printStackTrace(); + return NO_DATE; + } + } + + +} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/MergeTool.java b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/MergeTool.java new file mode 100644 index 000000000..0958deebb --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/tool/MergeTool.java @@ -0,0 +1,109 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.tool; + +import java.io.IOException; +import java.io.StringWriter; +import java.util.Iterator; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.Velocity; +import org.apache.velocity.app.VelocityEngine; +import org.apache.velocity.runtime.RuntimeConstants; +import org.apache.velocity.runtime.resource.loader.StringResourceLoader; +import org.apache.velocity.runtime.resource.util.StringResourceRepository; +import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + + +public class MergeTool { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(MergeTool.class); + + public static String mergeMap2TemplateData(String template, Map< String, String> dataMap ){ + log.info("MergeMap2TemplateData Template :"+ template + " Maps :"+ dataMap); + StringWriter writer = new StringWriter(); + VelocityEngine ve = new VelocityEngine(); + ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "string"); + ve.addProperty("string.resource.loader.class", StringResourceLoader.class.getName()); + ve.addProperty("string.resource.loader.repository.static", "false"); + ve.init(); + + StringResourceRepository repo = (StringResourceRepository)ve.getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT); + repo.putStringResource("TemplateResource", template); + + Template t = ve.getTemplate("TemplateResource"); + VelocityContext context = new VelocityContext(); + Iterator> entries = dataMap.entrySet().iterator(); + while (entries.hasNext()) { + Map.Entry entry = entries.next(); + context.put(entry.getKey(), entry.getValue()); + } + t.merge(context, writer); + return writer.toString(); + } + + + public static String mergeJson2TemplateData(String template, String jsonData, String templateType, String doPrettyOutput) throws JsonParseException, JsonMappingException, IOException{ + String mergedData = template; + if( StringUtils.isNotBlank(template) && StringUtils.isNotBlank(jsonData)){ + Velocity.init(); + + ObjectMapper mapper = new ObjectMapper(); + CustomJsonNodeFactory f = new CustomJsonNodeFactory(); + mapper.setNodeFactory(f); + + JsonNode jsonObj = mapper.readValue(jsonData, JsonNode.class); + + VelocityContext context = new VelocityContext(); + Iterator ii = jsonObj.fieldNames(); + while (ii.hasNext()) { + String key = ii.next(); + context.put(key, jsonObj.get(key)); + } + + StringWriter writer = new StringWriter(); + Velocity.evaluate(context, writer, "TemplateData", template); + writer.flush(); + mergedData = writer.toString(); + + if(StringUtils.isNotBlank(templateType) && StringUtils.isNotBlank(doPrettyOutput) + && ConfigGeneratorConstant.Y.equalsIgnoreCase(doPrettyOutput) + && ( ConfigGeneratorConstant.DATA_TYPE_JSON.equalsIgnoreCase(templateType) + || ConfigGeneratorConstant.DATA_TYPE_XML.equalsIgnoreCase(templateType)) ){ + // Perform Prettying + + } + } + return mergedData; + + } + +} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/transform/XSLTTransformerNode.java b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/transform/XSLTTransformerNode.java new file mode 100644 index 000000000..682b3f2c1 --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/transform/XSLTTransformerNode.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.transform; + +import java.io.File; +import java.io.StringReader; +import java.io.StringWriter; +import java.nio.charset.Charset; +import java.util.Map; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; + + +public class XSLTTransformerNode implements SvcLogicJavaPlugin { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(XSLTTransformerNode.class); + + public void transformData(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + log.trace("Received convertJson2DGContext call with params : " + inParams); + String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); + try { + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix + ".") : ""; + + String templateData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_DATA); + + if (StringUtils.isNotBlank(templateData)) { + String templateFile = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_FILE); + if (StringUtils.isNotBlank(templateFile)) { + templateData = FileUtils.readFileToString(new File(templateFile), Charset.defaultCharset()); + } + } + if (StringUtils.isBlank(templateData)) { + throw new Exception("In-param templateFile/templateData value is missing"); + } + + String requestData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_REQUEST_DATA); + if (StringUtils.isBlank(requestData)) { + throw new Exception("In-param requestData value is missing"); + } + + String transformedData = transform(requestData, templateData); + log.trace("Transformed Data : "+ transformedData); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_TRANSFORMED_DATA, transformedData); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + } catch (Exception e) { + e.printStackTrace(); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, + ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in XSLTTransformerNode : " + e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + } + + public String transform(String requestData, String templateData) + throws TransformerConfigurationException, TransformerException { + StringWriter xmlResultResource = new StringWriter(); + Transformer xmlTransformer = TransformerFactory.newInstance().newTransformer(new StreamSource(new StringReader(templateData))); + xmlTransformer.transform(new StreamSource(new StringReader(requestData)), new StreamResult(xmlResultResource)); + return xmlResultResource.getBuffer().toString(); + } + +} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/writer/FileWriterNode.java b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/writer/FileWriterNode.java new file mode 100644 index 000000000..e383476c2 --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/main/java/org/onap/sdnc/config/generator/writer/FileWriterNode.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.writer; + +import java.io.File; +import java.util.Map; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; + + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +public class FileWriterNode implements SvcLogicJavaPlugin { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(FileWriterNode.class); + + + + public void writeFile(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + log.info("Received writeFile call with params : " + inParams); + String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); + try{ + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + String fileName = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_FILE_NAME); + String fileContents = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_REQUEST_DATA); + + + File file = new File(fileName); + File filePath = file.getParentFile(); + FileUtils.forceMkdir(filePath); + + FileUtils.writeStringToFile(file, fileContents, ConfigGeneratorConstant.STRING_ENCODING); + + + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); + log.error("Failed in writeFile " + e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + } + + + +} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/ConfigGeneratorActivator.java b/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/ConfigGeneratorActivator.java deleted file mode 100644 index f2987d2f4..000000000 --- a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/ConfigGeneratorActivator.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator; - -import java.util.LinkedList; -import java.util.List; - -import org.openecomp.sdnc.config.generator.convert.ConvertNode; -import org.openecomp.sdnc.config.generator.merge.MergeNode; -import org.openecomp.sdnc.config.generator.pattern.PatternNode; -import org.openecomp.sdnc.config.generator.reader.ReaderNode; -import org.openecomp.sdnc.config.generator.writer.FileWriterNode; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class ConfigGeneratorActivator implements BundleActivator{ - - private List registrations = new LinkedList(); - - - private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigGeneratorActivator.class); - - @Override - public void start(BundleContext ctx) throws Exception - { - - ConvertNode convertNode = new ConvertNode(); - log.info("Registering service "+ convertNode.getClass().getName()); - registrations.add(ctx.registerService(convertNode.getClass().getName(), convertNode, null)); - log.info("Registering service sccessful for "+ convertNode.getClass().getName()); - - MergeNode mergeNode = new MergeNode(); - log.info("Registering service "+ mergeNode.getClass().getName()); - registrations.add(ctx.registerService(mergeNode.getClass().getName(), mergeNode, null)); - log.info("Registering service sccessful for "+ mergeNode.getClass().getName()); - - PatternNode patternNode = new PatternNode(); - log.info("Registering service "+ patternNode.getClass().getName()); - registrations.add(ctx.registerService(patternNode.getClass().getName(), patternNode, null)); - log.info("Registering service sccessful for "+ patternNode.getClass().getName()); - - ReaderNode readerNode = new ReaderNode(); - log.info("Registering service "+ readerNode.getClass().getName()); - registrations.add(ctx.registerService(readerNode.getClass().getName(), readerNode, null)); - log.info("Registering service sccessful for "+ readerNode.getClass().getName()); - - FileWriterNode writerNode = new FileWriterNode(); - log.info("Registering service "+ writerNode.getClass().getName()); - registrations.add(ctx.registerService(writerNode.getClass().getName(), writerNode, null)); - log.info("Registering service sccessful for "+ writerNode.getClass().getName()); - - } - @Override - public void stop(BundleContext arg0) throws Exception - { - for (ServiceRegistration registration: registrations) - { - registration.unregister(); - registration = null; - } - - } - -} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/ConfigGeneratorConstant.java b/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/ConfigGeneratorConstant.java deleted file mode 100644 index cdfc34229..000000000 --- a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/ConfigGeneratorConstant.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator; - -public class ConfigGeneratorConstant { - - - public static String STRING_ENCODING = "utf-8"; - public static String Y = "Y"; - public static String N = "N"; - public static String DATA_TYPE_TEXT = "TEXT"; - public static String DATA_TYPE_JSON = "JSON"; - public static String DATA_TYPE_XML = "XML"; - public static String DATA_TYPE_SQL = "SQL"; - - public static String INPUT_PARAM_JSON_DATA = "jsonData"; - public static String INPUT_PARAM_IS_ESCAPED = "isEscaped"; - public static String INPUT_PARAM_BLOCK_KEYS = "blockKeys"; - public static String INPUT_PARAM_LOG_DATA = "logData"; - public static String INPUT_PARAM_CHECK_DATA = "checkData"; - public static String INPUT_PARAM_ESCAPE_DATA = "escapeData"; - public static String INPUT_PARAM_UNESCAPE_DATA = "unEscapeData"; - public static String INPUT_PARAM_DATA_TYPE = "dataType"; - public static String INPUT_PARAM_FILE_NAME = "fileName"; - - public static String INPUT_PARAM_TEMPLATE_DATA = "templateData"; - public static String INPUT_PARAM_TEMPLATE_FILE = "templateFile"; - public static String INPUT_PARAM_TEMPLATE_TYPE = "templateType"; - public static String INPUT_PARAM_DO_PRETTY_OUTPUT = "doPrettyOutput"; - public static String INPUT_PARAM_REQUEST_DATA = "requestData"; - public static String INPUT_PARAM_RESPONSE_PRIFIX = "responsePrefix"; - - - public static String OUTPUT_PARAM_MERGED_DATA = "mergedData"; - public static String OUTPUT_PARAM_TRANSFORMED_DATA = "transformedData"; - public static String OUTPUT_PARAM_FILE_DATA = "fileData"; - public static String OUTPUT_PARAM_PARSED_ERROR = "parsedError"; - public static String OUTPUT_PARAM_DATA_TYPE = "dataType"; - public static String OUTPUT_PARAM_STATUS = "status"; - public static String OUTPUT_PARAM_ERROR_MESSAGE = "error-message"; - public static String OUTPUT_PARAM_ESCAPE_DATA = "escapeData"; - public static String OUTPUT_PARAM_UNESCAPE_DATA = "unEscapeData"; - - public static String OUTPUT_STATUS_SUCCESS = "success"; - public static String OUTPUT_STATUS_FAILURE = "failure"; - - public static final Object INPUT_PARAM_CONTEXT_KEY = "contextKey"; - public static final Object INPUT_PARAM_JSON_CONTENT = "jsonContent"; - -} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/convert/ConvertNode.java b/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/convert/ConvertNode.java deleted file mode 100644 index f6a9043b1..000000000 --- a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/convert/ConvertNode.java +++ /dev/null @@ -1,189 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.convert; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; -import org.openecomp.sdnc.config.generator.tool.EscapeUtils; -import org.openecomp.sdnc.config.generator.tool.JSONTool; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -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.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; - -public class ConvertNode implements SvcLogicJavaPlugin { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(ConvertNode.class); - - public void convertJson2DGContext( Map inParams, SvcLogicContext ctx) throws SvcLogicException { - log.trace("Received convertJson2DGContext call with params : " + inParams); - String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); - try { - String jsonData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_JSON_DATA); - String isEscaped = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_IS_ESCAPED); - String blockKey = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_BLOCK_KEYS); - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - - if(StringUtils.isNotBlank(jsonData)){ - if(StringUtils.isNotBlank(isEscaped) && isEscaped.equalsIgnoreCase("Y")){ - jsonData = StringEscapeUtils.unescapeJavaScript(jsonData); - } - - List blockKeys = new ArrayList(); - if(blockKey != null){ - blockKeys = Arrays.asList(blockKey.split(",")); - } - - Map dgContext = JSONTool.convertToProperties(jsonData, blockKeys); - log.trace("DG Context Populated:"+dgContext); - - for (Map.Entry entry : dgContext.entrySet()) { - if(entry != null && entry.getKey() != null){ - ctx.setAttribute(entry.getKey(), entry.getValue()); - } - } - } - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - - } catch (Exception e) { - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); - log.error("Failed in JSON to DGContext Conversion" + e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - } - - - public void escapeData( Map inParams, SvcLogicContext ctx) throws SvcLogicException { - log.trace("Received escapeData call with params : " + inParams); - String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); - try { - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - String unEscapeData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_UNESCAPE_DATA); - String dataType = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_DATA_TYPE); - - if(StringUtils.isBlank(unEscapeData)){ - throw new Exception("Unescape ("+ConfigGeneratorConstant.INPUT_PARAM_UNESCAPE_DATA +") param is missing for escapeData conversion." + unEscapeData); - } - - if(StringUtils.isBlank(dataType)){ - throw new Exception(" Datatype ("+ConfigGeneratorConstant.INPUT_PARAM_DATA_TYPE+")param is missing for escapeData conversion."); - } - - String escapedData = null; - if(ConfigGeneratorConstant.DATA_TYPE_JSON.equalsIgnoreCase(dataType)){ - escapedData = StringEscapeUtils.escapeJavaScript(unEscapeData); - }else if(ConfigGeneratorConstant.DATA_TYPE_XML.equalsIgnoreCase(dataType)){ - escapedData = StringEscapeUtils.escapeXml(unEscapeData); - }else if(ConfigGeneratorConstant.DATA_TYPE_SQL.equalsIgnoreCase(dataType)){ - escapedData = EscapeUtils.escapeSql(unEscapeData); - }else{ - throw new Exception(" Datatype ("+ConfigGeneratorConstant.INPUT_PARAM_DATA_TYPE+") param value ("+dataType+")is not supported for escapeData conversion."); - } - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ESCAPE_DATA, escapedData); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - log.trace("Data escapeData Successfully :" + ctx.getAttributeKeySet()); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); - log.error("Failed in escapeData Conversion" + e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - } - - public void unEscapeData( Map inParams, SvcLogicContext ctx) throws SvcLogicException { - log.trace("Received unEscapeData call with params : " + inParams); - String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); - try { - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - String escapeData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_ESCAPE_DATA); - String dataType = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_DATA_TYPE); - - if(StringUtils.isBlank(escapeData)){ - throw new Exception("Escape ("+ConfigGeneratorConstant.INPUT_PARAM_ESCAPE_DATA +") param is missing for escapeData conversion."); - } - - if(StringUtils.isBlank(dataType)){ - throw new Exception(" Datatype ("+ConfigGeneratorConstant.INPUT_PARAM_DATA_TYPE+")param is missing for escapeData conversion."); - } - - String unEscapedData = null; - if(ConfigGeneratorConstant.DATA_TYPE_JSON.equalsIgnoreCase(dataType)){ - unEscapedData = StringEscapeUtils.unescapeJavaScript(escapeData); - }else if(ConfigGeneratorConstant.DATA_TYPE_XML.equalsIgnoreCase(dataType)){ - unEscapedData = StringEscapeUtils.unescapeXml(escapeData); - }else{ - throw new Exception(" Datatype ("+ConfigGeneratorConstant.INPUT_PARAM_DATA_TYPE+") param value ("+dataType+")is not supported for unEscapeData conversion."); - } - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_UNESCAPE_DATA, unEscapedData); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - log.trace("Converted unEscapeData Successfully :" + ctx.getAttributeKeySet()); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); - log.error("Failed in unEscapeData Conversion" + e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - } - - - public void convertContextToJson(Map inParams, SvcLogicContext ctx) throws SvcLogicException{ - log.trace("Received convertContextToJson call with params : " + inParams); - String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); - String contextKey = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_CONTEXT_KEY); - try { - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - - ObjectMapper mapper = new ObjectMapper(); - ObjectNode objectNode = mapper.createObjectNode(); - - Set keys = ctx.getAttributeKeySet(); - for (String key : keys) { - if(key.startsWith(contextKey +".")){ - String objkey= key.replaceFirst(contextKey + ".", ""); - objectNode.put(objkey, ctx.getAttribute(key)); - - } - } - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.INPUT_PARAM_JSON_CONTENT, objectNode.toString()); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - log.trace("convertContextToJson Successful" ); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); - log.error("Failed in convertContextToJson" + e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - } - -} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/merge/MergeNode.java b/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/merge/MergeNode.java deleted file mode 100644 index 3369f7588..000000000 --- a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/merge/MergeNode.java +++ /dev/null @@ -1,132 +0,0 @@ - -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); -i * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.merge; - -import java.nio.charset.Charset; -import java.util.Map; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; -import org.openecomp.sdnc.config.generator.tool.JSONTool; -import org.openecomp.sdnc.config.generator.tool.MergeTool; -import org.openecomp.sdnc.config.generator.tool.EscapeUtils; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -public class MergeNode implements SvcLogicJavaPlugin { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(MergeNode.class); - - public void mergeDataOnTemplate(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - } - - public void mergeJsonDataOnTemplate(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - log.info("Received mergeJsonDataOnTemplate call with params : " + inParams); - String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); - try{ - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - String jsonData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_JSON_DATA); - if(StringUtils.isBlank(jsonData)){ - throw new Exception("JSON Data is missing"); - } - - String templateData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_DATA); - String templateFile = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_FILE); - - if(StringUtils.isBlank(templateData) && StringUtils.isBlank(templateFile)){ - throw new Exception("Template data or Template file is missing"); - } - if(StringUtils.isBlank(templateData)){ - String path = MergeNode.class.getClassLoader().getResource(".").toString(); - templateData = IOUtils.toString(MergeNode.class.getClassLoader().getResourceAsStream(templateFile)); - } - - String templateType = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_TYPE); - - Map dataMap = JSONTool.convertToProperties(jsonData); - log.info("Data Maps created :" + dataMap); - if(dataMap != null){ - String mergedData = MergeTool.mergeMap2TemplateData(templateData, dataMap); - if(mergedData != null){ - // ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_MERGED_DATA,mergedData); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_MERGED_DATA,EscapeUtils.unescapeSql(mergedData)); - - } - } - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - log.info("Data Merge Successful :" + ctx); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); - log.error("Failed in merging data to template " + e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - } - - public void mergeComplexJsonDataOnTemplate(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - //log.info("Received mergeJsonComplexDataOnTemplate call with params : " + inParams); - String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); - try{ - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - String jsonData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_JSON_DATA); - if(StringUtils.isBlank(jsonData)){ - throw new Exception("JSON Data is missing"); - } - - String templateData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_DATA); - String templateFile = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_FILE); - - if(StringUtils.isBlank(templateData) && StringUtils.isBlank(templateFile)){ - throw new Exception("Template data or Template file is missing"); - } - if(StringUtils.isBlank(templateData)){ - //String path = MergeNode.class.getClassLoader().getResource(".").toString(); - templateData = IOUtils.toString(MergeNode.class.getClassLoader().getResourceAsStream(templateFile), Charset.defaultCharset()); - } - - String templateType = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_TYPE); - String doPrettyOutput = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_DO_PRETTY_OUTPUT); - - String mergedData = MergeTool.mergeJson2TemplateData(templateData, jsonData, templateType, doPrettyOutput); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_MERGED_DATA,mergedData); - - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - //log.info("Data Merge Successful :" + ctx); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); - log.error("Failed in merging data to template " + e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - } - - public void mergeYamlDataOnTemplate(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - } - -} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/pattern/PatternNode.java b/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/pattern/PatternNode.java deleted file mode 100644 index 67a5d2cc7..000000000 --- a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/pattern/PatternNode.java +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.pattern; - -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; -import org.openecomp.sdnc.config.generator.tool.CheckDataTool; -import org.openecomp.sdnc.config.generator.tool.LogParserTool; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -public class PatternNode implements SvcLogicJavaPlugin { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(PatternNode.class); - - public void parseErrorLog(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - log.info("Received parseErroLog call with params : " + inParams); - String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); - try{ - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - String logData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_LOG_DATA); - if(StringUtils.isBlank(logData)){ - throw new Exception("Log Data is missing"); - } - LogParserTool logParserTool = new LogParserTool(); - String parsedError = logParserTool.parseErrorLog(logData); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_PARSED_ERROR, parsedError); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); - log.error("Failed in parsing error log " + e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - } - - public void checkDataType(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - log.info("Received checkDataType call with params : " + inParams); - String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); - try{ - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - String checkData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_CHECK_DATA); - if(StringUtils.isBlank(checkData)){ - throw new Exception("Check Data is missing"); - } - String dataType = CheckDataTool.checkData(checkData); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_DATA_TYPE, dataType); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); - log.error("Failed in checkDataType " + e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - } - -} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/reader/ReaderNode.java b/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/reader/ReaderNode.java deleted file mode 100644 index 379b7c769..000000000 --- a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/reader/ReaderNode.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.reader; - -import java.io.File; -import java.util.Map; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; -import org.openecomp.sdnc.config.generator.merge.MergeNode; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -public class ReaderNode implements SvcLogicJavaPlugin { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(MergeNode.class); - - - public void getFileData(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - log.info("Received getFileData call with params : " + inParams); - String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); - try{ - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - String fileName = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_FILE_NAME); - - String fileData = FileUtils.readFileToString(new File(fileName), ConfigGeneratorConstant.STRING_ENCODING); - - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_FILE_DATA,fileData); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); - log.error("Failed in merging data to template " + e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - } - - -} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/CheckDataTool.java b/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/CheckDataTool.java deleted file mode 100644 index 316e821df..000000000 --- a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/CheckDataTool.java +++ /dev/null @@ -1,84 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.tool; - -import java.io.StringReader; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.codehaus.jettison.json.JSONArray; -import org.codehaus.jettison.json.JSONException; -import org.codehaus.jettison.json.JSONObject; -import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; -import org.w3c.dom.Document; -import org.xml.sax.InputSource; - -public class CheckDataTool { - - public static String checkData(String data){ - boolean isJSON = isJSON(data); - if(isJSON){ - return ConfigGeneratorConstant.DATA_TYPE_JSON; - } - - boolean isXML = isXML(data); - if(isXML){ - return ConfigGeneratorConstant.DATA_TYPE_XML; - } - - return ConfigGeneratorConstant.DATA_TYPE_TEXT; - } - - public static boolean isJSON(String data) { - try { - new JSONObject(data); - } catch (JSONException ex) { - try { - new JSONArray(data); - } catch (JSONException ex1) { - return false; - } - } - return true; - - // try { - // final ObjectMapper mapper = new ObjectMapper(); - // mapper.readTree(data); - // return true; - // } catch (IOException e) { - // return false; - // } - } - - public static boolean isXML(String data) { - try { - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); - Document doc = dBuilder.parse(new InputSource(new StringReader(data))); - return true; - } catch (Exception ex) { - return false; - } - - } - -} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/Constants.java b/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/Constants.java deleted file mode 100644 index d8af571e8..000000000 --- a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/Constants.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.tool; - -public class Constants -{ - - public static final String DBLIB_SERVICE = "org.openecomp.sdnc.sli.resource.dblib.DBResourceManager"; - public static final String DEVICE_AUTHENTICATION="DEVICE_AUTHENTICATION"; - public static final String SCHEMA_SDNCTL="SDNCTL"; - - public static final String APPC_CONFIG_DIR="/opt/app/bvc/properties"; - -} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/CustomJsonNodeFactory.java b/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/CustomJsonNodeFactory.java deleted file mode 100644 index 5820cea7a..000000000 --- a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/CustomJsonNodeFactory.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.tool; - -import com.fasterxml.jackson.databind.node.JsonNodeFactory; -import com.fasterxml.jackson.databind.node.TextNode; - -public class CustomJsonNodeFactory extends JsonNodeFactory { - - public TextNode textNode(String text) { - return new CustomTextNode(text); - } - -} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/CustomTextNode.java b/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/CustomTextNode.java deleted file mode 100644 index 93e252a6d..000000000 --- a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/CustomTextNode.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.tool; - - -import com.fasterxml.jackson.core.io.CharTypes; -import com.fasterxml.jackson.databind.node.TextNode; - -public class CustomTextNode extends TextNode{ - - public CustomTextNode(String v) { - super(v); - } - - @Override - public String toString() - { - int len = textValue().length(); - len = len + 2 + (len >> 4); - StringBuilder sb = new StringBuilder(len); - appendQuoted(sb, textValue()); - return sb.toString(); - } - - protected static void appendQuoted(StringBuilder sb, String content) - { - // sb.append('"'); - CharTypes.appendQuoted(sb, content); - // sb.append('"'); - } - -} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/DbServiceUtil.java b/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/DbServiceUtil.java deleted file mode 100644 index c8340816e..000000000 --- a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/DbServiceUtil.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.tool; - -import java.io.File; -import java.net.URL; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Properties; - -import javax.sql.rowset.CachedRowSet; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.onap.ccsdk.sli.core.dblib.DBResourceManager; -import org.onap.ccsdk.sli.core.dblib.DbLibService; - -public class DbServiceUtil -{ - private static final Logger log = LoggerFactory - .getLogger(DbServiceUtil.class); - - private static Properties props; - private static DBResourceManager jdbcDataSource = null; - - - public static boolean updateDB(String tableName, ArrayList inputArgs, String scema, String whereClause, String setCluase) throws SQLException - { - String updatePasswordString = "update " + tableName + " set " + setCluase + " where " + whereClause ; - boolean result = jdbcDataSource.writeData(updatePasswordString, inputArgs,Constants.SCHEMA_SDNCTL); - return result; - } - - - public static CachedRowSet getData(String tableName, ArrayList argList, String schema, String getselectData, String getDataClasue ) throws SQLException - { - String selectQuery = "select " + getselectData + "from " + tableName + " where " + getDataClasue ; - CachedRowSet data = jdbcDataSource.getData(selectQuery, argList, schema); - return data; - } - - - public static DBResourceManager initDbLibService() throws Exception - { - props = new Properties(); - File file = new File("/opt/app/bvc/properties/dblib.properties"); - URL propURL = file.toURI().toURL(); - props.load(propURL.openStream()); - jdbcDataSource = new DBResourceManager(props); - return jdbcDataSource; - - } - - - -} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/EscapeUtils.java b/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/EscapeUtils.java deleted file mode 100644 index 36afe76ae..000000000 --- a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/EscapeUtils.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.tool; - -import org.apache.commons.lang3.StringUtils; - -public class EscapeUtils { - - public EscapeUtils() { - // TODO Auto-generated constructor stub - } - - public static String escapeSql(String str) { - if (str == null) { - return null; - } - String searchList[] = new String[]{"'","\\"}; - String replacementList[] = new String[]{ "''","\\\\"}; - return StringUtils.replaceEach(str,searchList, replacementList); - } - - public static String unescapeSql(String str) { - if (str == null) { - return null; - } - - String searchList[] = new String[] {"''"}; - String replacementList[] = new String[] {"'"}; - return StringUtils.replaceEach(str, searchList, replacementList); - } - - - // For Generic Purpose - public static String escapeSQL(String s) { - if (s == null) { - return null; - } - - int length = s.length(); - int newLength = length; - for (int i = 0; i < length; i++) { - char c = s.charAt(i); - switch (c) { - case '\\': - case '\"': - case '\'': - case '\0': { - newLength += 1; - } - break; - } - } - if (length == newLength) { - // nothing to escape in the string - return s; - } - StringBuffer sb = new StringBuffer(newLength); - for (int i = 0; i < length; i++) { - char c = s.charAt(i); - switch (c) { - case '\\': { - sb.append("\\\\"); - } - break; - case '\"': { - sb.append("\\\""); - } - break; - case '\'': { - sb.append("\\\'"); - } - break; - case '\0': { - sb.append("\\0"); - } - break; - default: { - sb.append(c); - } - } - } - return sb.toString(); - } -} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/JSONTool.java b/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/JSONTool.java deleted file mode 100644 index 63fd7006e..000000000 --- a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/JSONTool.java +++ /dev/null @@ -1,157 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.tool; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.codehaus.jettison.json.JSONArray; -import org.codehaus.jettison.json.JSONException; -import org.codehaus.jettison.json.JSONObject; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - - - -public class JSONTool { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(JSONTool.class); - - public static Map convertToProperties(String s) throws JSONException { - return convertToProperties(s, null); - } - - public static Map convertToProperties(String s,List blockKeys) throws JSONException { - JSONObject json = new JSONObject(s); - Map mm = new HashMap(); - - Map wm = new HashMap(); - Iterator ii = json.keys(); - while (ii.hasNext()) { - String key1 = ii.next(); - wm.put(key1, json.get(key1)); - - - } - - while (!wm.isEmpty()) - for (String key : new ArrayList<>(wm.keySet())) { - Object o = wm.get(key); - wm.remove(key); - - - if(blockKeys != null && blockKeys.contains(key) && o != null){ - //log.info("Adding JSON Block Keys : " + key + "=" + o.toString()); - mm.put("block_" +key,o.toString()); - } - - if (o instanceof Boolean || o instanceof Number || o instanceof String) { - mm.put(key, o.toString()); - //log.info("Added property: " + key + ": " + o.toString()); - } - - else if (o instanceof JSONObject) { - JSONObject jo = (JSONObject) o; - Iterator i = jo.keys(); - while (i.hasNext()) { - String key1 = i.next(); - wm.put(key + "." + key1, jo.get(key1)); - } - } - - else if (o instanceof JSONArray) { - JSONArray ja = (JSONArray) o; - mm.put("size_"+key, String.valueOf(ja.length())); - - //log.info("Added property: " + key + "_length" + ": " + String.valueOf(ja.length())); - - for (int i = 0; i < ja.length(); i++) - wm.put(key + '[' + i + ']', ja.get(i)); - } - } - - return mm; - } - - /* - public static Map convertToProperties1(String s,List blockKeys) throws Exception { - ObjectMapper objectMapper = new ObjectMapper(); - - JsonNode rootNode = objectMapper.readTree(s); - - Map mm = new HashMap(); - - Map wm = new HashMap(); - Iterator ii = rootNode.fieldNames(); - while (ii.hasNext()) { - String key1 = ii.next(); - wm.put(key1, rootNode.get(key1)); - - - } - - while (!wm.isEmpty()) - for (String key : new ArrayList<>(wm.keySet())) { - Object o = wm.get(key); - wm.remove(key); - - - if(blockKeys != null && blockKeys.contains(key) && o != null){ - //log.info("Adding JSON Block Keys : " + key + "=" + o.toString()); - mm.put("block_" +key,o.toString()); - } - - if (o instanceof Boolean || o instanceof Number || o instanceof String) { - mm.put(key, o.toString()); - //log.info("Added property: " + key + ": " + o.toString()); - } - - else if (o instanceof JSONObject) { - JSONObject jo = (JSONObject) o; - Iterator i = jo.keys(); - while (i.hasNext()) { - String key1 = i.next(); - wm.put(key + "." + key1, jo.get(key1)); - } - } - - else if (o instanceof JSONArray) { - JSONArray ja = (JSONArray) o; - mm.put("size_"+key, String.valueOf(ja.length())); - - //log.info("Added property: " + key + "_length" + ": " + String.valueOf(ja.length())); - - for (int i = 0; i < ja.length(); i++) - wm.put(key + '[' + i + ']', ja.get(i)); - } - } - - return mm; - } -*/ - -} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/LogParserTool.java b/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/LogParserTool.java deleted file mode 100644 index 54823bc17..000000000 --- a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/LogParserTool.java +++ /dev/null @@ -1,94 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.tool; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class LogParserTool { - private static final EELFLogger log = EELFManager.getInstance().getLogger(JSONTool.class); - - private String[] singleLines; - private List recentErrors = new ArrayList ();; - private Date todaysDate = new Date(); - private SimpleDateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); - private final int minMilli = 60000; - private final int IN_TIME = 0; - private final int NOT_IN_TIME = 1; - private final int NO_DATE = 2; - - public String parseErrorLog(String data){ - singleLines = data.split("\\r?\\n"); - try { - getNearestDates(); - - } catch (Exception e) { - e.printStackTrace(); - } - if(recentErrors.size() == 0){ - recentErrors.clear(); - return "Did not find the string 'Starting orchestration of file backed up to /var/opt/MetaSwitch/orch/orch_conf.json' in the log file with timestamp within the last 5 minutes"; - }else if(recentErrors.size() == 1){ - recentErrors.clear(); - return "Did not find the string ‘Error parsing orchestration file’ in the log file with timestamp within the last 5 minutes"; - }else{ - String error = recentErrors.get(0); - recentErrors.clear(); - return "Error: "+ error.substring(error.indexOf("Error parsing orchestration file:")+34); - } - } - - public void getNearestDates() throws ParseException{ - int result; - for( int i = singleLines.length-1; i >= 0 ; i--){ - if(singleLines[i].contains("Starting orchestration of file backed up to") || singleLines[i].contains("Error parsing orchestration file:")){ - result = checkDateTime(singleLines[i]); - if( result == IN_TIME) - recentErrors.add(singleLines[i]); - else if(result == NOT_IN_TIME){ - return; - } - } - } - } - - private int checkDateTime(String line){ - Date newDate; - try { - newDate = dFormat.parse(line.substring(0, 19)); - if((todaysDate.getTime() - newDate.getTime()) <= 5*minMilli){ - return IN_TIME; - }else - return NOT_IN_TIME; - } catch (ParseException e) { - e.printStackTrace(); - return NO_DATE; - } - } - - -} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/MergeTool.java b/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/MergeTool.java deleted file mode 100644 index 0958deebb..000000000 --- a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/tool/MergeTool.java +++ /dev/null @@ -1,109 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.tool; - -import java.io.IOException; -import java.io.StringWriter; -import java.util.Iterator; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.Velocity; -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.runtime.RuntimeConstants; -import org.apache.velocity.runtime.resource.loader.StringResourceLoader; -import org.apache.velocity.runtime.resource.util.StringResourceRepository; -import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - - -public class MergeTool { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(MergeTool.class); - - public static String mergeMap2TemplateData(String template, Map< String, String> dataMap ){ - log.info("MergeMap2TemplateData Template :"+ template + " Maps :"+ dataMap); - StringWriter writer = new StringWriter(); - VelocityEngine ve = new VelocityEngine(); - ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "string"); - ve.addProperty("string.resource.loader.class", StringResourceLoader.class.getName()); - ve.addProperty("string.resource.loader.repository.static", "false"); - ve.init(); - - StringResourceRepository repo = (StringResourceRepository)ve.getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT); - repo.putStringResource("TemplateResource", template); - - Template t = ve.getTemplate("TemplateResource"); - VelocityContext context = new VelocityContext(); - Iterator> entries = dataMap.entrySet().iterator(); - while (entries.hasNext()) { - Map.Entry entry = entries.next(); - context.put(entry.getKey(), entry.getValue()); - } - t.merge(context, writer); - return writer.toString(); - } - - - public static String mergeJson2TemplateData(String template, String jsonData, String templateType, String doPrettyOutput) throws JsonParseException, JsonMappingException, IOException{ - String mergedData = template; - if( StringUtils.isNotBlank(template) && StringUtils.isNotBlank(jsonData)){ - Velocity.init(); - - ObjectMapper mapper = new ObjectMapper(); - CustomJsonNodeFactory f = new CustomJsonNodeFactory(); - mapper.setNodeFactory(f); - - JsonNode jsonObj = mapper.readValue(jsonData, JsonNode.class); - - VelocityContext context = new VelocityContext(); - Iterator ii = jsonObj.fieldNames(); - while (ii.hasNext()) { - String key = ii.next(); - context.put(key, jsonObj.get(key)); - } - - StringWriter writer = new StringWriter(); - Velocity.evaluate(context, writer, "TemplateData", template); - writer.flush(); - mergedData = writer.toString(); - - if(StringUtils.isNotBlank(templateType) && StringUtils.isNotBlank(doPrettyOutput) - && ConfigGeneratorConstant.Y.equalsIgnoreCase(doPrettyOutput) - && ( ConfigGeneratorConstant.DATA_TYPE_JSON.equalsIgnoreCase(templateType) - || ConfigGeneratorConstant.DATA_TYPE_XML.equalsIgnoreCase(templateType)) ){ - // Perform Prettying - - } - } - return mergedData; - - } - -} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/transform/XSLTTransformerNode.java b/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/transform/XSLTTransformerNode.java deleted file mode 100644 index 682b3f2c1..000000000 --- a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/transform/XSLTTransformerNode.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.transform; - -import java.io.File; -import java.io.StringReader; -import java.io.StringWriter; -import java.nio.charset.Charset; -import java.util.Map; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.stream.StreamResult; -import javax.xml.transform.stream.StreamSource; - - -public class XSLTTransformerNode implements SvcLogicJavaPlugin { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(XSLTTransformerNode.class); - - public void transformData(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - log.trace("Received convertJson2DGContext call with params : " + inParams); - String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); - try { - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix + ".") : ""; - - String templateData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_DATA); - - if (StringUtils.isNotBlank(templateData)) { - String templateFile = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_FILE); - if (StringUtils.isNotBlank(templateFile)) { - templateData = FileUtils.readFileToString(new File(templateFile), Charset.defaultCharset()); - } - } - if (StringUtils.isBlank(templateData)) { - throw new Exception("In-param templateFile/templateData value is missing"); - } - - String requestData = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_REQUEST_DATA); - if (StringUtils.isBlank(requestData)) { - throw new Exception("In-param requestData value is missing"); - } - - String transformedData = transform(requestData, templateData); - log.trace("Transformed Data : "+ transformedData); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_TRANSFORMED_DATA, transformedData); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - } catch (Exception e) { - e.printStackTrace(); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, - ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in XSLTTransformerNode : " + e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - } - - public String transform(String requestData, String templateData) - throws TransformerConfigurationException, TransformerException { - StringWriter xmlResultResource = new StringWriter(); - Transformer xmlTransformer = TransformerFactory.newInstance().newTransformer(new StreamSource(new StringReader(templateData))); - xmlTransformer.transform(new StreamSource(new StringReader(requestData)), new StreamResult(xmlResultResource)); - return xmlResultResource.getBuffer().toString(); - } - -} diff --git a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/writer/FileWriterNode.java b/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/writer/FileWriterNode.java deleted file mode 100644 index e383476c2..000000000 --- a/appc-config/appc-config-generator/provider/src/main/java/org/openecomp/sdnc/config/generator/writer/FileWriterNode.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.writer; - -import java.io.File; -import java.util.Map; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; - - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -public class FileWriterNode implements SvcLogicJavaPlugin { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(FileWriterNode.class); - - - - public void writeFile(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - log.info("Received writeFile call with params : " + inParams); - String responsePrefix = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX); - try{ - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - String fileName = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_FILE_NAME); - String fileContents = inParams.get(ConfigGeneratorConstant.INPUT_PARAM_REQUEST_DATA); - - - File file = new File(fileName); - File filePath = file.getParentFile(); - FileUtils.forceMkdir(filePath); - - FileUtils.writeStringToFile(file, fileContents, ConfigGeneratorConstant.STRING_ENCODING); - - - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS, ConfigGeneratorConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + ConfigGeneratorConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); - log.error("Failed in writeFile " + e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - } - - - -} diff --git a/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/convert/TestConvertNode.java b/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/convert/TestConvertNode.java new file mode 100644 index 000000000..0bfb80cf1 --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/convert/TestConvertNode.java @@ -0,0 +1,146 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.convert; + +import static org.junit.Assert.assertEquals; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import org.apache.commons.io.IOUtils; +import org.junit.Test; +import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; +import org.openecomp.sdnc.config.generator.merge.TestMergeNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.powermock.reflect.Whitebox; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class TestConvertNode { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(TestConvertNode.class); + @Test(expected = Exception.class) + public void testPayloadParametersConfig() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + Map inParams = new HashMap(); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_IS_ESCAPED, "N"); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_BLOCK_KEYS, + "configuration-parameters,configuration.configuration-json,configuration.configuration-string"); + convertJson2Context("convert/payload_parameters_config.json", inParams, ctx); + Whitebox.invokeMethod("convertJson2Context", "convert/payload_parameters_config.json", inParams, ctx); + log.info("testPayloadParametersConfig Result: " + ctx.getAttribute("block_configuration-parameters")); + } + + @Test + public void testPayloadCliConfig() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + Map inParams = new HashMap(); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_IS_ESCAPED, "N"); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_BLOCK_KEYS, + "configuration-parameters,configuration.configuration-json,configuration.configuration-string"); + convertJson2Context("convert/payload_cli_config.json", inParams, ctx); + log.info("testPayloadCliConfig Result: " + ctx.getAttribute("block_configuration-parameters")); + log.info("testPayloadCliConfig Result: " + ctx.getAttribute("block_configuration.configuration-string")); + } + + @Test(expected = Exception.class) + public void testPayloadXMLConfig() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + Map inParams = new HashMap(); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_IS_ESCAPED, "N"); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_BLOCK_KEYS, + "configuration-parameters,configuration.configuration-json,configuration.configuration-string"); + convertJson2Context("convert/payload_xml_config.json", inParams, ctx); + log.info("testPayloadXMLConfig Result: " + ctx.getAttribute("block_configuration-parameters")); + log.info("testPayloadXMLConfig Result: " + ctx.getAttribute("block_configuration.configuration-string")); + } + + @Test(expected = Exception.class) + public void testPayloadJsonConfig() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + Map inParams = new HashMap(); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_IS_ESCAPED, "N"); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_BLOCK_KEYS, + "configuration-parameters,configuration.configuration-json,configuration.configuration-string"); + convertJson2Context("convert/payload_json_config.json", inParams, ctx); + log.info("testPayloadJsonConfig Result: " + ctx.getAttribute("block_configuration-parameters")); + log.info("testPayloadJsonConfig Result: " + ctx.getAttribute("block_configuration.configuration-json")); + } + + private void convertJson2Context(String jsonFile, Map inParams, SvcLogicContext ctx) + throws IOException, SvcLogicException { + ConvertNode convertNode = new ConvertNode(); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); + String jsonData = IOUtils.toString(TestMergeNode.class.getClassLoader().getResourceAsStream(jsonFile)); + log.info("TestConvertNode.testConvertJson2DGContext()" + jsonData); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_JSON_DATA, jsonData); + convertNode.convertJson2DGContext(inParams, ctx); + assertEquals(ctx.getAttribute("test." + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), + ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + } + + @Test(expected = Exception.class) + public void testEscapeData() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + Map inParams = new HashMap(); + String unescapeData = IOUtils + .toString(TestMergeNode.class.getClassLoader().getResourceAsStream("convert/escape/config_ssc.txt")); + log.info("TestConvertNode.testEscapeData() unescapeData :" + unescapeData); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_UNESCAPE_DATA, unescapeData); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_DATA_TYPE, ConfigGeneratorConstant.DATA_TYPE_SQL); + ConvertNode convertNode = new ConvertNode(); + convertNode.escapeData(inParams, ctx); + log.info("testEscapeData Result: " + + ctx.getAttribute("test." + ConfigGeneratorConstant.OUTPUT_PARAM_ESCAPE_DATA)); + } + + @Test + public void testConvertContextToJson() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("tmp.uploadConfigInfo.UPLOAD-CONFIG-ID", "200"); + ctx.setAttribute("tmp.uploadConfigInfo.VNF-ID", "00000"); + ctx.setAttribute("tmp.uploadConfigInfo.test[0]", "test0"); + ctx.setAttribute("tmp.uploadConfigInfo.test[1]", "test1"); + ctx.setAttribute("tmp.uploadConfigInfo.test[2]", "test2"); + ConvertNode convertNode = new ConvertNode(); + Map inParams = new HashMap(); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); + inParams.put("contextKey", "tmp.uploadConfigInfo"); + convertNode.convertContextToJson(inParams, ctx); + log.info("JSON CONTENT " + ctx.getAttribute("test.jsonContent")); + assertEquals(ctx.getAttribute("test." + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), + ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + + } + @Test(expected = Exception.class) + public void testunEscapeData() throws Exception { + ConvertNode convertNode = new ConvertNode(); + Map inParams = new HashMap(); + SvcLogicContext ctx = new SvcLogicContext(); + log.trace("Received unEscapeData call with params : " + inParams); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "tmp"); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_ESCAPE_DATA, "//"); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_DATA_TYPE, "String"); + convertNode.unEscapeData(inParams, ctx); + + } +} diff --git a/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/merge/TestMergeNode.java b/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/merge/TestMergeNode.java new file mode 100644 index 000000000..cd7bb9e9a --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/merge/TestMergeNode.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.merge; + +import org.apache.commons.io.IOUtils; +import org.junit.Test; +import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; +import org.openecomp.sdnc.config.generator.merge.MergeNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import static org.junit.Assert.assertEquals; +import java.util.HashMap; +import java.util.Map; + +public class TestMergeNode { + + @Test(expected = Exception.class) + public void testMergeJsonDataOnTemplate() throws Exception { + MergeNode mergeNode = new MergeNode(); + Map inParams = new HashMap(); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); + String jsonData = IOUtils + .toString(TestMergeNode.class.getClassLoader().getResourceAsStream("merge/vdbe_data.json")); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_JSON_DATA, jsonData); + String templateData = IOUtils + .toString(TestMergeNode.class.getClassLoader().getResourceAsStream("merge/vdbe_template.xml")); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_DATA, templateData); + SvcLogicContext ctx = new SvcLogicContext(); + mergeNode.mergeJsonDataOnTemplate(inParams, ctx); + assertEquals(ctx.getAttribute("test." + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), + ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + + } + + @Test(expected = Exception.class) + public void testMergeComplexJsonDataOnTemplate() throws Exception { + MergeNode mergeNode = new MergeNode(); + Map inParams = new HashMap(); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); + String jsonData = IOUtils + .toString(TestMergeNode.class.getClassLoader().getResourceAsStream("merge/complex/vdbe_data.json")); + System.out.println("TestMergeNode.testMergeJsonComplexDataOnTemplate()" + jsonData); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_JSON_DATA, jsonData); + + String templateData = IOUtils + .toString(TestMergeNode.class.getClassLoader().getResourceAsStream("merge/complex/vdbe_template.xml")); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_DATA, templateData); + SvcLogicContext ctx = new SvcLogicContext(); + mergeNode.mergeComplexJsonDataOnTemplate(inParams, ctx); + assertEquals(ctx.getAttribute("test." + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), + ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + + } + + @Test(expected = Exception.class) + public void testMergeJsonDataOnTemplateFile() throws Exception { + MergeNode mergeNode = new MergeNode(); + Map inParams = new HashMap(); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); + String jsonData = IOUtils + .toString(TestMergeNode.class.getClassLoader().getResourceAsStream("merge/vdbe_data.json")); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_JSON_DATA, jsonData); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_FILE, "merge/vdbe_template.xml"); + + SvcLogicContext ctx = new SvcLogicContext(); + mergeNode.mergeJsonDataOnTemplate(inParams, ctx); + assertEquals(ctx.getAttribute("test." + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), + ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + } + @Test + public void testMmergeDataOnTemplate() throws SvcLogicException { + MergeNode mergeNode = new MergeNode(); + SvcLogicContext ctx = new SvcLogicContext(); + Map inParams = new HashMap(); + mergeNode.mergeDataOnTemplate(inParams, ctx); + } + + @Test + public void mergeYamlDataOnTemplate() throws SvcLogicException { + MergeNode mergeNode = new MergeNode(); + SvcLogicContext ctx = new SvcLogicContext(); + Map inParams = new HashMap(); + mergeNode.mergeYamlDataOnTemplate(inParams, ctx); + } +} diff --git a/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/pattern/TestPatternNode.java b/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/pattern/TestPatternNode.java new file mode 100644 index 000000000..db3fa7149 --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/pattern/TestPatternNode.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.pattern; + +import static org.junit.Assert.assertEquals; +import java.util.HashMap; +import java.util.Map; +import org.apache.commons.io.IOUtils; +import org.junit.Test; +import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; +import org.openecomp.sdnc.config.generator.pattern.PatternNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class TestPatternNode { + + @Test + public void parseErrorLog() throws Exception { + PatternNode patternNode = new PatternNode(); + Map inParams = new HashMap(); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); + String logData = IOUtils.toString(TestPatternNode.class.getClassLoader().getResourceAsStream("pattern/errorlog.txt"),ConfigGeneratorConstant.STRING_ENCODING); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_LOG_DATA, logData); + SvcLogicContext ctx = new SvcLogicContext(); + patternNode.parseErrorLog(inParams, ctx); + assertEquals(ctx.getAttribute("test."+ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + + } +// @Test(expected=Exception.class) + public void checkXMLData() throws Exception { + PatternNode patternNode = new PatternNode(); + Map inParams = new HashMap(); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); + + String xmlData = IOUtils.toString(TestPatternNode.class.getClassLoader().getResourceAsStream("pattern/xml_data.xml"),ConfigGeneratorConstant.STRING_ENCODING); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_CHECK_DATA, xmlData); + SvcLogicContext ctx = new SvcLogicContext(); + patternNode.checkDataType(inParams, ctx); + } + + //@Test + public void checkJsonData() throws Exception { + PatternNode patternNode = new PatternNode(); + Map inParams = new HashMap(); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); + String xmlData = IOUtils.toString(TestPatternNode.class.getClassLoader().getResourceAsStream("pattern/json_data.json"),ConfigGeneratorConstant.STRING_ENCODING); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_CHECK_DATA, xmlData); + SvcLogicContext ctx = new SvcLogicContext(); + patternNode.checkDataType(inParams, ctx); + assertEquals(ctx.getAttribute("test."+ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + } + + @Test(expected=Exception.class) + public void checStringData() throws Exception { + PatternNode patternNode = new PatternNode(); + Map inParams = new HashMap(); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); + String stringData = IOUtils.toString(TestPatternNode.class.getClassLoader().getResourceAsStream("pattern/text_data.txt"),ConfigGeneratorConstant.STRING_ENCODING); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_CHECK_DATA, stringData); + SvcLogicContext ctx = new SvcLogicContext(); + patternNode.checkDataType(inParams, ctx); + assertEquals(ctx.getAttribute("test."+ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + } +} diff --git a/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/reader/TestReaderNode.java b/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/reader/TestReaderNode.java new file mode 100644 index 000000000..cda966b60 --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/reader/TestReaderNode.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.reader; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import org.apache.commons.io.IOUtils; +import org.junit.Test; +import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; +import org.openecomp.sdnc.config.generator.merge.TestMergeNode; +import org.openecomp.sdnc.config.generator.reader.ReaderNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +public class TestReaderNode { + @Test(expected = Exception.class) + public void testGetFileData() throws SvcLogicException, IOException { + ReaderNode r = new ReaderNode(); + Map inParams = new HashMap(); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_FILE_NAME, IOUtils + .toString(TestMergeNode.class.getClassLoader().getResourceAsStream("convert/payload_cli_config.json"))); + SvcLogicContext ctx = new SvcLogicContext(); + r.getFileData(inParams, ctx); + } +} diff --git a/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/tool/TestDataTool.java b/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/tool/TestDataTool.java new file mode 100644 index 000000000..85230f472 --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/tool/TestDataTool.java @@ -0,0 +1,153 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.tool; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.io.IOUtils; +import org.junit.Test; +import org.mockito.Mock; +import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; +import org.openecomp.sdnc.config.generator.pattern.TestPatternNode; +import org.openecomp.sdnc.config.generator.tool.CheckDataTool; +import org.powermock.reflect.Whitebox; + +public class TestDataTool { + @Mock + LogParserTool lp = new LogParserTool(); + + @Test + public void testCheckData() throws IOException { + String data = IOUtils.toString( + TestPatternNode.class.getClassLoader().getResourceAsStream("convert/payload_cli_config.json"), + ConfigGeneratorConstant.STRING_ENCODING); + CheckDataTool.checkData(data); + } + + @Test + public void testIsJSON() throws IOException { + String data = IOUtils.toString( + TestPatternNode.class.getClassLoader().getResourceAsStream("convert/payload_cli_config.json"), + ConfigGeneratorConstant.STRING_ENCODING); + CheckDataTool.isJSON(data); + } + + @Test + public void testIsXML() throws IOException { + String data = IOUtils.toString( + TestPatternNode.class.getClassLoader().getResourceAsStream("pattern/xml_data.xml"), + ConfigGeneratorConstant.STRING_ENCODING); + CheckDataTool.isXML(data); + } + + @Test + public void testNode() { + CustomJsonNodeFactory c = new CustomJsonNodeFactory(); + String text = "test"; + c.textNode(text); + } + + @Test + public void testCustomText() { + CustomTextNode c = new CustomTextNode("test"); + c.toString(); + } + + @Test + public void testEscapeUtils() { + String s = "test\\"; + String st = "test\"test"; + String str = "test\'" + "test"; + String strng = "test\0"; + EscapeUtils.escapeSQL(s); + EscapeUtils.escapeSql(s); + EscapeUtils.escapeSQL(st); + EscapeUtils.escapeSQL(str); + EscapeUtils.escapeSQL(strng); + EscapeUtils.escapeSQL(null); + } + +// @Test(expected = Exception.class) + public void testgetData() throws Exception { + ArrayList argList = null; + String schema = "sdnctl"; + String tableName = "dual"; + String getselectData = "123"; + String getDataClasue = "123='123'"; + DbServiceUtil.getData(tableName, argList, schema, getselectData, getDataClasue); + } + +// @Test(expected = Exception.class) + public void testupdateDB() throws Exception { + String setCluase = null; + String schema = "sdnctl"; + String tableName = "dual"; + ArrayList inputArgs = null; + String whereClause = "123='123'"; + DbServiceUtil.updateDB(tableName, inputArgs, schema, whereClause, setCluase); + } + +// @Test(expected = Exception.class) + public void testinitDbLibService() throws Exception { + DbServiceUtil.initDbLibService(); + } + + @Test + public void testJSONTool() throws Exception { + String data = IOUtils.toString( + TestPatternNode.class.getClassLoader().getResourceAsStream("convert/payload_cli_config.json"), + ConfigGeneratorConstant.STRING_ENCODING); + JSONTool.convertToProperties(data); + List blockKeys = new ArrayList(); + blockKeys.add("vnf-type"); + blockKeys.add("request-parameters"); + JSONTool.convertToProperties(data, blockKeys); + } + + @Test + public void testLogParserTool() throws Exception { + String data = IOUtils.toString( + TestPatternNode.class.getClassLoader().getResourceAsStream("pattern/errorlog.txt"), + ConfigGeneratorConstant.STRING_ENCODING); + LogParserTool lpt = new LogParserTool(); + lpt.parseErrorLog(data); + } + + @Test + public void testMergeTool() throws Exception { + String template = "test"; + Map dataMap = new HashMap(); + MergeTool.mergeMap2TemplateData(template, dataMap); + } + + @Test + public void testcheckDateTime() throws Exception { + String line = "2017-08-20T17:40:23.100361+00:00"; + Whitebox.invokeMethod(lp, "checkDateTime", line); + } +} diff --git a/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/transform/TestXSLTTransformerNode.java b/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/transform/TestXSLTTransformerNode.java new file mode 100644 index 000000000..e2e808192 --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/transform/TestXSLTTransformerNode.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.transform; + +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; +import org.apache.commons.io.IOUtils; +import org.junit.Test; +import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; +import org.openecomp.sdnc.config.generator.merge.TestMergeNode; +import org.openecomp.sdnc.config.generator.transform.XSLTTransformerNode; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class TestXSLTTransformerNode { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(TestXSLTTransformerNode.class); + + @Test + public void transformData() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + String templateData = IOUtils.toString( + TestMergeNode.class.getClassLoader().getResourceAsStream("transform/template.xsl"), + Charset.defaultCharset()); + String requestData = IOUtils.toString( + TestMergeNode.class.getClassLoader().getResourceAsStream("transform/request.xml"), + Charset.defaultCharset()); + Map inParams = new HashMap(); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_DATA, templateData); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_REQUEST_DATA, requestData); + XSLTTransformerNode transformerNode = new XSLTTransformerNode(); + transformerNode.transformData(inParams, ctx); + log.info("transformData Result: " + ctx.getAttribute(ConfigGeneratorConstant.OUTPUT_PARAM_TRANSFORMED_DATA)); + + } +} diff --git a/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/writer/TestFileWriterNode.java b/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/writer/TestFileWriterNode.java new file mode 100644 index 000000000..74c17bdc6 --- /dev/null +++ b/appc-config/appc-config-generator/provider/src/test/java/org/onap/sdnc/config/generator/writer/TestFileWriterNode.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.generator.writer; + +import static org.junit.Assert.assertEquals; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; +import org.openecomp.sdnc.config.generator.writer.FileWriterNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class TestFileWriterNode { + + @Test + public void writeFile() throws Exception { + FileWriterNode FileWriterNode = new FileWriterNode(); + Map inParams = new HashMap(); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_FILE_NAME, "src/test/resources/writer/testcvaas.json"); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_REQUEST_DATA, "{'name':'Name','role':'admin'}"); + inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); + SvcLogicContext ctx = new SvcLogicContext(); + FileWriterNode.writeFile(inParams, ctx); + assertEquals(ctx.getAttribute("test." + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), + ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); + } +} diff --git a/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/convert/TestConvertNode.java b/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/convert/TestConvertNode.java deleted file mode 100644 index 0bfb80cf1..000000000 --- a/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/convert/TestConvertNode.java +++ /dev/null @@ -1,146 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.convert; - -import static org.junit.Assert.assertEquals; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import org.apache.commons.io.IOUtils; -import org.junit.Test; -import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; -import org.openecomp.sdnc.config.generator.merge.TestMergeNode; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.powermock.reflect.Whitebox; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class TestConvertNode { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(TestConvertNode.class); - @Test(expected = Exception.class) - public void testPayloadParametersConfig() throws Exception { - SvcLogicContext ctx = new SvcLogicContext(); - Map inParams = new HashMap(); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_IS_ESCAPED, "N"); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_BLOCK_KEYS, - "configuration-parameters,configuration.configuration-json,configuration.configuration-string"); - convertJson2Context("convert/payload_parameters_config.json", inParams, ctx); - Whitebox.invokeMethod("convertJson2Context", "convert/payload_parameters_config.json", inParams, ctx); - log.info("testPayloadParametersConfig Result: " + ctx.getAttribute("block_configuration-parameters")); - } - - @Test - public void testPayloadCliConfig() throws Exception { - SvcLogicContext ctx = new SvcLogicContext(); - Map inParams = new HashMap(); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_IS_ESCAPED, "N"); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_BLOCK_KEYS, - "configuration-parameters,configuration.configuration-json,configuration.configuration-string"); - convertJson2Context("convert/payload_cli_config.json", inParams, ctx); - log.info("testPayloadCliConfig Result: " + ctx.getAttribute("block_configuration-parameters")); - log.info("testPayloadCliConfig Result: " + ctx.getAttribute("block_configuration.configuration-string")); - } - - @Test(expected = Exception.class) - public void testPayloadXMLConfig() throws Exception { - SvcLogicContext ctx = new SvcLogicContext(); - Map inParams = new HashMap(); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_IS_ESCAPED, "N"); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_BLOCK_KEYS, - "configuration-parameters,configuration.configuration-json,configuration.configuration-string"); - convertJson2Context("convert/payload_xml_config.json", inParams, ctx); - log.info("testPayloadXMLConfig Result: " + ctx.getAttribute("block_configuration-parameters")); - log.info("testPayloadXMLConfig Result: " + ctx.getAttribute("block_configuration.configuration-string")); - } - - @Test(expected = Exception.class) - public void testPayloadJsonConfig() throws Exception { - SvcLogicContext ctx = new SvcLogicContext(); - Map inParams = new HashMap(); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_IS_ESCAPED, "N"); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_BLOCK_KEYS, - "configuration-parameters,configuration.configuration-json,configuration.configuration-string"); - convertJson2Context("convert/payload_json_config.json", inParams, ctx); - log.info("testPayloadJsonConfig Result: " + ctx.getAttribute("block_configuration-parameters")); - log.info("testPayloadJsonConfig Result: " + ctx.getAttribute("block_configuration.configuration-json")); - } - - private void convertJson2Context(String jsonFile, Map inParams, SvcLogicContext ctx) - throws IOException, SvcLogicException { - ConvertNode convertNode = new ConvertNode(); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); - String jsonData = IOUtils.toString(TestMergeNode.class.getClassLoader().getResourceAsStream(jsonFile)); - log.info("TestConvertNode.testConvertJson2DGContext()" + jsonData); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_JSON_DATA, jsonData); - convertNode.convertJson2DGContext(inParams, ctx); - assertEquals(ctx.getAttribute("test." + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), - ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - } - - @Test(expected = Exception.class) - public void testEscapeData() throws Exception { - SvcLogicContext ctx = new SvcLogicContext(); - Map inParams = new HashMap(); - String unescapeData = IOUtils - .toString(TestMergeNode.class.getClassLoader().getResourceAsStream("convert/escape/config_ssc.txt")); - log.info("TestConvertNode.testEscapeData() unescapeData :" + unescapeData); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_UNESCAPE_DATA, unescapeData); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_DATA_TYPE, ConfigGeneratorConstant.DATA_TYPE_SQL); - ConvertNode convertNode = new ConvertNode(); - convertNode.escapeData(inParams, ctx); - log.info("testEscapeData Result: " - + ctx.getAttribute("test." + ConfigGeneratorConstant.OUTPUT_PARAM_ESCAPE_DATA)); - } - - @Test - public void testConvertContextToJson() throws Exception { - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("tmp.uploadConfigInfo.UPLOAD-CONFIG-ID", "200"); - ctx.setAttribute("tmp.uploadConfigInfo.VNF-ID", "00000"); - ctx.setAttribute("tmp.uploadConfigInfo.test[0]", "test0"); - ctx.setAttribute("tmp.uploadConfigInfo.test[1]", "test1"); - ctx.setAttribute("tmp.uploadConfigInfo.test[2]", "test2"); - ConvertNode convertNode = new ConvertNode(); - Map inParams = new HashMap(); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); - inParams.put("contextKey", "tmp.uploadConfigInfo"); - convertNode.convertContextToJson(inParams, ctx); - log.info("JSON CONTENT " + ctx.getAttribute("test.jsonContent")); - assertEquals(ctx.getAttribute("test." + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), - ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - - } - @Test(expected = Exception.class) - public void testunEscapeData() throws Exception { - ConvertNode convertNode = new ConvertNode(); - Map inParams = new HashMap(); - SvcLogicContext ctx = new SvcLogicContext(); - log.trace("Received unEscapeData call with params : " + inParams); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "tmp"); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_ESCAPE_DATA, "//"); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_DATA_TYPE, "String"); - convertNode.unEscapeData(inParams, ctx); - - } -} diff --git a/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/merge/TestMergeNode.java b/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/merge/TestMergeNode.java deleted file mode 100644 index cd7bb9e9a..000000000 --- a/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/merge/TestMergeNode.java +++ /dev/null @@ -1,103 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.merge; - -import org.apache.commons.io.IOUtils; -import org.junit.Test; -import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; -import org.openecomp.sdnc.config.generator.merge.MergeNode; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import static org.junit.Assert.assertEquals; -import java.util.HashMap; -import java.util.Map; - -public class TestMergeNode { - - @Test(expected = Exception.class) - public void testMergeJsonDataOnTemplate() throws Exception { - MergeNode mergeNode = new MergeNode(); - Map inParams = new HashMap(); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); - String jsonData = IOUtils - .toString(TestMergeNode.class.getClassLoader().getResourceAsStream("merge/vdbe_data.json")); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_JSON_DATA, jsonData); - String templateData = IOUtils - .toString(TestMergeNode.class.getClassLoader().getResourceAsStream("merge/vdbe_template.xml")); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_DATA, templateData); - SvcLogicContext ctx = new SvcLogicContext(); - mergeNode.mergeJsonDataOnTemplate(inParams, ctx); - assertEquals(ctx.getAttribute("test." + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), - ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - - } - - @Test(expected = Exception.class) - public void testMergeComplexJsonDataOnTemplate() throws Exception { - MergeNode mergeNode = new MergeNode(); - Map inParams = new HashMap(); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); - String jsonData = IOUtils - .toString(TestMergeNode.class.getClassLoader().getResourceAsStream("merge/complex/vdbe_data.json")); - System.out.println("TestMergeNode.testMergeJsonComplexDataOnTemplate()" + jsonData); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_JSON_DATA, jsonData); - - String templateData = IOUtils - .toString(TestMergeNode.class.getClassLoader().getResourceAsStream("merge/complex/vdbe_template.xml")); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_DATA, templateData); - SvcLogicContext ctx = new SvcLogicContext(); - mergeNode.mergeComplexJsonDataOnTemplate(inParams, ctx); - assertEquals(ctx.getAttribute("test." + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), - ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - - } - - @Test(expected = Exception.class) - public void testMergeJsonDataOnTemplateFile() throws Exception { - MergeNode mergeNode = new MergeNode(); - Map inParams = new HashMap(); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); - String jsonData = IOUtils - .toString(TestMergeNode.class.getClassLoader().getResourceAsStream("merge/vdbe_data.json")); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_JSON_DATA, jsonData); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_FILE, "merge/vdbe_template.xml"); - - SvcLogicContext ctx = new SvcLogicContext(); - mergeNode.mergeJsonDataOnTemplate(inParams, ctx); - assertEquals(ctx.getAttribute("test." + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), - ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - } - @Test - public void testMmergeDataOnTemplate() throws SvcLogicException { - MergeNode mergeNode = new MergeNode(); - SvcLogicContext ctx = new SvcLogicContext(); - Map inParams = new HashMap(); - mergeNode.mergeDataOnTemplate(inParams, ctx); - } - - @Test - public void mergeYamlDataOnTemplate() throws SvcLogicException { - MergeNode mergeNode = new MergeNode(); - SvcLogicContext ctx = new SvcLogicContext(); - Map inParams = new HashMap(); - mergeNode.mergeYamlDataOnTemplate(inParams, ctx); - } -} diff --git a/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/pattern/TestPatternNode.java b/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/pattern/TestPatternNode.java deleted file mode 100644 index db3fa7149..000000000 --- a/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/pattern/TestPatternNode.java +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.pattern; - -import static org.junit.Assert.assertEquals; -import java.util.HashMap; -import java.util.Map; -import org.apache.commons.io.IOUtils; -import org.junit.Test; -import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; -import org.openecomp.sdnc.config.generator.pattern.PatternNode; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class TestPatternNode { - - @Test - public void parseErrorLog() throws Exception { - PatternNode patternNode = new PatternNode(); - Map inParams = new HashMap(); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); - String logData = IOUtils.toString(TestPatternNode.class.getClassLoader().getResourceAsStream("pattern/errorlog.txt"),ConfigGeneratorConstant.STRING_ENCODING); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_LOG_DATA, logData); - SvcLogicContext ctx = new SvcLogicContext(); - patternNode.parseErrorLog(inParams, ctx); - assertEquals(ctx.getAttribute("test."+ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - - } -// @Test(expected=Exception.class) - public void checkXMLData() throws Exception { - PatternNode patternNode = new PatternNode(); - Map inParams = new HashMap(); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); - - String xmlData = IOUtils.toString(TestPatternNode.class.getClassLoader().getResourceAsStream("pattern/xml_data.xml"),ConfigGeneratorConstant.STRING_ENCODING); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_CHECK_DATA, xmlData); - SvcLogicContext ctx = new SvcLogicContext(); - patternNode.checkDataType(inParams, ctx); - } - - //@Test - public void checkJsonData() throws Exception { - PatternNode patternNode = new PatternNode(); - Map inParams = new HashMap(); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); - String xmlData = IOUtils.toString(TestPatternNode.class.getClassLoader().getResourceAsStream("pattern/json_data.json"),ConfigGeneratorConstant.STRING_ENCODING); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_CHECK_DATA, xmlData); - SvcLogicContext ctx = new SvcLogicContext(); - patternNode.checkDataType(inParams, ctx); - assertEquals(ctx.getAttribute("test."+ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - } - - @Test(expected=Exception.class) - public void checStringData() throws Exception { - PatternNode patternNode = new PatternNode(); - Map inParams = new HashMap(); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); - String stringData = IOUtils.toString(TestPatternNode.class.getClassLoader().getResourceAsStream("pattern/text_data.txt"),ConfigGeneratorConstant.STRING_ENCODING); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_CHECK_DATA, stringData); - SvcLogicContext ctx = new SvcLogicContext(); - patternNode.checkDataType(inParams, ctx); - assertEquals(ctx.getAttribute("test."+ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - } -} diff --git a/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/reader/TestReaderNode.java b/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/reader/TestReaderNode.java deleted file mode 100644 index cda966b60..000000000 --- a/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/reader/TestReaderNode.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.reader; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import org.apache.commons.io.IOUtils; -import org.junit.Test; -import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; -import org.openecomp.sdnc.config.generator.merge.TestMergeNode; -import org.openecomp.sdnc.config.generator.reader.ReaderNode; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; - -public class TestReaderNode { - @Test(expected = Exception.class) - public void testGetFileData() throws SvcLogicException, IOException { - ReaderNode r = new ReaderNode(); - Map inParams = new HashMap(); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_FILE_NAME, IOUtils - .toString(TestMergeNode.class.getClassLoader().getResourceAsStream("convert/payload_cli_config.json"))); - SvcLogicContext ctx = new SvcLogicContext(); - r.getFileData(inParams, ctx); - } -} diff --git a/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/tool/TestDataTool.java b/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/tool/TestDataTool.java deleted file mode 100644 index 85230f472..000000000 --- a/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/tool/TestDataTool.java +++ /dev/null @@ -1,153 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.tool; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.io.IOUtils; -import org.junit.Test; -import org.mockito.Mock; -import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; -import org.openecomp.sdnc.config.generator.pattern.TestPatternNode; -import org.openecomp.sdnc.config.generator.tool.CheckDataTool; -import org.powermock.reflect.Whitebox; - -public class TestDataTool { - @Mock - LogParserTool lp = new LogParserTool(); - - @Test - public void testCheckData() throws IOException { - String data = IOUtils.toString( - TestPatternNode.class.getClassLoader().getResourceAsStream("convert/payload_cli_config.json"), - ConfigGeneratorConstant.STRING_ENCODING); - CheckDataTool.checkData(data); - } - - @Test - public void testIsJSON() throws IOException { - String data = IOUtils.toString( - TestPatternNode.class.getClassLoader().getResourceAsStream("convert/payload_cli_config.json"), - ConfigGeneratorConstant.STRING_ENCODING); - CheckDataTool.isJSON(data); - } - - @Test - public void testIsXML() throws IOException { - String data = IOUtils.toString( - TestPatternNode.class.getClassLoader().getResourceAsStream("pattern/xml_data.xml"), - ConfigGeneratorConstant.STRING_ENCODING); - CheckDataTool.isXML(data); - } - - @Test - public void testNode() { - CustomJsonNodeFactory c = new CustomJsonNodeFactory(); - String text = "test"; - c.textNode(text); - } - - @Test - public void testCustomText() { - CustomTextNode c = new CustomTextNode("test"); - c.toString(); - } - - @Test - public void testEscapeUtils() { - String s = "test\\"; - String st = "test\"test"; - String str = "test\'" + "test"; - String strng = "test\0"; - EscapeUtils.escapeSQL(s); - EscapeUtils.escapeSql(s); - EscapeUtils.escapeSQL(st); - EscapeUtils.escapeSQL(str); - EscapeUtils.escapeSQL(strng); - EscapeUtils.escapeSQL(null); - } - -// @Test(expected = Exception.class) - public void testgetData() throws Exception { - ArrayList argList = null; - String schema = "sdnctl"; - String tableName = "dual"; - String getselectData = "123"; - String getDataClasue = "123='123'"; - DbServiceUtil.getData(tableName, argList, schema, getselectData, getDataClasue); - } - -// @Test(expected = Exception.class) - public void testupdateDB() throws Exception { - String setCluase = null; - String schema = "sdnctl"; - String tableName = "dual"; - ArrayList inputArgs = null; - String whereClause = "123='123'"; - DbServiceUtil.updateDB(tableName, inputArgs, schema, whereClause, setCluase); - } - -// @Test(expected = Exception.class) - public void testinitDbLibService() throws Exception { - DbServiceUtil.initDbLibService(); - } - - @Test - public void testJSONTool() throws Exception { - String data = IOUtils.toString( - TestPatternNode.class.getClassLoader().getResourceAsStream("convert/payload_cli_config.json"), - ConfigGeneratorConstant.STRING_ENCODING); - JSONTool.convertToProperties(data); - List blockKeys = new ArrayList(); - blockKeys.add("vnf-type"); - blockKeys.add("request-parameters"); - JSONTool.convertToProperties(data, blockKeys); - } - - @Test - public void testLogParserTool() throws Exception { - String data = IOUtils.toString( - TestPatternNode.class.getClassLoader().getResourceAsStream("pattern/errorlog.txt"), - ConfigGeneratorConstant.STRING_ENCODING); - LogParserTool lpt = new LogParserTool(); - lpt.parseErrorLog(data); - } - - @Test - public void testMergeTool() throws Exception { - String template = "test"; - Map dataMap = new HashMap(); - MergeTool.mergeMap2TemplateData(template, dataMap); - } - - @Test - public void testcheckDateTime() throws Exception { - String line = "2017-08-20T17:40:23.100361+00:00"; - Whitebox.invokeMethod(lp, "checkDateTime", line); - } -} diff --git a/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/transform/TestXSLTTransformerNode.java b/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/transform/TestXSLTTransformerNode.java deleted file mode 100644 index e2e808192..000000000 --- a/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/transform/TestXSLTTransformerNode.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.transform; - -import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.Map; -import org.apache.commons.io.IOUtils; -import org.junit.Test; -import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; -import org.openecomp.sdnc.config.generator.merge.TestMergeNode; -import org.openecomp.sdnc.config.generator.transform.XSLTTransformerNode; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class TestXSLTTransformerNode { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(TestXSLTTransformerNode.class); - - @Test - public void transformData() throws Exception { - SvcLogicContext ctx = new SvcLogicContext(); - String templateData = IOUtils.toString( - TestMergeNode.class.getClassLoader().getResourceAsStream("transform/template.xsl"), - Charset.defaultCharset()); - String requestData = IOUtils.toString( - TestMergeNode.class.getClassLoader().getResourceAsStream("transform/request.xml"), - Charset.defaultCharset()); - Map inParams = new HashMap(); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_TEMPLATE_DATA, templateData); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_REQUEST_DATA, requestData); - XSLTTransformerNode transformerNode = new XSLTTransformerNode(); - transformerNode.transformData(inParams, ctx); - log.info("transformData Result: " + ctx.getAttribute(ConfigGeneratorConstant.OUTPUT_PARAM_TRANSFORMED_DATA)); - - } -} diff --git a/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/writer/TestFileWriterNode.java b/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/writer/TestFileWriterNode.java deleted file mode 100644 index 74c17bdc6..000000000 --- a/appc-config/appc-config-generator/provider/src/test/java/org/openecomp/sdnc/config/generator/writer/TestFileWriterNode.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.generator.writer; - -import static org.junit.Assert.assertEquals; -import java.util.HashMap; -import java.util.Map; -import org.junit.Test; -import org.openecomp.sdnc.config.generator.ConfigGeneratorConstant; -import org.openecomp.sdnc.config.generator.writer.FileWriterNode; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class TestFileWriterNode { - - @Test - public void writeFile() throws Exception { - FileWriterNode FileWriterNode = new FileWriterNode(); - Map inParams = new HashMap(); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_FILE_NAME, "src/test/resources/writer/testcvaas.json"); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_REQUEST_DATA, "{'name':'Name','role':'admin'}"); - inParams.put(ConfigGeneratorConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); - SvcLogicContext ctx = new SvcLogicContext(); - FileWriterNode.writeFile(inParams, ctx); - assertEquals(ctx.getAttribute("test." + ConfigGeneratorConstant.OUTPUT_PARAM_STATUS), - ConfigGeneratorConstant.OUTPUT_STATUS_SUCCESS); - } -} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/ParamsHandlerActivator.java b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/ParamsHandlerActivator.java new file mode 100644 index 000000000..dd4515cca --- /dev/null +++ b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/ParamsHandlerActivator.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.params; + +import java.util.LinkedList; +import java.util.List; + +import org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ParamsHandlerActivator implements BundleActivator{ + + private List registrations = new LinkedList(); + + + private static final EELFLogger log = EELFManager.getInstance().getLogger(ParamsHandlerActivator.class); + + @Override + public void start(BundleContext ctx) throws Exception + { + + try { + PropertyDefinitionNode propertyDefinitionNode = new PropertyDefinitionNode(); + log.info("Registering service "+ propertyDefinitionNode.getClass().getName()); + registrations.add(ctx.registerService(propertyDefinitionNode.getClass().getName(), propertyDefinitionNode, null)); + log.info("Registering service sccessful for "+ propertyDefinitionNode.getClass().getName()); + } catch (Exception e) { + e.printStackTrace(); + } + + } + @Override + public void stop(BundleContext arg0) throws Exception + { + for (ServiceRegistration registration: registrations) + { + registration.unregister(); + registration = null; + } + + } + +} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/ParamsHandlerConstant.java b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/ParamsHandlerConstant.java new file mode 100644 index 000000000..65b93d738 --- /dev/null +++ b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/ParamsHandlerConstant.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.openecomp.sdnc.config.params; + +public class ParamsHandlerConstant { + + public static String STRING_ENCODING = "utf-8"; + public static String Y = "Y"; + public static String N = "N"; + public static String DATA_TYPE_TEXT = "TEXT"; + public static String DATA_TYPE_JSON = "JSON"; + public static String DATA_TYPE_XML = "XML"; + public static String DATA_TYPE_SQL = "SQL"; + + + public static String INPUT_PARAM_PD_CONTENT = "pdContent"; + public static String INPUT_PARAM_SYSTEM_NAME = "systemName"; + public static String INPUT_PARAM_JSON_DATA = "jsonData"; + public static String INPUT_PARAM_MERGE__JSON_DATA = "mergeJsonData"; + + + public static String INPUT_PARAM_REQUEST_DATA = "requestData"; + public static String INPUT_PARAM_RESPONSE_PRIFIX = "responsePrefix"; + public static String OUTPUT_PARAM_CONFIGURATION_PARAMETER = "configuration-parameters"; + + + + public static String OUTPUT_PARAM_STATUS = "status"; + public static String OUTPUT_PARAM_ERROR_MESSAGE = "error-message"; + public static String OUTPUT_STATUS_SUCCESS = "success"; + public static String OUTPUT_STATUS_FAILURE = "failure"; + +} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/data/Parameter.java b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/data/Parameter.java new file mode 100644 index 000000000..aaa457645 --- /dev/null +++ b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/data/Parameter.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.params.data; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Parameter { + private String name; + private String description; + private String type; + private boolean required; + private String source; + + @JsonProperty("rule-type") + private String ruleType; + + @JsonProperty("default") + private String defaultValue; + + @JsonProperty("request-keys") + private List requestKeys; + + @JsonProperty("response-keys") + private List responseKeys; + + 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 String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public boolean isRequired() { + return required; + } + + public void setRequired(boolean required) { + this.required = required; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + public String getRuleType() { + return ruleType; + } + + public void setRuleType(String ruleType) { + this.ruleType = ruleType; + } + + public String getDefaultValue() { + return defaultValue; + } + + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + public List getRequestKeys() { + return requestKeys; + } + + public void setRequestKeys(List requestKeys) { + this.requestKeys = requestKeys; + } + + public List getResponseKeys() { + return responseKeys; + } + + public void setResponseKeys(List responseKeys) { + this.responseKeys = responseKeys; + } + + + + + +} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/data/PropertyDefinition.java b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/data/PropertyDefinition.java new file mode 100644 index 000000000..d33fd9589 --- /dev/null +++ b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/data/PropertyDefinition.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.params.data; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class PropertyDefinition { + public String kind = "Property Definition"; + public String version = "V1"; + + @JsonProperty("vnf-parameter-list") + public List parameters; + public String getKind() { + return kind; + } + public void setKind(String kind) { + this.kind = kind; + } + public String getVersion() { + return version; + } + public void setVersion(String version) { + this.version = version; + } + public List getParameters() { + return parameters; + } + public void setParameters(List parameters) { + this.parameters = parameters; + } + +} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/data/RequestKey.java b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/data/RequestKey.java new file mode 100644 index 000000000..0589afcc3 --- /dev/null +++ b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/data/RequestKey.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.openecomp.sdnc.config.params.data; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class RequestKey{ + @JsonProperty("key-name") + private String keyName; + @JsonProperty("key-value") + private String keyValue; + + public String getKeyName() { + return keyName; + } + public void setKeyName(String keyName) { + this.keyName = keyName; + } + public String getKeyValue() { + return keyValue; + } + public void setKeyValue(String keyValue) { + this.keyValue = keyValue; + } + + + + +} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/data/ResponseKey.java b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/data/ResponseKey.java new file mode 100644 index 000000000..5277699e1 --- /dev/null +++ b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/data/ResponseKey.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.params.data; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ResponseKey{ + @JsonProperty("unique-key-name") + private String uniqueKeyName; + @JsonProperty("unique-key-value") + private String uniqueKeyValue; + @JsonProperty("field-key-name") + private String fieldKeyName; + + public String getUniqueKeyName() { + return uniqueKeyName; + } + public void setUniqueKeyName(String uniqueKeyName) { + this.uniqueKeyName = uniqueKeyName; + } + public String getUniqueKeyValue() { + return uniqueKeyValue; + } + public void setUniqueKeyValue(String uniqueKeyValue) { + this.uniqueKeyValue = uniqueKeyValue; + } + public String getFieldKeyName() { + return fieldKeyName; + } + public void setFieldKeyName(String fieldKeyName) { + this.fieldKeyName = fieldKeyName; + } + + +} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/parser/PropertyDefinitionNode.java b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/parser/PropertyDefinitionNode.java new file mode 100644 index 000000000..4916c46a8 --- /dev/null +++ b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/parser/PropertyDefinitionNode.java @@ -0,0 +1,251 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.params.parser; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdnc.config.params.ParamsHandlerConstant; +import org.openecomp.sdnc.config.params.data.Parameter; +import org.openecomp.sdnc.config.params.data.PropertyDefinition; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; + +public class PropertyDefinitionNode implements SvcLogicJavaPlugin{ + + + private static final EELFLogger log = EELFManager.getInstance().getLogger(PropertyDefinitionNode.class); + + public void processMissingParamKeys(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + log.info("Received processParamKeys call with params : " + inParams); + String responsePrefix = inParams.get(ParamsHandlerConstant.INPUT_PARAM_RESPONSE_PRIFIX); + try{ + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + + String requestParamJson = inParams.get(ParamsHandlerConstant.INPUT_PARAM_JSON_DATA); + String pdContent = inParams.get(ParamsHandlerConstant.INPUT_PARAM_PD_CONTENT); + + if(StringUtils.isBlank(pdContent)){ + throw new Exception("Request Param (pdContent) is Missing .."); + } + + if(StringUtils.isBlank(requestParamJson)){ + throw new Exception("Request Param (jsonData) is Missing .."); + } + + PropertyDefinition propertyDefinition = parsePDContent(pdContent); + if(propertyDefinition != null){ + requestParamJson = mergeMissingRequestParamFromPD(propertyDefinition, requestParamJson); + ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_CONFIGURATION_PARAMETER, requestParamJson); + } + + ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_STATUS, ParamsHandlerConstant.OUTPUT_STATUS_SUCCESS); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_STATUS, ParamsHandlerConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); + log.error("Failed in merging data to template " + e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + } + + public void processExternalSystemParamKeys(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + log.info("Received processExternalSystemParamKeys call with params : " + inParams); + String responsePrefix = inParams.get(ParamsHandlerConstant.INPUT_PARAM_RESPONSE_PRIFIX); + try{ + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + + String requestParamJson = inParams.get(ParamsHandlerConstant.INPUT_PARAM_JSON_DATA); + String pdContent = inParams.get(ParamsHandlerConstant.INPUT_PARAM_PD_CONTENT); + String systemName = inParams.get(ParamsHandlerConstant.INPUT_PARAM_SYSTEM_NAME); + + + if(StringUtils.isBlank(pdContent)){ + throw new Exception("Request Param (pdContent) is Missing .."); + } + + if(StringUtils.isBlank(requestParamJson)){ + throw new Exception("Request Param (jsonData) is Missing .."); + } + + if(StringUtils.isBlank(systemName)){ + throw new Exception("Request Param (systemName) is Missing .."); + } + + PropertyDefinition propertyDefinition = parsePDContent(pdContent); + if(propertyDefinition != null){ + getSystemRequestParamInfoFromPD(propertyDefinition, requestParamJson, systemName, ctx); + } + + ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_STATUS, ParamsHandlerConstant.OUTPUT_STATUS_SUCCESS); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_STATUS, ParamsHandlerConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); + log.error("Failed in merging data to template " + e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + } + + + public void mergeJsonData(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + log.info("Received mergeJsonData call with params : " + inParams); + String responsePrefix = inParams.get(ParamsHandlerConstant.INPUT_PARAM_RESPONSE_PRIFIX); + try{ + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + + String requestParamJson = inParams.get(ParamsHandlerConstant.INPUT_PARAM_JSON_DATA); + String mergeJsonData = inParams.get(ParamsHandlerConstant.INPUT_PARAM_MERGE__JSON_DATA); + + if(StringUtils.isBlank(requestParamJson)){ + throw new Exception("Request Param (jsonData) is Missing .."); + } + + if(StringUtils.isBlank(mergeJsonData)){ + throw new Exception("Request Param (mergeJsonData) is Missing .."); + } + + requestParamJson = mergeJson(requestParamJson, mergeJsonData); + ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_CONFIGURATION_PARAMETER, requestParamJson); + ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_STATUS, ParamsHandlerConstant.OUTPUT_STATUS_SUCCESS); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_STATUS, ParamsHandlerConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); + log.error("Failed in merging data to template " + e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + } + + + /* */ + + private PropertyDefinition parsePDContent(String pdContent) throws JsonParseException, JsonMappingException, IOException{ + PropertyDefinition propertyDefinition = null; + if(StringUtils.isNotBlank(pdContent)){ + ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); + propertyDefinition = mapper.readValue(pdContent, PropertyDefinition.class); + } + return propertyDefinition; + } + + + private String mergeMissingRequestParamFromPD(PropertyDefinition propertyDefinition, String requestParamJson) throws Exception{ + + if(propertyDefinition == null){ + throw new Exception("PropertyDefinition is Missing .."); + } + + if(StringUtils.isBlank(requestParamJson)){ + throw new Exception("Request Param is Missing .."); + } + + ObjectMapper mapper = new ObjectMapper(); + Map requestParamMap = mapper.readValue(requestParamJson, HashMap.class); + if(requestParamMap != null){ + List parameters = propertyDefinition.getParameters(); + for (Parameter parameter : parameters) { + if(parameter != null){ + + log.info("Checking Key " + parameter.getName() + ":: Source :" +parameter.getSource()); + // Add Only non external system keys,If it is not present in request Params + if( !requestParamMap.containsKey(parameter.getName()) + && StringUtils.isBlank(parameter.getSource()) + ){ + log.info("Adding New Key " + parameter.getName()); + requestParamMap.put(parameter.getName(), parameter.getDefaultValue()); + } + } + } + requestParamJson = mapper.writeValueAsString(requestParamMap); + log.info("Processed Request Param " + requestParamJson); + } + + return requestParamJson; + } + + private void getSystemRequestParamInfoFromPD(PropertyDefinition propertyDefinition, String requestParamJson, String systemName, SvcLogicContext ctx) throws Exception{ + + if(propertyDefinition == null){ + throw new Exception("PropertyDefinition is Missing .."); + } + + if(StringUtils.isBlank(requestParamJson)){ + throw new Exception("Request Param is Missing .."); + } + + ObjectMapper mapper = new ObjectMapper(); + Map requestParamMap = mapper.readValue(requestParamJson, HashMap.class); + if(requestParamMap != null){ + List parameters = propertyDefinition.getParameters(); + + List externalSystemKeys = new ArrayList(); + for (Parameter parameter : parameters) { + if(parameter != null){ + if( !requestParamMap.containsKey(parameter.getName()) && StringUtils.isNotBlank(parameter.getSource()) && !StringUtils.equalsIgnoreCase(parameter.getSource(),"Manual") ){ + log.info("Adding New System Key " + parameter.getName() + ":"+ mapper.writeValueAsString(parameter)); + externalSystemKeys.add(parameter.getName()); + ctx.setAttribute(systemName +"."+parameter.getName(), mapper.writeValueAsString(parameter)); + } + } + } + + String systemKeys = systemName+".keys"; + ctx.setAttribute(systemKeys, mapper.writeValueAsString(externalSystemKeys)); + } + } + + + private String mergeJson(String requestParamJson, String systemParamJson) throws Exception { + ObjectMapper mapper = new ObjectMapper(); + Map requestParamMap = mapper.readValue(requestParamJson, HashMap.class); + if(requestParamMap != null){ + Map systemParamMap = mapper.readValue(systemParamJson, HashMap.class); + if(systemParamMap != null){ + for (String systemParamKey : systemParamMap.keySet()) { + log.trace("Megging System Key Values " + systemParamKey); + requestParamMap.put( systemParamKey , systemParamMap.get(systemParamKey)); + } + } + requestParamJson = mapper.writeValueAsString(requestParamMap); + log.info("Processed Request Param " + requestParamJson); + } + + return requestParamJson; + } + + + + +} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/ArtificatTransformer.java b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/ArtificatTransformer.java new file mode 100644 index 000000000..8498b6375 --- /dev/null +++ b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/ArtificatTransformer.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.params.transformer; + +import java.io.IOException; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdnc.config.params.data.Parameter; +import org.openecomp.sdnc.config.params.data.PropertyDefinition; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; + +public class ArtificatTransformer { + + + public String convertPDToYaml(PropertyDefinition propertyDefinition) throws JsonParseException, JsonMappingException, IOException{ + String yamlContent = null; + if(propertyDefinition != null){ + ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); + mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); + yamlContent = mapper.writeValueAsString(propertyDefinition); + } + return yamlContent; + } + + public String transformYamlToJson(String yaml) throws JsonParseException, JsonMappingException, IOException { + ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory()); + Object obj = yamlReader.readValue(yaml, Object.class); + ObjectMapper jsonWriter = new ObjectMapper(); + jsonWriter.enable(SerializationFeature.INDENT_OUTPUT); + return jsonWriter.writeValueAsString(obj); + } + + public PropertyDefinition convertYAMLToPD(String pdContent) throws JsonParseException, JsonMappingException, IOException{ + PropertyDefinition propertyDefinition = null; + if(StringUtils.isNotBlank(pdContent)){ + ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); + propertyDefinition = mapper.readValue(pdContent, PropertyDefinition.class); + } + return propertyDefinition; + } + + public String convertYAMLToParams(String pdContent) throws JsonParseException, JsonMappingException, IOException{ + String paramJson = null; + if(StringUtils.isNotBlank(pdContent)){ + paramJson = convertPdToParams(convertYAMLToPD(pdContent)); + } + return paramJson; + } + + public String convertPdToParams(PropertyDefinition propertyDefinition) throws JsonParseException, JsonMappingException, IOException{ + String paramJson = null; + if(propertyDefinition != null && propertyDefinition.getParameters() != null){ + List parameters = propertyDefinition.getParameters(); + + } + return paramJson; + } + +} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/tosca/ArtifactProcessor.java b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/tosca/ArtifactProcessor.java new file mode 100644 index 000000000..cb4f1e0f7 --- /dev/null +++ b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/tosca/ArtifactProcessor.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.openecomp.sdnc.config.params.transformer.tosca; + +import org.openecomp.sdnc.config.params.data.PropertyDefinition; +import org.openecomp.sdnc.config.params.transformer.tosca.exceptions.ArtifactProcessorException; + +import java.io.OutputStream; + +public interface ArtifactProcessor +{ + /** + * Generates Tosca artifact from PropertyDefinition object. + * + * @param artifact + * PropertyDefinition object which is to be converted to Tosca. + * @param stream + * Stream to which the generated Tosca is to be written. + * @throws ArtifactProcessorException + * If the Tosca Generation failed + */ + void generateArtifact(PropertyDefinition artifact, OutputStream stream) throws ArtifactProcessorException; + + /** + * Generates Tosca artifact from PropertyDefinition string. + * + * @param artifact + * PropertyDefinition string which is to be converted to Tosca. + * @param stream + * Stream to which the generated Tosca is to be written. + * @throws ArtifactProcessorException + * If the Tosca Generation failed + */ + void generateArtifact(String artifact, OutputStream stream) throws ArtifactProcessorException; + + /** + * Generates the PropertyDefinition object from a Tosca artifact. + * + * @param toscaArtifact + * Tosca artifact which is to be converted. + * @return PropertyDefinition object generated from Tosca + * @throws ArtifactProcessorException + * If the PropertyDefinition Generation failed + */ + PropertyDefinition readArtifact(String toscaArtifact) throws ArtifactProcessorException; +} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/tosca/ArtifactProcessorFactory.java b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/tosca/ArtifactProcessorFactory.java new file mode 100644 index 000000000..9ec80c9a4 --- /dev/null +++ b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/tosca/ArtifactProcessorFactory.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.openecomp.sdnc.config.params.transformer.tosca; + +/** + * Created by pranavdi on 3/29/2017. + */ +public class ArtifactProcessorFactory +{ + private static class InstanceHolder + { + private static ArtifactProcessorImpl instance = new ArtifactProcessorImpl(); + } + + private ArtifactProcessorFactory(){} + + public static ArtifactProcessor getArtifactProcessor() + { + return InstanceHolder.instance; + } +} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/tosca/ArtifactProcessorImpl.java b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/tosca/ArtifactProcessorImpl.java new file mode 100644 index 000000000..e3dd5dc41 --- /dev/null +++ b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/tosca/ArtifactProcessorImpl.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.openecomp.sdnc.config.params.transformer.tosca; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import org.apache.commons.lang.StringUtils; + +import org.openecomp.sdc.tosca.datatypes.model.*; +import org.openecomp.sdc.tosca.services.YamlUtil; +import org.openecomp.sdnc.config.params.data.Parameter; +import org.openecomp.sdnc.config.params.data.PropertyDefinition; +import org.openecomp.sdnc.config.params.data.RequestKey; +import org.openecomp.sdnc.config.params.data.ResponseKey; +import org.openecomp.sdnc.config.params.transformer.tosca.exceptions.ArtifactProcessorException; +import org.slf4j.MDC; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; + +public class ArtifactProcessorImpl implements ArtifactProcessor +{ + private static final String DERIVEDFROM = "org.openecomp.genericvnf"; + private static final EELFLogger Log = EELFManager.getInstance().getLogger(ArtifactProcessorImpl.class); + private static final String EQUALSENCODING = "="; + private static final String COLONENCODING = ":"; + private static final String COMMAENCODING = ","; + private static final String GREATERTHANENCODING = ">"; + private static final String LESSTHANENCODING = "<"; + + @Override + public void generateArtifact(PropertyDefinition artifact, OutputStream stream) throws ArtifactProcessorException + { + MDC.clear(); + MDC.put(MDC_SERVICE_NAME,"ArtifactGenerator"); + Log.info("Entered into generateArtifact"); + if(!StringUtils.isBlank(artifact.getKind())) { + logArtifact(artifact); + ServiceTemplate serviceTemplate = new ServiceTemplate(); + + addNodeType(artifact, serviceTemplate); + + TopologyTemplate topologyTemplate = new TopologyTemplate(); + serviceTemplate.setTopology_template(topologyTemplate); + addNodeTemplate(artifact, serviceTemplate); + + String tosca = new YamlUtil().objectToYaml(serviceTemplate); + OutputStreamWriter writer = new OutputStreamWriter(stream); + try { + writer.write(tosca); + writer.flush(); + } catch (IOException e) { + Log.error("Error writing to outputstream", e); + throw new ArtifactProcessorException(e); + } finally { + try { + writer.close(); + } catch (IOException e) { + Log.error("Error while closing outputstream writer", e); + } + MDC.clear(); + } + } + else + { + Log.error("Kind in PropertyDefinition is blank or null"); + throw new ArtifactProcessorException("Kind in PropertyDefinition is blank or null"); + } + } + + @Override + public void generateArtifact(String artifact, OutputStream stream) throws ArtifactProcessorException + { + ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); + try { + PropertyDefinition pd = mapper.readValue(artifact, PropertyDefinition.class); + generateArtifact(pd, stream); + } + catch (IOException e) + { + Log.error("Error parsing property definition content = "+ artifact,e); + throw new ArtifactProcessorException(e); + } + } + + @Override + public PropertyDefinition readArtifact(String toscaArtifact) throws ArtifactProcessorException{ + Log.info("Entered into readArtifact."); + Log.info("Received ToscaArtifact:\n" + toscaArtifact); + + PropertyDefinition propertyDefinitionObj = new PropertyDefinition(); + ServiceTemplate serviceTemplate = new YamlUtil().yamlToObject(toscaArtifact, ServiceTemplate.class); + + //mapping parameters + Map nodeTypeMap = serviceTemplate.getNode_types(); + Map nodeTemplateMap = serviceTemplate.getTopology_template().getNode_templates(); + + String nodeTemplateName = nodeTemplateMap.keySet().toArray(new String[0])[0]; + NodeTemplate nodeTemplate = nodeTemplateMap.get(nodeTemplateName); + Map nodeTemplateProperties = nodeTemplate.getProperties(); + + String kind = nodeTypeMap.keySet().toArray(new String[0])[0]; + NodeType nodeType = nodeTypeMap.get(kind); + String version = nodeType.getVersion(); + Log.info("ReadArtifact for "+ kind + " with version "+version); + propertyDefinitionObj.setKind(kind); + propertyDefinitionObj.setVersion(version); + + List parameterList = new LinkedList<>(); + + Map propertyDefinitionFromTOSCA = nodeType.getProperties(); + if(null != propertyDefinitionFromTOSCA){ + for (String propertyName : propertyDefinitionFromTOSCA.keySet()) { + org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition propertyDefinition = propertyDefinitionFromTOSCA.get(propertyName); + + Parameter parameter = new Parameter(); + parameter.setName(propertyName); + + if (propertyDefinition.get_default() != null) { + parameter.setDefaultValue(propertyDefinition.get_default().toString()); + } + parameter.setDescription(propertyDefinition.getDescription()); + if (null != propertyDefinition.getRequired()) { + parameter.setRequired(propertyDefinition.getRequired()); + } else { + parameter.setRequired(false); + } + + if (StringUtils.isNotEmpty(propertyDefinition.getType())) { + parameter.setType(propertyDefinition.getType()); + } + + String propertValueExpr = (String) nodeTemplateProperties.get(propertyName); + String[] stringTokens = parsePropertyValueExpression(propertValueExpr); + String ruleType = stringTokens[0].substring(stringTokens[0].indexOf('=')+1,stringTokens[0].length()).replaceAll(">","").trim(); + String responseExpression = stringTokens[1].substring(stringTokens[1].indexOf('=')+1,stringTokens[1].length()); + String source = stringTokens[2].substring(stringTokens[2].indexOf('=')+1,stringTokens[2].length()).replaceAll(">","").trim(); + String requestExpression = stringTokens[3].substring(stringTokens[3].indexOf('=')+1,stringTokens[3].length()); + + List requestKeys = readRequestKeys(requestExpression); + List responseKeys = readResponseKeys(responseExpression); + + parameter.setRuleType(ruleType); + parameter.setSource(source); + parameter.setRequestKeys(requestKeys); + parameter.setResponseKeys(responseKeys); + + parameterList.add(parameter); + + } + } + propertyDefinitionObj.setParameters(parameterList); + Log.info("Exiting from readArtifact. "); + return propertyDefinitionObj; + } + + private List readResponseKeys(String responseExpression) throws ArtifactProcessorException { + Log.info("Entered into readResponseKeys."); + List responseKeyList = null; + String expression; + expression = responseExpression.replaceAll("<", "").replaceAll(">", "").trim(); + if (StringUtils.isNotEmpty(expression)) { + responseKeyList = new ArrayList<>(); + + String[] responseKeys = expression.split(","); + for (String responseKeyStr : responseKeys) { + ResponseKey responseKey = new ResponseKey(); + try { + responseKey.setUniqueKeyName(responseKeyStr.split(":")[0].replaceAll(LESSTHANENCODING, "<").replaceAll(GREATERTHANENCODING, ">").replaceAll(COLONENCODING, ":").replaceAll(COMMAENCODING, ",").replaceAll(EQUALSENCODING,"=").trim()); + responseKey.setUniqueKeyValue(responseKeyStr.split(":")[1].replaceAll(LESSTHANENCODING, "<").replaceAll(GREATERTHANENCODING, ">").replaceAll(COLONENCODING, ":").replaceAll(COMMAENCODING, ",").replaceAll(EQUALSENCODING,"=").trim()); + responseKey.setFieldKeyName(responseKeyStr.split(":")[2].replaceAll(LESSTHANENCODING, "<").replaceAll(GREATERTHANENCODING, ">").replaceAll(COLONENCODING, ":").replaceAll(COMMAENCODING, ",").replaceAll(EQUALSENCODING,"=").trim()); + } catch (ArrayIndexOutOfBoundsException e) { + Log.error("Invalid response attribute found :" + responseKeyStr + "due to "+e); + throw new ArtifactProcessorException("Invalid response attribute found :" + responseKeyStr); + } + responseKeyList.add(responseKey); + } + } + Log.info("Exiting from readResponseKeys."); + return responseKeyList; + } + + private List readRequestKeys(String requestExpression) { + Log.info("Entered into readRequestKeys."); + List requestKeyList = null; + String expression; + expression = requestExpression.replaceAll("<","").replaceAll(">","").trim(); + if(StringUtils.isNotEmpty(expression)){ + requestKeyList = new ArrayList<>(); + String[] requestKeys = expression.split(","); + for(String responseKeyStr :requestKeys){ + RequestKey requestKey = new RequestKey(); + requestKey.setKeyName(responseKeyStr.split(":")[0].replaceAll(LESSTHANENCODING, "<").replaceAll(GREATERTHANENCODING, ">").replaceAll(COLONENCODING,":").replaceAll(COMMAENCODING,",").replaceAll(EQUALSENCODING,"=").trim()); + requestKey.setKeyValue(responseKeyStr.split(":")[1].replaceAll(LESSTHANENCODING, "<").replaceAll(GREATERTHANENCODING, ">").replaceAll(COLONENCODING,":").replaceAll(COMMAENCODING,",").replaceAll(EQUALSENCODING,"=").trim()); + requestKeyList.add(requestKey); + } + } + Log.info("Exiting from readRequestKeys."); + return requestKeyList; + } + + private String[] parsePropertyValueExpression(String propertValueExpr) throws ArtifactProcessorException{ + Log.info("Entered into parsePropertyValueExpression."); + String nodeRegex = "<(.*?)>"; + Pattern pattern = Pattern.compile(nodeRegex, Pattern.CASE_INSENSITIVE); + Matcher matcher = pattern.matcher(propertValueExpr); + List stringTokens = new ArrayList<>(); + while(matcher.find()){ + stringTokens.add(matcher.group(0)); + } + String[] propertiesArr = new String[stringTokens.size()]; + propertiesArr = stringTokens.toArray(propertiesArr); + if(propertiesArr.length!=4){ + throw new ArtifactProcessorException("Invalid input found " + propertValueExpr); + } + Log.info("Exiting from parsePropertyValueExpression."); + return propertiesArr; + } + + private void addNodeType(PropertyDefinition artifact, ServiceTemplate toscaTemplate) throws ArtifactProcessorException { + //Add basic fields for the node + NodeType toscaNodeType = new NodeType(); + toscaNodeType.setDerived_from(DERIVEDFROM); + toscaNodeType.setVersion(artifact.getVersion()); + toscaNodeType.setDescription(""); + if(artifact.getParameters()!=null) { + Map toscaPropertyMap = new HashMap<>(); + toscaNodeType.setProperties(toscaPropertyMap); + + //Add properties from parameters of PD + for (Parameter pdParameter : artifact.getParameters()) { + addProperty(toscaNodeType, pdParameter); + } + } + + // This is where it adds node in node Map and adds the map in tosca template + Map toscaNodeMap = new HashMap<>(); + toscaNodeMap.put(artifact.getKind(),toscaNodeType); + toscaTemplate.setNode_types(toscaNodeMap); + } + + private void addProperty(NodeType toscaNodeType, Parameter pdParameter) throws ArtifactProcessorException { + if(!StringUtils.isBlank(pdParameter.getName())&& !pdParameter.getName().matches(".*\\s+.*")) { + Log.info("Adding parameter " + pdParameter.getName() + " in node type"); + org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition toscaProperty = new org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition(); + + toscaProperty.setType(StringUtils.isBlank(pdParameter.getType()) ? "string" : pdParameter.getType()); + toscaProperty.set_default(pdParameter.getDefaultValue()); + + toscaProperty.setDescription(pdParameter.getDescription()); + toscaProperty.setRequired(pdParameter.isRequired()); + + toscaNodeType.getProperties().put(pdParameter.getName(), toscaProperty); + } + else + { + String message ="Parameter name is empty,null or contains whitespace"; + Log.error(message); + throw new ArtifactProcessorException(message); + } + } + + private void addNodeTemplate(PropertyDefinition artifact, ServiceTemplate toscaTemplate) + { + NodeTemplate nodeTemplate = new NodeTemplate(); + nodeTemplate.setType(artifact.getKind()); + Map templateProperties = new HashMap<>(); + //Add properties from parameters of PD + if(artifact.getParameters()!=null) { + for (Parameter pdParameter : artifact.getParameters()) { + addTemplateProperty(templateProperties, pdParameter); + } + nodeTemplate.setProperties(templateProperties); + } + Map nodeTemplateMap = new HashMap<>(); + nodeTemplateMap.put(artifact.getKind()+"_Template",nodeTemplate); + toscaTemplate.getTopology_template().setNode_templates(nodeTemplateMap); + } + + private void addTemplateProperty(Map templateProperties, Parameter pdParameter) + { + Log.info("Adding parameter "+ pdParameter.getName() + " in node templates"); + String responseKeys = buildResponseKeyExpression(pdParameter.getResponseKeys()); + String requestKeys = buildRequestKeyExpression(pdParameter.getRequestKeys()); + String ruleType = buildRuleType(pdParameter.getRuleType()); + String source = buildSourceSystem(pdParameter.getSource()); + String properties = ruleType + " " + responseKeys + " " + source + " " + requestKeys; + templateProperties.put(pdParameter.getName(),properties); + } + + protected String buildResponseKeyExpression(List responseKeys) + { + StringBuilder propertyBuilder = new StringBuilder(); + propertyBuilder.append(" itr = responseKeys.iterator(); + while (itr.hasNext()) { + ResponseKey res = itr.next(); + if(res!=null) + propertyBuilder.append(encode(res.getUniqueKeyName()) + ":" + encode(res.getUniqueKeyValue()) + ":" + encode(res.getFieldKeyName())); + if (itr.hasNext()) + propertyBuilder.append(" , "); + } + } + propertyBuilder.append(">"); + return propertyBuilder.toString(); + } + + protected String buildRequestKeyExpression(List requestKeys) + { + StringBuilder propertyBuilder = new StringBuilder(); + propertyBuilder.append(" itr = requestKeys.iterator(); + while (itr.hasNext()) { + RequestKey res = itr.next(); + if(res!=null) + propertyBuilder.append(encode(res.getKeyName()) + ":" + encode(res.getKeyValue())); + if (itr.hasNext()) + propertyBuilder.append(" , "); + } + } + propertyBuilder.append(">"); + return propertyBuilder.toString(); + } + + protected String buildRuleType(String classType) + { + StringBuilder propertyBuilder = new StringBuilder(); + String encodedClassType = StringUtils.isBlank(encode(classType))?"":encode(classType); + propertyBuilder.append("<"); + propertyBuilder.append("rule-type = "+encodedClassType); + propertyBuilder.append(">"); + return propertyBuilder.toString(); + } + + protected String buildSourceSystem(String source) + { + StringBuilder sourceBuilder = new StringBuilder(); + sourceBuilder.append(""); + return sourceBuilder.toString(); + } + + protected String encode(String string) + { + String encodedString = null; + if(string!=null) { + encodedString = string.trim().replaceAll("<", "<").replaceAll(">", ">").replaceAll(":",":").replaceAll(",",",").replaceAll("=","="); + } + return encodedString; + } + + private void logArtifact(PropertyDefinition artifact) + { + ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); + String stringArtifact=null; + try + { + stringArtifact = mapper.writeValueAsString(artifact); + Log.info("Received PropertyDefinition:\n" + stringArtifact); + } + catch (JsonProcessingException e) + { + Log.error("Exception while logging artifact:",e); + } + + } +} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/tosca/exceptions/ArtifactProcessorException.java b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/tosca/exceptions/ArtifactProcessorException.java new file mode 100644 index 000000000..e788fbf88 --- /dev/null +++ b/appc-config/appc-config-params/provider/src/main/java/org/onap/sdnc/config/params/transformer/tosca/exceptions/ArtifactProcessorException.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.openecomp.sdnc.config.params.transformer.tosca.exceptions; + +/** + * Created by pranavdi on 3/17/2017. + */ +public class ArtifactProcessorException extends Exception +{ + public ArtifactProcessorException() {} + + public ArtifactProcessorException(String message) + { + super(message); + } + + public ArtifactProcessorException(Throwable cause) + { + super(cause); + } + + public ArtifactProcessorException(String message, Throwable cause) + { + super(message,cause); + } +} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/ParamsHandlerActivator.java b/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/ParamsHandlerActivator.java deleted file mode 100644 index dd4515cca..000000000 --- a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/ParamsHandlerActivator.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.params; - -import java.util.LinkedList; -import java.util.List; - -import org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class ParamsHandlerActivator implements BundleActivator{ - - private List registrations = new LinkedList(); - - - private static final EELFLogger log = EELFManager.getInstance().getLogger(ParamsHandlerActivator.class); - - @Override - public void start(BundleContext ctx) throws Exception - { - - try { - PropertyDefinitionNode propertyDefinitionNode = new PropertyDefinitionNode(); - log.info("Registering service "+ propertyDefinitionNode.getClass().getName()); - registrations.add(ctx.registerService(propertyDefinitionNode.getClass().getName(), propertyDefinitionNode, null)); - log.info("Registering service sccessful for "+ propertyDefinitionNode.getClass().getName()); - } catch (Exception e) { - e.printStackTrace(); - } - - } - @Override - public void stop(BundleContext arg0) throws Exception - { - for (ServiceRegistration registration: registrations) - { - registration.unregister(); - registration = null; - } - - } - -} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/ParamsHandlerConstant.java b/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/ParamsHandlerConstant.java deleted file mode 100644 index 65b93d738..000000000 --- a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/ParamsHandlerConstant.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.openecomp.sdnc.config.params; - -public class ParamsHandlerConstant { - - public static String STRING_ENCODING = "utf-8"; - public static String Y = "Y"; - public static String N = "N"; - public static String DATA_TYPE_TEXT = "TEXT"; - public static String DATA_TYPE_JSON = "JSON"; - public static String DATA_TYPE_XML = "XML"; - public static String DATA_TYPE_SQL = "SQL"; - - - public static String INPUT_PARAM_PD_CONTENT = "pdContent"; - public static String INPUT_PARAM_SYSTEM_NAME = "systemName"; - public static String INPUT_PARAM_JSON_DATA = "jsonData"; - public static String INPUT_PARAM_MERGE__JSON_DATA = "mergeJsonData"; - - - public static String INPUT_PARAM_REQUEST_DATA = "requestData"; - public static String INPUT_PARAM_RESPONSE_PRIFIX = "responsePrefix"; - public static String OUTPUT_PARAM_CONFIGURATION_PARAMETER = "configuration-parameters"; - - - - public static String OUTPUT_PARAM_STATUS = "status"; - public static String OUTPUT_PARAM_ERROR_MESSAGE = "error-message"; - public static String OUTPUT_STATUS_SUCCESS = "success"; - public static String OUTPUT_STATUS_FAILURE = "failure"; - -} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/data/Parameter.java b/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/data/Parameter.java deleted file mode 100644 index aaa457645..000000000 --- a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/data/Parameter.java +++ /dev/null @@ -1,126 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.params.data; - -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class Parameter { - private String name; - private String description; - private String type; - private boolean required; - private String source; - - @JsonProperty("rule-type") - private String ruleType; - - @JsonProperty("default") - private String defaultValue; - - @JsonProperty("request-keys") - private List requestKeys; - - @JsonProperty("response-keys") - private List responseKeys; - - 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 String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public boolean isRequired() { - return required; - } - - public void setRequired(boolean required) { - this.required = required; - } - - public String getSource() { - return source; - } - - public void setSource(String source) { - this.source = source; - } - - public String getRuleType() { - return ruleType; - } - - public void setRuleType(String ruleType) { - this.ruleType = ruleType; - } - - public String getDefaultValue() { - return defaultValue; - } - - public void setDefaultValue(String defaultValue) { - this.defaultValue = defaultValue; - } - - public List getRequestKeys() { - return requestKeys; - } - - public void setRequestKeys(List requestKeys) { - this.requestKeys = requestKeys; - } - - public List getResponseKeys() { - return responseKeys; - } - - public void setResponseKeys(List responseKeys) { - this.responseKeys = responseKeys; - } - - - - - -} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/data/PropertyDefinition.java b/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/data/PropertyDefinition.java deleted file mode 100644 index d33fd9589..000000000 --- a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/data/PropertyDefinition.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.params.data; - -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class PropertyDefinition { - public String kind = "Property Definition"; - public String version = "V1"; - - @JsonProperty("vnf-parameter-list") - public List parameters; - public String getKind() { - return kind; - } - public void setKind(String kind) { - this.kind = kind; - } - public String getVersion() { - return version; - } - public void setVersion(String version) { - this.version = version; - } - public List getParameters() { - return parameters; - } - public void setParameters(List parameters) { - this.parameters = parameters; - } - -} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/data/RequestKey.java b/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/data/RequestKey.java deleted file mode 100644 index 0589afcc3..000000000 --- a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/data/RequestKey.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.openecomp.sdnc.config.params.data; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class RequestKey{ - @JsonProperty("key-name") - private String keyName; - @JsonProperty("key-value") - private String keyValue; - - public String getKeyName() { - return keyName; - } - public void setKeyName(String keyName) { - this.keyName = keyName; - } - public String getKeyValue() { - return keyValue; - } - public void setKeyValue(String keyValue) { - this.keyValue = keyValue; - } - - - - -} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/data/ResponseKey.java b/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/data/ResponseKey.java deleted file mode 100644 index 5277699e1..000000000 --- a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/data/ResponseKey.java +++ /dev/null @@ -1,57 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.params.data; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class ResponseKey{ - @JsonProperty("unique-key-name") - private String uniqueKeyName; - @JsonProperty("unique-key-value") - private String uniqueKeyValue; - @JsonProperty("field-key-name") - private String fieldKeyName; - - public String getUniqueKeyName() { - return uniqueKeyName; - } - public void setUniqueKeyName(String uniqueKeyName) { - this.uniqueKeyName = uniqueKeyName; - } - public String getUniqueKeyValue() { - return uniqueKeyValue; - } - public void setUniqueKeyValue(String uniqueKeyValue) { - this.uniqueKeyValue = uniqueKeyValue; - } - public String getFieldKeyName() { - return fieldKeyName; - } - public void setFieldKeyName(String fieldKeyName) { - this.fieldKeyName = fieldKeyName; - } - - -} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/parser/PropertyDefinitionNode.java b/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/parser/PropertyDefinitionNode.java deleted file mode 100644 index 4916c46a8..000000000 --- a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/parser/PropertyDefinitionNode.java +++ /dev/null @@ -1,251 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.params.parser; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdnc.config.params.ParamsHandlerConstant; -import org.openecomp.sdnc.config.params.data.Parameter; -import org.openecomp.sdnc.config.params.data.PropertyDefinition; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; - -public class PropertyDefinitionNode implements SvcLogicJavaPlugin{ - - - private static final EELFLogger log = EELFManager.getInstance().getLogger(PropertyDefinitionNode.class); - - public void processMissingParamKeys(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - log.info("Received processParamKeys call with params : " + inParams); - String responsePrefix = inParams.get(ParamsHandlerConstant.INPUT_PARAM_RESPONSE_PRIFIX); - try{ - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - - String requestParamJson = inParams.get(ParamsHandlerConstant.INPUT_PARAM_JSON_DATA); - String pdContent = inParams.get(ParamsHandlerConstant.INPUT_PARAM_PD_CONTENT); - - if(StringUtils.isBlank(pdContent)){ - throw new Exception("Request Param (pdContent) is Missing .."); - } - - if(StringUtils.isBlank(requestParamJson)){ - throw new Exception("Request Param (jsonData) is Missing .."); - } - - PropertyDefinition propertyDefinition = parsePDContent(pdContent); - if(propertyDefinition != null){ - requestParamJson = mergeMissingRequestParamFromPD(propertyDefinition, requestParamJson); - ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_CONFIGURATION_PARAMETER, requestParamJson); - } - - ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_STATUS, ParamsHandlerConstant.OUTPUT_STATUS_SUCCESS); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_STATUS, ParamsHandlerConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); - log.error("Failed in merging data to template " + e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - } - - public void processExternalSystemParamKeys(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - log.info("Received processExternalSystemParamKeys call with params : " + inParams); - String responsePrefix = inParams.get(ParamsHandlerConstant.INPUT_PARAM_RESPONSE_PRIFIX); - try{ - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - - String requestParamJson = inParams.get(ParamsHandlerConstant.INPUT_PARAM_JSON_DATA); - String pdContent = inParams.get(ParamsHandlerConstant.INPUT_PARAM_PD_CONTENT); - String systemName = inParams.get(ParamsHandlerConstant.INPUT_PARAM_SYSTEM_NAME); - - - if(StringUtils.isBlank(pdContent)){ - throw new Exception("Request Param (pdContent) is Missing .."); - } - - if(StringUtils.isBlank(requestParamJson)){ - throw new Exception("Request Param (jsonData) is Missing .."); - } - - if(StringUtils.isBlank(systemName)){ - throw new Exception("Request Param (systemName) is Missing .."); - } - - PropertyDefinition propertyDefinition = parsePDContent(pdContent); - if(propertyDefinition != null){ - getSystemRequestParamInfoFromPD(propertyDefinition, requestParamJson, systemName, ctx); - } - - ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_STATUS, ParamsHandlerConstant.OUTPUT_STATUS_SUCCESS); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_STATUS, ParamsHandlerConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); - log.error("Failed in merging data to template " + e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - } - - - public void mergeJsonData(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - log.info("Received mergeJsonData call with params : " + inParams); - String responsePrefix = inParams.get(ParamsHandlerConstant.INPUT_PARAM_RESPONSE_PRIFIX); - try{ - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - - String requestParamJson = inParams.get(ParamsHandlerConstant.INPUT_PARAM_JSON_DATA); - String mergeJsonData = inParams.get(ParamsHandlerConstant.INPUT_PARAM_MERGE__JSON_DATA); - - if(StringUtils.isBlank(requestParamJson)){ - throw new Exception("Request Param (jsonData) is Missing .."); - } - - if(StringUtils.isBlank(mergeJsonData)){ - throw new Exception("Request Param (mergeJsonData) is Missing .."); - } - - requestParamJson = mergeJson(requestParamJson, mergeJsonData); - ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_CONFIGURATION_PARAMETER, requestParamJson); - ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_STATUS, ParamsHandlerConstant.OUTPUT_STATUS_SUCCESS); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_STATUS, ParamsHandlerConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + ParamsHandlerConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); - log.error("Failed in merging data to template " + e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - } - - - /* */ - - private PropertyDefinition parsePDContent(String pdContent) throws JsonParseException, JsonMappingException, IOException{ - PropertyDefinition propertyDefinition = null; - if(StringUtils.isNotBlank(pdContent)){ - ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); - propertyDefinition = mapper.readValue(pdContent, PropertyDefinition.class); - } - return propertyDefinition; - } - - - private String mergeMissingRequestParamFromPD(PropertyDefinition propertyDefinition, String requestParamJson) throws Exception{ - - if(propertyDefinition == null){ - throw new Exception("PropertyDefinition is Missing .."); - } - - if(StringUtils.isBlank(requestParamJson)){ - throw new Exception("Request Param is Missing .."); - } - - ObjectMapper mapper = new ObjectMapper(); - Map requestParamMap = mapper.readValue(requestParamJson, HashMap.class); - if(requestParamMap != null){ - List parameters = propertyDefinition.getParameters(); - for (Parameter parameter : parameters) { - if(parameter != null){ - - log.info("Checking Key " + parameter.getName() + ":: Source :" +parameter.getSource()); - // Add Only non external system keys,If it is not present in request Params - if( !requestParamMap.containsKey(parameter.getName()) - && StringUtils.isBlank(parameter.getSource()) - ){ - log.info("Adding New Key " + parameter.getName()); - requestParamMap.put(parameter.getName(), parameter.getDefaultValue()); - } - } - } - requestParamJson = mapper.writeValueAsString(requestParamMap); - log.info("Processed Request Param " + requestParamJson); - } - - return requestParamJson; - } - - private void getSystemRequestParamInfoFromPD(PropertyDefinition propertyDefinition, String requestParamJson, String systemName, SvcLogicContext ctx) throws Exception{ - - if(propertyDefinition == null){ - throw new Exception("PropertyDefinition is Missing .."); - } - - if(StringUtils.isBlank(requestParamJson)){ - throw new Exception("Request Param is Missing .."); - } - - ObjectMapper mapper = new ObjectMapper(); - Map requestParamMap = mapper.readValue(requestParamJson, HashMap.class); - if(requestParamMap != null){ - List parameters = propertyDefinition.getParameters(); - - List externalSystemKeys = new ArrayList(); - for (Parameter parameter : parameters) { - if(parameter != null){ - if( !requestParamMap.containsKey(parameter.getName()) && StringUtils.isNotBlank(parameter.getSource()) && !StringUtils.equalsIgnoreCase(parameter.getSource(),"Manual") ){ - log.info("Adding New System Key " + parameter.getName() + ":"+ mapper.writeValueAsString(parameter)); - externalSystemKeys.add(parameter.getName()); - ctx.setAttribute(systemName +"."+parameter.getName(), mapper.writeValueAsString(parameter)); - } - } - } - - String systemKeys = systemName+".keys"; - ctx.setAttribute(systemKeys, mapper.writeValueAsString(externalSystemKeys)); - } - } - - - private String mergeJson(String requestParamJson, String systemParamJson) throws Exception { - ObjectMapper mapper = new ObjectMapper(); - Map requestParamMap = mapper.readValue(requestParamJson, HashMap.class); - if(requestParamMap != null){ - Map systemParamMap = mapper.readValue(systemParamJson, HashMap.class); - if(systemParamMap != null){ - for (String systemParamKey : systemParamMap.keySet()) { - log.trace("Megging System Key Values " + systemParamKey); - requestParamMap.put( systemParamKey , systemParamMap.get(systemParamKey)); - } - } - requestParamJson = mapper.writeValueAsString(requestParamMap); - log.info("Processed Request Param " + requestParamJson); - } - - return requestParamJson; - } - - - - -} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/ArtificatTransformer.java b/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/ArtificatTransformer.java deleted file mode 100644 index 8498b6375..000000000 --- a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/ArtificatTransformer.java +++ /dev/null @@ -1,87 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.params.transformer; - -import java.io.IOException; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdnc.config.params.data.Parameter; -import org.openecomp.sdnc.config.params.data.PropertyDefinition; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; - -public class ArtificatTransformer { - - - public String convertPDToYaml(PropertyDefinition propertyDefinition) throws JsonParseException, JsonMappingException, IOException{ - String yamlContent = null; - if(propertyDefinition != null){ - ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); - mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); - yamlContent = mapper.writeValueAsString(propertyDefinition); - } - return yamlContent; - } - - public String transformYamlToJson(String yaml) throws JsonParseException, JsonMappingException, IOException { - ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory()); - Object obj = yamlReader.readValue(yaml, Object.class); - ObjectMapper jsonWriter = new ObjectMapper(); - jsonWriter.enable(SerializationFeature.INDENT_OUTPUT); - return jsonWriter.writeValueAsString(obj); - } - - public PropertyDefinition convertYAMLToPD(String pdContent) throws JsonParseException, JsonMappingException, IOException{ - PropertyDefinition propertyDefinition = null; - if(StringUtils.isNotBlank(pdContent)){ - ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); - propertyDefinition = mapper.readValue(pdContent, PropertyDefinition.class); - } - return propertyDefinition; - } - - public String convertYAMLToParams(String pdContent) throws JsonParseException, JsonMappingException, IOException{ - String paramJson = null; - if(StringUtils.isNotBlank(pdContent)){ - paramJson = convertPdToParams(convertYAMLToPD(pdContent)); - } - return paramJson; - } - - public String convertPdToParams(PropertyDefinition propertyDefinition) throws JsonParseException, JsonMappingException, IOException{ - String paramJson = null; - if(propertyDefinition != null && propertyDefinition.getParameters() != null){ - List parameters = propertyDefinition.getParameters(); - - } - return paramJson; - } - -} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/tosca/ArtifactProcessor.java b/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/tosca/ArtifactProcessor.java deleted file mode 100644 index cb4f1e0f7..000000000 --- a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/tosca/ArtifactProcessor.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.openecomp.sdnc.config.params.transformer.tosca; - -import org.openecomp.sdnc.config.params.data.PropertyDefinition; -import org.openecomp.sdnc.config.params.transformer.tosca.exceptions.ArtifactProcessorException; - -import java.io.OutputStream; - -public interface ArtifactProcessor -{ - /** - * Generates Tosca artifact from PropertyDefinition object. - * - * @param artifact - * PropertyDefinition object which is to be converted to Tosca. - * @param stream - * Stream to which the generated Tosca is to be written. - * @throws ArtifactProcessorException - * If the Tosca Generation failed - */ - void generateArtifact(PropertyDefinition artifact, OutputStream stream) throws ArtifactProcessorException; - - /** - * Generates Tosca artifact from PropertyDefinition string. - * - * @param artifact - * PropertyDefinition string which is to be converted to Tosca. - * @param stream - * Stream to which the generated Tosca is to be written. - * @throws ArtifactProcessorException - * If the Tosca Generation failed - */ - void generateArtifact(String artifact, OutputStream stream) throws ArtifactProcessorException; - - /** - * Generates the PropertyDefinition object from a Tosca artifact. - * - * @param toscaArtifact - * Tosca artifact which is to be converted. - * @return PropertyDefinition object generated from Tosca - * @throws ArtifactProcessorException - * If the PropertyDefinition Generation failed - */ - PropertyDefinition readArtifact(String toscaArtifact) throws ArtifactProcessorException; -} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/tosca/ArtifactProcessorFactory.java b/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/tosca/ArtifactProcessorFactory.java deleted file mode 100644 index 9ec80c9a4..000000000 --- a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/tosca/ArtifactProcessorFactory.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.openecomp.sdnc.config.params.transformer.tosca; - -/** - * Created by pranavdi on 3/29/2017. - */ -public class ArtifactProcessorFactory -{ - private static class InstanceHolder - { - private static ArtifactProcessorImpl instance = new ArtifactProcessorImpl(); - } - - private ArtifactProcessorFactory(){} - - public static ArtifactProcessor getArtifactProcessor() - { - return InstanceHolder.instance; - } -} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/tosca/ArtifactProcessorImpl.java b/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/tosca/ArtifactProcessorImpl.java deleted file mode 100644 index e3dd5dc41..000000000 --- a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/tosca/ArtifactProcessorImpl.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.openecomp.sdnc.config.params.transformer.tosca; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; -import org.apache.commons.lang.StringUtils; - -import org.openecomp.sdc.tosca.datatypes.model.*; -import org.openecomp.sdc.tosca.services.YamlUtil; -import org.openecomp.sdnc.config.params.data.Parameter; -import org.openecomp.sdnc.config.params.data.PropertyDefinition; -import org.openecomp.sdnc.config.params.data.RequestKey; -import org.openecomp.sdnc.config.params.data.ResponseKey; -import org.openecomp.sdnc.config.params.transformer.tosca.exceptions.ArtifactProcessorException; -import org.slf4j.MDC; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; - -public class ArtifactProcessorImpl implements ArtifactProcessor -{ - private static final String DERIVEDFROM = "org.openecomp.genericvnf"; - private static final EELFLogger Log = EELFManager.getInstance().getLogger(ArtifactProcessorImpl.class); - private static final String EQUALSENCODING = "="; - private static final String COLONENCODING = ":"; - private static final String COMMAENCODING = ","; - private static final String GREATERTHANENCODING = ">"; - private static final String LESSTHANENCODING = "<"; - - @Override - public void generateArtifact(PropertyDefinition artifact, OutputStream stream) throws ArtifactProcessorException - { - MDC.clear(); - MDC.put(MDC_SERVICE_NAME,"ArtifactGenerator"); - Log.info("Entered into generateArtifact"); - if(!StringUtils.isBlank(artifact.getKind())) { - logArtifact(artifact); - ServiceTemplate serviceTemplate = new ServiceTemplate(); - - addNodeType(artifact, serviceTemplate); - - TopologyTemplate topologyTemplate = new TopologyTemplate(); - serviceTemplate.setTopology_template(topologyTemplate); - addNodeTemplate(artifact, serviceTemplate); - - String tosca = new YamlUtil().objectToYaml(serviceTemplate); - OutputStreamWriter writer = new OutputStreamWriter(stream); - try { - writer.write(tosca); - writer.flush(); - } catch (IOException e) { - Log.error("Error writing to outputstream", e); - throw new ArtifactProcessorException(e); - } finally { - try { - writer.close(); - } catch (IOException e) { - Log.error("Error while closing outputstream writer", e); - } - MDC.clear(); - } - } - else - { - Log.error("Kind in PropertyDefinition is blank or null"); - throw new ArtifactProcessorException("Kind in PropertyDefinition is blank or null"); - } - } - - @Override - public void generateArtifact(String artifact, OutputStream stream) throws ArtifactProcessorException - { - ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); - try { - PropertyDefinition pd = mapper.readValue(artifact, PropertyDefinition.class); - generateArtifact(pd, stream); - } - catch (IOException e) - { - Log.error("Error parsing property definition content = "+ artifact,e); - throw new ArtifactProcessorException(e); - } - } - - @Override - public PropertyDefinition readArtifact(String toscaArtifact) throws ArtifactProcessorException{ - Log.info("Entered into readArtifact."); - Log.info("Received ToscaArtifact:\n" + toscaArtifact); - - PropertyDefinition propertyDefinitionObj = new PropertyDefinition(); - ServiceTemplate serviceTemplate = new YamlUtil().yamlToObject(toscaArtifact, ServiceTemplate.class); - - //mapping parameters - Map nodeTypeMap = serviceTemplate.getNode_types(); - Map nodeTemplateMap = serviceTemplate.getTopology_template().getNode_templates(); - - String nodeTemplateName = nodeTemplateMap.keySet().toArray(new String[0])[0]; - NodeTemplate nodeTemplate = nodeTemplateMap.get(nodeTemplateName); - Map nodeTemplateProperties = nodeTemplate.getProperties(); - - String kind = nodeTypeMap.keySet().toArray(new String[0])[0]; - NodeType nodeType = nodeTypeMap.get(kind); - String version = nodeType.getVersion(); - Log.info("ReadArtifact for "+ kind + " with version "+version); - propertyDefinitionObj.setKind(kind); - propertyDefinitionObj.setVersion(version); - - List parameterList = new LinkedList<>(); - - Map propertyDefinitionFromTOSCA = nodeType.getProperties(); - if(null != propertyDefinitionFromTOSCA){ - for (String propertyName : propertyDefinitionFromTOSCA.keySet()) { - org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition propertyDefinition = propertyDefinitionFromTOSCA.get(propertyName); - - Parameter parameter = new Parameter(); - parameter.setName(propertyName); - - if (propertyDefinition.get_default() != null) { - parameter.setDefaultValue(propertyDefinition.get_default().toString()); - } - parameter.setDescription(propertyDefinition.getDescription()); - if (null != propertyDefinition.getRequired()) { - parameter.setRequired(propertyDefinition.getRequired()); - } else { - parameter.setRequired(false); - } - - if (StringUtils.isNotEmpty(propertyDefinition.getType())) { - parameter.setType(propertyDefinition.getType()); - } - - String propertValueExpr = (String) nodeTemplateProperties.get(propertyName); - String[] stringTokens = parsePropertyValueExpression(propertValueExpr); - String ruleType = stringTokens[0].substring(stringTokens[0].indexOf('=')+1,stringTokens[0].length()).replaceAll(">","").trim(); - String responseExpression = stringTokens[1].substring(stringTokens[1].indexOf('=')+1,stringTokens[1].length()); - String source = stringTokens[2].substring(stringTokens[2].indexOf('=')+1,stringTokens[2].length()).replaceAll(">","").trim(); - String requestExpression = stringTokens[3].substring(stringTokens[3].indexOf('=')+1,stringTokens[3].length()); - - List requestKeys = readRequestKeys(requestExpression); - List responseKeys = readResponseKeys(responseExpression); - - parameter.setRuleType(ruleType); - parameter.setSource(source); - parameter.setRequestKeys(requestKeys); - parameter.setResponseKeys(responseKeys); - - parameterList.add(parameter); - - } - } - propertyDefinitionObj.setParameters(parameterList); - Log.info("Exiting from readArtifact. "); - return propertyDefinitionObj; - } - - private List readResponseKeys(String responseExpression) throws ArtifactProcessorException { - Log.info("Entered into readResponseKeys."); - List responseKeyList = null; - String expression; - expression = responseExpression.replaceAll("<", "").replaceAll(">", "").trim(); - if (StringUtils.isNotEmpty(expression)) { - responseKeyList = new ArrayList<>(); - - String[] responseKeys = expression.split(","); - for (String responseKeyStr : responseKeys) { - ResponseKey responseKey = new ResponseKey(); - try { - responseKey.setUniqueKeyName(responseKeyStr.split(":")[0].replaceAll(LESSTHANENCODING, "<").replaceAll(GREATERTHANENCODING, ">").replaceAll(COLONENCODING, ":").replaceAll(COMMAENCODING, ",").replaceAll(EQUALSENCODING,"=").trim()); - responseKey.setUniqueKeyValue(responseKeyStr.split(":")[1].replaceAll(LESSTHANENCODING, "<").replaceAll(GREATERTHANENCODING, ">").replaceAll(COLONENCODING, ":").replaceAll(COMMAENCODING, ",").replaceAll(EQUALSENCODING,"=").trim()); - responseKey.setFieldKeyName(responseKeyStr.split(":")[2].replaceAll(LESSTHANENCODING, "<").replaceAll(GREATERTHANENCODING, ">").replaceAll(COLONENCODING, ":").replaceAll(COMMAENCODING, ",").replaceAll(EQUALSENCODING,"=").trim()); - } catch (ArrayIndexOutOfBoundsException e) { - Log.error("Invalid response attribute found :" + responseKeyStr + "due to "+e); - throw new ArtifactProcessorException("Invalid response attribute found :" + responseKeyStr); - } - responseKeyList.add(responseKey); - } - } - Log.info("Exiting from readResponseKeys."); - return responseKeyList; - } - - private List readRequestKeys(String requestExpression) { - Log.info("Entered into readRequestKeys."); - List requestKeyList = null; - String expression; - expression = requestExpression.replaceAll("<","").replaceAll(">","").trim(); - if(StringUtils.isNotEmpty(expression)){ - requestKeyList = new ArrayList<>(); - String[] requestKeys = expression.split(","); - for(String responseKeyStr :requestKeys){ - RequestKey requestKey = new RequestKey(); - requestKey.setKeyName(responseKeyStr.split(":")[0].replaceAll(LESSTHANENCODING, "<").replaceAll(GREATERTHANENCODING, ">").replaceAll(COLONENCODING,":").replaceAll(COMMAENCODING,",").replaceAll(EQUALSENCODING,"=").trim()); - requestKey.setKeyValue(responseKeyStr.split(":")[1].replaceAll(LESSTHANENCODING, "<").replaceAll(GREATERTHANENCODING, ">").replaceAll(COLONENCODING,":").replaceAll(COMMAENCODING,",").replaceAll(EQUALSENCODING,"=").trim()); - requestKeyList.add(requestKey); - } - } - Log.info("Exiting from readRequestKeys."); - return requestKeyList; - } - - private String[] parsePropertyValueExpression(String propertValueExpr) throws ArtifactProcessorException{ - Log.info("Entered into parsePropertyValueExpression."); - String nodeRegex = "<(.*?)>"; - Pattern pattern = Pattern.compile(nodeRegex, Pattern.CASE_INSENSITIVE); - Matcher matcher = pattern.matcher(propertValueExpr); - List stringTokens = new ArrayList<>(); - while(matcher.find()){ - stringTokens.add(matcher.group(0)); - } - String[] propertiesArr = new String[stringTokens.size()]; - propertiesArr = stringTokens.toArray(propertiesArr); - if(propertiesArr.length!=4){ - throw new ArtifactProcessorException("Invalid input found " + propertValueExpr); - } - Log.info("Exiting from parsePropertyValueExpression."); - return propertiesArr; - } - - private void addNodeType(PropertyDefinition artifact, ServiceTemplate toscaTemplate) throws ArtifactProcessorException { - //Add basic fields for the node - NodeType toscaNodeType = new NodeType(); - toscaNodeType.setDerived_from(DERIVEDFROM); - toscaNodeType.setVersion(artifact.getVersion()); - toscaNodeType.setDescription(""); - if(artifact.getParameters()!=null) { - Map toscaPropertyMap = new HashMap<>(); - toscaNodeType.setProperties(toscaPropertyMap); - - //Add properties from parameters of PD - for (Parameter pdParameter : artifact.getParameters()) { - addProperty(toscaNodeType, pdParameter); - } - } - - // This is where it adds node in node Map and adds the map in tosca template - Map toscaNodeMap = new HashMap<>(); - toscaNodeMap.put(artifact.getKind(),toscaNodeType); - toscaTemplate.setNode_types(toscaNodeMap); - } - - private void addProperty(NodeType toscaNodeType, Parameter pdParameter) throws ArtifactProcessorException { - if(!StringUtils.isBlank(pdParameter.getName())&& !pdParameter.getName().matches(".*\\s+.*")) { - Log.info("Adding parameter " + pdParameter.getName() + " in node type"); - org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition toscaProperty = new org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition(); - - toscaProperty.setType(StringUtils.isBlank(pdParameter.getType()) ? "string" : pdParameter.getType()); - toscaProperty.set_default(pdParameter.getDefaultValue()); - - toscaProperty.setDescription(pdParameter.getDescription()); - toscaProperty.setRequired(pdParameter.isRequired()); - - toscaNodeType.getProperties().put(pdParameter.getName(), toscaProperty); - } - else - { - String message ="Parameter name is empty,null or contains whitespace"; - Log.error(message); - throw new ArtifactProcessorException(message); - } - } - - private void addNodeTemplate(PropertyDefinition artifact, ServiceTemplate toscaTemplate) - { - NodeTemplate nodeTemplate = new NodeTemplate(); - nodeTemplate.setType(artifact.getKind()); - Map templateProperties = new HashMap<>(); - //Add properties from parameters of PD - if(artifact.getParameters()!=null) { - for (Parameter pdParameter : artifact.getParameters()) { - addTemplateProperty(templateProperties, pdParameter); - } - nodeTemplate.setProperties(templateProperties); - } - Map nodeTemplateMap = new HashMap<>(); - nodeTemplateMap.put(artifact.getKind()+"_Template",nodeTemplate); - toscaTemplate.getTopology_template().setNode_templates(nodeTemplateMap); - } - - private void addTemplateProperty(Map templateProperties, Parameter pdParameter) - { - Log.info("Adding parameter "+ pdParameter.getName() + " in node templates"); - String responseKeys = buildResponseKeyExpression(pdParameter.getResponseKeys()); - String requestKeys = buildRequestKeyExpression(pdParameter.getRequestKeys()); - String ruleType = buildRuleType(pdParameter.getRuleType()); - String source = buildSourceSystem(pdParameter.getSource()); - String properties = ruleType + " " + responseKeys + " " + source + " " + requestKeys; - templateProperties.put(pdParameter.getName(),properties); - } - - protected String buildResponseKeyExpression(List responseKeys) - { - StringBuilder propertyBuilder = new StringBuilder(); - propertyBuilder.append(" itr = responseKeys.iterator(); - while (itr.hasNext()) { - ResponseKey res = itr.next(); - if(res!=null) - propertyBuilder.append(encode(res.getUniqueKeyName()) + ":" + encode(res.getUniqueKeyValue()) + ":" + encode(res.getFieldKeyName())); - if (itr.hasNext()) - propertyBuilder.append(" , "); - } - } - propertyBuilder.append(">"); - return propertyBuilder.toString(); - } - - protected String buildRequestKeyExpression(List requestKeys) - { - StringBuilder propertyBuilder = new StringBuilder(); - propertyBuilder.append(" itr = requestKeys.iterator(); - while (itr.hasNext()) { - RequestKey res = itr.next(); - if(res!=null) - propertyBuilder.append(encode(res.getKeyName()) + ":" + encode(res.getKeyValue())); - if (itr.hasNext()) - propertyBuilder.append(" , "); - } - } - propertyBuilder.append(">"); - return propertyBuilder.toString(); - } - - protected String buildRuleType(String classType) - { - StringBuilder propertyBuilder = new StringBuilder(); - String encodedClassType = StringUtils.isBlank(encode(classType))?"":encode(classType); - propertyBuilder.append("<"); - propertyBuilder.append("rule-type = "+encodedClassType); - propertyBuilder.append(">"); - return propertyBuilder.toString(); - } - - protected String buildSourceSystem(String source) - { - StringBuilder sourceBuilder = new StringBuilder(); - sourceBuilder.append(""); - return sourceBuilder.toString(); - } - - protected String encode(String string) - { - String encodedString = null; - if(string!=null) { - encodedString = string.trim().replaceAll("<", "<").replaceAll(">", ">").replaceAll(":",":").replaceAll(",",",").replaceAll("=","="); - } - return encodedString; - } - - private void logArtifact(PropertyDefinition artifact) - { - ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); - String stringArtifact=null; - try - { - stringArtifact = mapper.writeValueAsString(artifact); - Log.info("Received PropertyDefinition:\n" + stringArtifact); - } - catch (JsonProcessingException e) - { - Log.error("Exception while logging artifact:",e); - } - - } -} diff --git a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/tosca/exceptions/ArtifactProcessorException.java b/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/tosca/exceptions/ArtifactProcessorException.java deleted file mode 100644 index e788fbf88..000000000 --- a/appc-config/appc-config-params/provider/src/main/java/org/openecomp/sdnc/config/params/transformer/tosca/exceptions/ArtifactProcessorException.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.openecomp.sdnc.config.params.transformer.tosca.exceptions; - -/** - * Created by pranavdi on 3/17/2017. - */ -public class ArtifactProcessorException extends Exception -{ - public ArtifactProcessorException() {} - - public ArtifactProcessorException(String message) - { - super(message); - } - - public ArtifactProcessorException(Throwable cause) - { - super(cause); - } - - public ArtifactProcessorException(String message, Throwable cause) - { - super(message,cause); - } -} diff --git a/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/parser/TestPropertyDefinitionNode.java b/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/parser/TestPropertyDefinitionNode.java new file mode 100644 index 000000000..be11384c4 --- /dev/null +++ b/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/parser/TestPropertyDefinitionNode.java @@ -0,0 +1,116 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.params.parser; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.io.IOUtils; +import org.junit.Test; +import org.junit.Ignore; +import org.openecomp.sdnc.config.params.ParamsHandlerConstant; +import org.openecomp.sdnc.config.params.data.PropertyDefinition; +import org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode; +import org.openecomp.sdnc.config.params.transformer.ArtificatTransformer; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class TestPropertyDefinitionNode { + + @Ignore + public void testProcessMissingParamKeys() throws Exception { + PropertyDefinitionNode propertyDefinitionNode = new PropertyDefinitionNode(); + Map inParams = new HashMap(); + inParams.put(ParamsHandlerConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); + + String yamlData = IOUtils.toString(TestPropertyDefinitionNode.class.getClassLoader().getResourceAsStream("parser/pd.yaml"), Charset.defaultCharset()); + inParams.put(ParamsHandlerConstant.INPUT_PARAM_PD_CONTENT, yamlData); + + String jsonData = IOUtils.toString(TestPropertyDefinitionNode.class.getClassLoader().getResourceAsStream("parser/request-param.json"), Charset.defaultCharset()); + inParams.put(ParamsHandlerConstant.INPUT_PARAM_JSON_DATA, jsonData); + + SvcLogicContext ctx = new SvcLogicContext(); + propertyDefinitionNode.processMissingParamKeys(inParams, ctx); + assertEquals(ctx.getAttribute("test."+ParamsHandlerConstant.OUTPUT_PARAM_STATUS), ParamsHandlerConstant.OUTPUT_STATUS_SUCCESS); + + } + + @Test + public void testProcessExternalSystemParamKeys() throws Exception { + PropertyDefinitionNode propertyDefinitionNode = new PropertyDefinitionNode(); + Map inParams = new HashMap(); + inParams.put(ParamsHandlerConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); + + String yamlData = IOUtils.toString(TestPropertyDefinitionNode.class.getClassLoader().getResourceAsStream("parser/pd.yaml"), Charset.defaultCharset()); + inParams.put(ParamsHandlerConstant.INPUT_PARAM_PD_CONTENT, yamlData); + + String jsonData = IOUtils.toString(TestPropertyDefinitionNode.class.getClassLoader().getResourceAsStream("parser/request-param.json"), Charset.defaultCharset()); + inParams.put(ParamsHandlerConstant.INPUT_PARAM_JSON_DATA, jsonData); + + inParams.put(ParamsHandlerConstant.INPUT_PARAM_SYSTEM_NAME, "SOURCE"); + + SvcLogicContext ctx = new SvcLogicContext(); + propertyDefinitionNode.processExternalSystemParamKeys(inParams, ctx); + assertEquals(ctx.getAttribute("test."+ParamsHandlerConstant.OUTPUT_PARAM_STATUS), ParamsHandlerConstant.OUTPUT_STATUS_SUCCESS); +} + + @Test + public void mergeJsonData() throws Exception { + PropertyDefinitionNode propertyDefinitionNode = new PropertyDefinitionNode(); + Map inParams = new HashMap(); + inParams.put(ParamsHandlerConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); + + String jsonData = IOUtils.toString(TestPropertyDefinitionNode.class.getClassLoader().getResourceAsStream("parser/request-param.json"), Charset.defaultCharset()); + inParams.put(ParamsHandlerConstant.INPUT_PARAM_JSON_DATA, jsonData); + + String mergeJsonData = IOUtils.toString(TestPropertyDefinitionNode.class.getClassLoader().getResourceAsStream("parser/merge-param.json"), Charset.defaultCharset()); + inParams.put(ParamsHandlerConstant.INPUT_PARAM_MERGE__JSON_DATA, mergeJsonData); + + SvcLogicContext ctx = new SvcLogicContext(); + propertyDefinitionNode.mergeJsonData(inParams, ctx); + assertEquals(ctx.getAttribute("test."+ParamsHandlerConstant.OUTPUT_PARAM_STATUS), ParamsHandlerConstant.OUTPUT_STATUS_SUCCESS); + } + + @Test + public void testArtificatTransformer() throws Exception { + ArtificatTransformer transformer = new ArtificatTransformer(); + String yamlData = IOUtils.toString(TestPropertyDefinitionNode.class.getClassLoader().getResourceAsStream("parser/pd.yaml"), Charset.defaultCharset()); + + PropertyDefinition propertyDefinition = transformer.convertYAMLToPD(yamlData); + String yaml = transformer.convertPDToYaml(propertyDefinition); + } + +} diff --git a/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestArtifactProcessor.java b/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestArtifactProcessor.java new file mode 100644 index 000000000..33845ddca --- /dev/null +++ b/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestArtifactProcessor.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.params.transformer.tosca; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.openecomp.sdnc.config.params.transformer.tosca.exceptions.ArtifactProcessorException; + +import java.io.*; + +public class TestArtifactProcessor{ + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + public void testArtifactProcessor() throws IOException, ArtifactProcessorException { + + ArtifactProcessor arp = ArtifactProcessorFactory.getArtifactProcessor(); + + String pdString = getFileContent("tosca/ExamplePropertyDefinition.yml"); + OutputStream outstream=null; + + File tempFile = temporaryFolder.newFile("TestTosca.yml"); + outstream = new FileOutputStream(tempFile); + arp.generateArtifact(pdString,outstream); + outstream.flush(); + outstream.close(); + + String expectedTosca = getFileContent("tosca/ExpectedTosca.yml"); + String toscaString = getFileContent(tempFile); + Assert.assertEquals(expectedTosca,toscaString); + } + + @Test + public void testArtifactProcessorWithStringOutput() throws IOException, ArtifactProcessorException { + + ArtifactProcessor arp = ArtifactProcessorFactory.getArtifactProcessor(); + + String pdString = getFileContent("tosca/ExamplePropertyDefinition.yml"); + OutputStream outstream=null; + + outstream = new ByteArrayOutputStream(); + arp.generateArtifact(pdString,outstream); + outstream.flush(); + outstream.close(); + + String expectedTosca = getFileContent("tosca/ExpectedTosca.yml"); + String toscaString = outstream.toString(); + } + + private String getFileContent(String fileName) throws IOException{ + ClassLoader classLoader = new TestArtifactProcessor().getClass().getClassLoader(); + InputStream is = new FileInputStream(classLoader.getResource(fileName).getFile()); + BufferedReader buf = new BufferedReader(new InputStreamReader(is)); + String line = buf.readLine(); + StringBuilder sb = new StringBuilder(); + + while (line != null) { + sb.append(line).append("\n"); + line = buf.readLine(); + } + String fileString = sb.toString(); + is.close(); + return fileString; + } + + private String getFileContent(File file) throws IOException{ + InputStream is = new FileInputStream(file); + BufferedReader buf = new BufferedReader(new InputStreamReader(is)); + String line = buf.readLine(); + StringBuilder sb = new StringBuilder(); + + while (line != null) { + sb.append(line).append("\n"); + line = buf.readLine(); + } + String fileString = sb.toString(); + is.close(); + return fileString; + } +} diff --git a/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestGenerateArtifactObject.java b/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestGenerateArtifactObject.java new file mode 100644 index 000000000..950180262 --- /dev/null +++ b/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestGenerateArtifactObject.java @@ -0,0 +1,254 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.params.transformer.tosca; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.openecomp.sdnc.config.params.data.Parameter; +import org.openecomp.sdnc.config.params.data.PropertyDefinition; +import org.openecomp.sdnc.config.params.data.RequestKey; +import org.openecomp.sdnc.config.params.data.ResponseKey; +import org.openecomp.sdnc.config.params.transformer.tosca.exceptions.ArtifactProcessorException; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; + +public class TestGenerateArtifactObject +{ + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + public void testObjectArtifactProcessor() throws IOException, ArtifactProcessorException { + + String expectedTosca="node_types:\n" + + " VNF:\n" + + " derived_from: org.openecomp.genericvnf\n" + + " version: V1\n" + + " description: ''\n" + + " properties:\n" + + " LOCAL_ACCESS_IP_ADDR:\n" + + " type: string\n" + + " required: false\n" + + " default: 0.0.0.0\n" + + " status: SUPPORTED\n" + + " LOCAL_CORE_ALT_IP_ADDR:\n" + + " type: String\n" + + " required: false\n" + + " default: value\n" + + " status: SUPPORTED\n" + + "topology_template:\n" + + " node_templates:\n" + + " VNF_Template:\n" + + " type: VNF\n" + + " properties:\n" + + " LOCAL_ACCESS_IP_ADDR: \n" + + " LOCAL_CORE_ALT_IP_ADDR: \n"; + //Create object + PropertyDefinition pd = new PropertyDefinition(); + pd.setKind("VNF"); + pd.setVersion("V1"); + pd.setParameters(createParameters()); + + //Call ArtifactProcessor + OutputStream outstream=null; + + File toscaFile =temporaryFolder.newFile("TestTosca.yml"); + outstream = new FileOutputStream(toscaFile); + ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); + arp.generateArtifact(pd,outstream); + outstream.flush(); + outstream.close(); + + String toscaString = getFileContent(toscaFile); + Assert.assertEquals(expectedTosca,toscaString); + + } + + @Test + public void testPDpropertiesSetNull() throws IOException, ArtifactProcessorException { + String expectedTosca = "node_types:\n" + + " PropertyDefinition:\n" + + " derived_from: org.openecomp.genericvnf\n" + + " version: V1\n" + + " description: ''\n" + + "topology_template:\n" + + " node_templates:\n" + + " PropertyDefinition_Template:\n" + + " type: PropertyDefinition\n"; + //Create object + PropertyDefinition pd = new PropertyDefinition(); + pd.setKind("PropertyDefinition"); + pd.setVersion("V1"); + OutputStream outstream=null; + + File toscaFile =temporaryFolder.newFile("TestTosca.yml"); + outstream = new FileOutputStream(toscaFile); + + ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); + arp.generateArtifact(pd,outstream); + outstream.flush(); + outstream.close(); + + String toscaString = getFileContent(toscaFile); + Assert.assertEquals(expectedTosca,toscaString); + } + + @Test + public void testArtifactGeneratorInvalidStream() throws IOException { + String expectedMsg = "java.io.IOException: Stream Closed"; + PropertyDefinition pd = new PropertyDefinition(); + pd.setKind("VNF"); + pd.setVersion("V1"); + pd.setParameters(createParameters()); + + //Call ArtifactProcessor + OutputStream outstream=null; + try { + File toscaFile =temporaryFolder.newFile("TestTosca.yml"); + outstream = new FileOutputStream(toscaFile); + outstream.close(); + ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); + arp.generateArtifact(pd,outstream); + Assert.fail(); + } + catch (ArtifactProcessorException e) + { + Assert.assertEquals(expectedMsg,e.getMessage()); + } + } + + private List createParameters() + { + //Create single Parameter object 1 + Parameter singleParameter1 = new Parameter(); + singleParameter1.setName("LOCAL_ACCESS_IP_ADDR"); + singleParameter1.setRequired(false); + singleParameter1.setSource("source"); + singleParameter1.setDefaultValue("0.0.0.0"); + singleParameter1.setRuleType("myRule1"); + singleParameter1.setRequestKeys(createRequestKeys()); + + //Create single Parameter object 2 + Parameter singleParameter2 = new Parameter(); + singleParameter2.setName("LOCAL_CORE_ALT_IP_ADDR"); + singleParameter2.setType("String"); + singleParameter2.setRequired(false); + singleParameter2.setSource("source"); + singleParameter2.setDefaultValue("value"); + singleParameter2.setRuleType("myRule2"); + singleParameter2.setResponseKeys(createResponseKeys()); + + //Add the Parameter objects to the List + List parameterList = new ArrayList(); + parameterList.add(singleParameter1); + parameterList.add(singleParameter2); + return parameterList; + } + + private List createRequestKeys() + { + //Create RequestKey object 1 + RequestKey requestKey1 = new RequestKey(); + requestKey1.setKeyName("class-type"); + requestKey1.setKeyValue("interface-ip-address"); + + //Create RequestKey object 2 + RequestKey requestKey2 = new RequestKey(); + requestKey2.setKeyName("address_fqdn"); + requestKey2.setKeyValue("someVal"); + + //Create RequestKey object 3 + RequestKey requestKey3 = new RequestKey(); + requestKey3.setKeyName("address_type"); + requestKey3.setKeyValue("v4"); + + //Add the RequestKey Objects to the List + List requestKeyList = new ArrayList(); + requestKeyList.add(requestKey1); + requestKeyList.add(requestKey2); + requestKeyList.add(requestKey3); + return requestKeyList; + } + + private List createResponseKeys() + { + //Create RequestKey object 1 + ResponseKey responseKey1 = new ResponseKey(); + + responseKey1.setUniqueKeyName("name1"); + responseKey1.setUniqueKeyValue("value1"); + responseKey1.setFieldKeyName("field1"); + + //Add the RequestKey Objects to the List + List responseKeyList = new ArrayList(); + responseKeyList.add(responseKey1); + + return responseKeyList; + } + + private Parameter createParameter() + { + Parameter singleParameter1 = new Parameter(); + singleParameter1.setName("LOCAL_ACCESS_IP_ADDR"); + singleParameter1.setRequired(false); + singleParameter1.setSource("source"); + singleParameter1.setDefaultValue("0.0.0.0"); + singleParameter1.setRequestKeys(createRequestKeys()); + singleParameter1.setResponseKeys(createResponseKeys()); + return singleParameter1; + } + + @Test(expected =Exception.class) + public void testPDnull() throws IOException, ArtifactProcessorException { + PropertyDefinition pd = null; + OutputStream outstream=null; + + outstream = new FileOutputStream(".\\TestTosca.yml"); + ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); + arp.generateArtifact(pd,outstream); + outstream.flush(); + outstream.close(); + } + + private String getFileContent(File file) throws IOException + { + InputStream is = new FileInputStream(file); + BufferedReader buf = new BufferedReader(new InputStreamReader(is)); + String line = buf.readLine(); + StringBuilder sb = new StringBuilder(); + + while (line != null) { + sb.append(line).append("\n"); + line = buf.readLine(); + } + String fileString = sb.toString(); + is.close(); + return fileString; + } +} diff --git a/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestGenerateArtifactString.java b/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestGenerateArtifactString.java new file mode 100644 index 000000000..4ffbe5298 --- /dev/null +++ b/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestGenerateArtifactString.java @@ -0,0 +1,155 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.params.transformer.tosca; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.openecomp.sdnc.config.params.transformer.tosca.exceptions.ArtifactProcessorException; + +import java.io.*; +import java.net.URL; + +public class TestGenerateArtifactString{ + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + public void testStringArtifactGenerator() throws IOException, ArtifactProcessorException { + + String pdString = getFileContent("tosca/ExamplePropertyDefinition.yml"); + OutputStream outstream=null; + + File tempFile = temporaryFolder.newFile("TestTosca.yml"); + outstream = new FileOutputStream(tempFile); + ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); + arp.generateArtifact(pdString,outstream); + outstream.flush(); + outstream.close(); + + String expectedTosca = getFileContent("tosca/ExpectedTosca.yml"); + String toscaString = getFileContent(tempFile); + Assert.assertEquals(expectedTosca,toscaString); + + } + + @Test + public void testArtifactGeneratorWithParameterNameBlank() throws IOException, ArtifactProcessorException { + + String pdString = getFileContent("tosca/ExamplePropertyDefinition2.yml"); + OutputStream outstream=null; + String expectedMsg ="Parameter name is empty,null or contains whitespace"; + + File tempFile = temporaryFolder.newFile("TestTosca.yml"); + outstream = new FileOutputStream(tempFile); + ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); + try { + arp.generateArtifact(pdString, outstream); + } + catch (ArtifactProcessorException e) + { + Assert.assertEquals(expectedMsg,e.getMessage()); + } + outstream.flush(); + outstream.close(); + } + + @Test + public void testArtifactGeneratorWithParameterNameNull() throws IOException, ArtifactProcessorException { + + String pdString = getFileContent("tosca/ExamplePropertyDefinition3.yml"); + OutputStream outstream=null; + String expectedMsg ="Parameter name is empty,null or contains whitespace"; + + File tempFile = temporaryFolder.newFile("TestTosca.yml"); + outstream = new FileOutputStream(tempFile); + ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); + try { + arp.generateArtifact(pdString, outstream); + } + catch (ArtifactProcessorException e) + { + Assert.assertEquals(expectedMsg,e.getMessage()); + } + outstream.flush(); + outstream.close(); + } + + @Test + public void testArtifactGeneratorWithKindNull() throws IOException, ArtifactProcessorException { + + String pdString = getFileContent("tosca/ExamplePropertyDefinition4.yml"); + OutputStream outstream=null; + String expectedMsg ="Kind in PropertyDefinition is blank or null"; + + File tempFile = temporaryFolder.newFile("TestTosca.yml"); + outstream = new FileOutputStream(tempFile); + ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); + try { + arp.generateArtifact(pdString, outstream); + } + catch (ArtifactProcessorException e) + { + Assert.assertEquals(expectedMsg,e.getMessage()); + } + outstream.flush(); + outstream.close(); + } + + private String getFileContent(String fileName) throws IOException + { + ClassLoader classLoader = new TestGenerateArtifactString().getClass().getClassLoader(); + InputStream is = new FileInputStream(classLoader.getResource(fileName).getFile()); + BufferedReader buf = new BufferedReader(new InputStreamReader(is)); + String line = buf.readLine(); + StringBuilder sb = new StringBuilder(); + + while (line != null) { + sb.append(line).append("\n"); + line = buf.readLine(); + } + String fileString = sb.toString(); + is.close(); + return fileString; + } + + private String getFileContent(File file) throws IOException + { + InputStream is = new FileInputStream(file); + BufferedReader buf = new BufferedReader(new InputStreamReader(is)); + String line = buf.readLine(); + StringBuilder sb = new StringBuilder(); + + while (line != null) { + sb.append(line).append("\n"); + line = buf.readLine(); + } + String fileString = sb.toString(); + is.close(); + return fileString; + } +} diff --git a/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestPropertyQueryString.java b/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestPropertyQueryString.java new file mode 100644 index 000000000..3eb231ae9 --- /dev/null +++ b/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestPropertyQueryString.java @@ -0,0 +1,171 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.config.params.transformer.tosca; + +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.sdnc.config.params.data.RequestKey; +import org.openecomp.sdnc.config.params.data.ResponseKey; + +import java.util.ArrayList; +import java.util.List; + +public class TestPropertyQueryString +{ + @Test + public void testBuildResponseKeys() + { + ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); + String properties= arp.buildResponseKeyExpression(createResponseKeys()); + Assert.assertEquals("",properties); + } + + @Test + public void testBuildRequestKeys() + { + ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); + String properties= arp.buildRequestKeyExpression(createRequestKeys()); + Assert.assertEquals("",properties); + } + + @Test + public void testEncoding() + { + ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); + + String expected1 = "<class-type>"; + String encoded1 = arp.encode(""); + Assert.assertEquals(expected1,encoded1); + + String expected2 = "<<<metallica<>iron_maiden>>>"; + String encoded2 = arp.encode("<<iron_maiden>>>"); + Assert.assertEquals(expected2,encoded2); + + String expected3 = "band-list:metallica,ironmaiden"; + String encoded3 = arp.encode("band-list:metallica,ironmaiden"); + Assert.assertEquals(expected3,encoded3); + + String expected4 = "motorhead=lemmy"; + String encoded4 = arp.encode("motorhead=lemmy"); + Assert.assertEquals(expected4,encoded4); + + String expected5 = "DreamTheater"; + String encoded5 = arp.encode(" DreamTheater "); + Assert.assertEquals(expected5,encoded5); + } + + @Test + public void testBuildRuleType() + { + ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); + String input = "IPV4"; + String expected = ""; + Assert.assertEquals(expected,arp.buildRuleType(input)); + } + + @Test + public void testRuleTypeSetNull() + { + ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); + String expected = ""; + Assert.assertEquals(expected,arp.buildRuleType(null)); + } + + @Test + public void testBuildRequestKeysWithKeyNull() + { + ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); + List requestKeyList = new ArrayList(); + requestKeyList.add(null); + String properties= arp.buildRequestKeyExpression(requestKeyList); + Assert.assertEquals("",properties); + } + + @Test + public void testBuildResponseKeysWithKeyNull() + { + ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); + List responseKeyList = new ArrayList(); + responseKeyList.add(null); + String properties= arp.buildResponseKeyExpression(responseKeyList); + Assert.assertEquals("",properties); + } + + @Test + public void testBuildSourceSystem() + { + ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); + Assert.assertEquals("",arp.buildSourceSystem("source")); + } + + //@Test + private List createRequestKeys() + { + //Create RequestKey object 1 + RequestKey requestKey1 = new RequestKey(); + requestKey1.setKeyName("class-type"); + requestKey1.setKeyValue("interface-ip-address"); + + //Create RequestKey object 2 + RequestKey requestKey2 = new RequestKey(); + requestKey2.setKeyName("address_fqdn"); + requestKey2.setKeyValue("00000000000000"); + + //Create RequestKey object 3 + RequestKey requestKey3 = new RequestKey(); + requestKey3.setKeyName("address_type"); + requestKey3.setKeyValue("v4"); + + //Add the RequestKey Objects to the List + List requestKeyList = new ArrayList(); + requestKeyList.add(requestKey1); + requestKeyList.add(requestKey2); + requestKeyList.add(requestKey3); + return requestKeyList; + } + + //@Test + private List createResponseKeys() + { + //Create RequestKey object 1 + ResponseKey responseKey1 = new ResponseKey(); + + responseKey1.setUniqueKeyName("address-fqdn"); + responseKey1.setUniqueKeyValue("0000000000000"); + responseKey1.setFieldKeyName("ipaddress-v4"); + + ResponseKey responseKey2 = new ResponseKey(); + responseKey2.setUniqueKeyName("key2"); + responseKey2.setUniqueKeyValue("value2"); + responseKey2.setFieldKeyName("field2"); + + //Add the RequestKey Objects to the List + List responseKeyList = new ArrayList(); + responseKeyList.add(responseKey1); + responseKeyList.add(responseKey2); + + return responseKeyList; + } +} diff --git a/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestReadArtifact.java b/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestReadArtifact.java new file mode 100644 index 000000000..1b65a21f6 --- /dev/null +++ b/appc-config/appc-config-params/provider/src/test/java/org/onap/sdnc/config/params/transformer/tosca/TestReadArtifact.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.openecomp.sdnc.config.params.transformer.tosca; + +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.sdnc.config.params.data.PropertyDefinition; +import org.openecomp.sdnc.config.params.transformer.tosca.exceptions.ArtifactProcessorException; + +import java.io.*; + +public class TestReadArtifact { + @Test + public void testReadArtifactPositive() throws ArtifactProcessorException, IOException { + + String toscaArtifact = getFileContent("tosca/ReadArtifactPositiveInputTosca.yml"); + ArtifactProcessorImpl artifact = new ArtifactProcessorImpl(); + PropertyDefinition ouptPD = artifact.readArtifact(toscaArtifact); + Assert.assertEquals(ouptPD.getKind(),"Property Definition"); + Assert.assertEquals(ouptPD.getVersion(),"V1"); + + Assert.assertEquals(ouptPD.getParameters().get(0).getDefaultValue(),"0.0.0.0"); + Assert.assertEquals(ouptPD.getParameters().get(0).getName(),"abc"); + Assert.assertEquals(ouptPD.getParameters().get(0).getSource(),"source"); + Assert.assertEquals(ouptPD.getParameters().get(0).getRuleType(),"interface-ip-address"); + Assert.assertEquals(ouptPD.getParameters().get(0).getDescription(),"param_desc"); + Assert.assertEquals(ouptPD.getParameters().get(0).getType(),"param1_type"); + Assert.assertEquals(ouptPD.getParameters().get(1).getRequestKeys().get(0).getKeyName(),"address_fqdn"); + Assert.assertEquals(ouptPD.getParameters().get(1).getRequestKeys().get(0).getKeyValue(),"0"); + Assert.assertEquals(ouptPD.getParameters().get(1).getRequestKeys().get(0).getKeyName(),"address_fqdn"); + Assert.assertEquals(ouptPD.getParameters().get(1).getRequestKeys().get(0).getKeyValue(),"0"); + Assert.assertEquals(ouptPD.getParameters().get(0).getResponseKeys().get(0).getUniqueKeyName(),"address-0"); + Assert.assertEquals(ouptPD.getParameters().get(0).getResponseKeys().get(0).getFieldKeyName(),"0"); + + Assert.assertEquals(ouptPD.getParameters().get(1).getDefaultValue(),"value"); + Assert.assertEquals(ouptPD.getParameters().get(1).getName(),"param 2"); + Assert.assertEquals(ouptPD.getParameters().get(1).getSource(),"source"); + Assert.assertEquals(ouptPD.getParameters().get(1).getRuleType(),"interface-ip-address"); + Assert.assertEquals(ouptPD.getParameters().get(1).getDescription(),"param2"); + Assert.assertEquals(ouptPD.getParameters().get(1).getType(),"param2 type"); + Assert.assertEquals(ouptPD.getParameters().get(1).getRequestKeys().get(0).getKeyName(),"address_fqdn"); + Assert.assertEquals(ouptPD.getParameters().get(1).getRequestKeys().get(0).getKeyValue(),"0"); + Assert.assertEquals(ouptPD.getParameters().get(1).getRequestKeys().get(1).getKeyName(),"address_type"); + Assert.assertEquals(ouptPD.getParameters().get(1).getRequestKeys().get(1).getKeyValue(),"v4"); + Assert.assertEquals(ouptPD.getParameters().get(1).getResponseKeys().get(0).getUniqueKeyName(),"address-0"); + Assert.assertEquals(ouptPD.getParameters().get(1).getResponseKeys().get(0).getUniqueKeyValue(),"0"); + Assert.assertEquals(ouptPD.getParameters().get(1).getResponseKeys().get(0).getFieldKeyName(),"0"); + + } + + @Test + public void testReadArtifactNegetive() throws IOException { + + String toscaArtifact = getFileContent("tosca/ReadArtifactNegetiveInputTosca.yml"); + ArtifactProcessorImpl artifact = new ArtifactProcessorImpl(); + try { + PropertyDefinition ouptPD = artifact.readArtifact(toscaArtifact); + } catch (ArtifactProcessorException e) { + Assert.assertNotNull(e); + Assert.assertEquals(e.getMessage(),"Invalid input found <> source1 "); + } + } + + private String getFileContent(String fileName) throws IOException + { + ClassLoader classLoader = new TestReadArtifact().getClass().getClassLoader(); + InputStream is = new FileInputStream(classLoader.getResource(fileName).getFile()); + BufferedReader buf = new BufferedReader(new InputStreamReader(is)); + String line = buf.readLine(); + StringBuilder sb = new StringBuilder(); + + while (line != null) { + sb.append(line).append("\n"); + line = buf.readLine(); + } + String fileString = sb.toString(); + is.close(); + return fileString; + } + +} diff --git a/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/parser/TestPropertyDefinitionNode.java b/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/parser/TestPropertyDefinitionNode.java deleted file mode 100644 index be11384c4..000000000 --- a/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/parser/TestPropertyDefinitionNode.java +++ /dev/null @@ -1,116 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.params.parser; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.apache.commons.io.IOUtils; -import org.junit.Test; -import org.junit.Ignore; -import org.openecomp.sdnc.config.params.ParamsHandlerConstant; -import org.openecomp.sdnc.config.params.data.PropertyDefinition; -import org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode; -import org.openecomp.sdnc.config.params.transformer.ArtificatTransformer; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import com.fasterxml.jackson.databind.ObjectMapper; - -public class TestPropertyDefinitionNode { - - @Ignore - public void testProcessMissingParamKeys() throws Exception { - PropertyDefinitionNode propertyDefinitionNode = new PropertyDefinitionNode(); - Map inParams = new HashMap(); - inParams.put(ParamsHandlerConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); - - String yamlData = IOUtils.toString(TestPropertyDefinitionNode.class.getClassLoader().getResourceAsStream("parser/pd.yaml"), Charset.defaultCharset()); - inParams.put(ParamsHandlerConstant.INPUT_PARAM_PD_CONTENT, yamlData); - - String jsonData = IOUtils.toString(TestPropertyDefinitionNode.class.getClassLoader().getResourceAsStream("parser/request-param.json"), Charset.defaultCharset()); - inParams.put(ParamsHandlerConstant.INPUT_PARAM_JSON_DATA, jsonData); - - SvcLogicContext ctx = new SvcLogicContext(); - propertyDefinitionNode.processMissingParamKeys(inParams, ctx); - assertEquals(ctx.getAttribute("test."+ParamsHandlerConstant.OUTPUT_PARAM_STATUS), ParamsHandlerConstant.OUTPUT_STATUS_SUCCESS); - - } - - @Test - public void testProcessExternalSystemParamKeys() throws Exception { - PropertyDefinitionNode propertyDefinitionNode = new PropertyDefinitionNode(); - Map inParams = new HashMap(); - inParams.put(ParamsHandlerConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); - - String yamlData = IOUtils.toString(TestPropertyDefinitionNode.class.getClassLoader().getResourceAsStream("parser/pd.yaml"), Charset.defaultCharset()); - inParams.put(ParamsHandlerConstant.INPUT_PARAM_PD_CONTENT, yamlData); - - String jsonData = IOUtils.toString(TestPropertyDefinitionNode.class.getClassLoader().getResourceAsStream("parser/request-param.json"), Charset.defaultCharset()); - inParams.put(ParamsHandlerConstant.INPUT_PARAM_JSON_DATA, jsonData); - - inParams.put(ParamsHandlerConstant.INPUT_PARAM_SYSTEM_NAME, "SOURCE"); - - SvcLogicContext ctx = new SvcLogicContext(); - propertyDefinitionNode.processExternalSystemParamKeys(inParams, ctx); - assertEquals(ctx.getAttribute("test."+ParamsHandlerConstant.OUTPUT_PARAM_STATUS), ParamsHandlerConstant.OUTPUT_STATUS_SUCCESS); -} - - @Test - public void mergeJsonData() throws Exception { - PropertyDefinitionNode propertyDefinitionNode = new PropertyDefinitionNode(); - Map inParams = new HashMap(); - inParams.put(ParamsHandlerConstant.INPUT_PARAM_RESPONSE_PRIFIX, "test"); - - String jsonData = IOUtils.toString(TestPropertyDefinitionNode.class.getClassLoader().getResourceAsStream("parser/request-param.json"), Charset.defaultCharset()); - inParams.put(ParamsHandlerConstant.INPUT_PARAM_JSON_DATA, jsonData); - - String mergeJsonData = IOUtils.toString(TestPropertyDefinitionNode.class.getClassLoader().getResourceAsStream("parser/merge-param.json"), Charset.defaultCharset()); - inParams.put(ParamsHandlerConstant.INPUT_PARAM_MERGE__JSON_DATA, mergeJsonData); - - SvcLogicContext ctx = new SvcLogicContext(); - propertyDefinitionNode.mergeJsonData(inParams, ctx); - assertEquals(ctx.getAttribute("test."+ParamsHandlerConstant.OUTPUT_PARAM_STATUS), ParamsHandlerConstant.OUTPUT_STATUS_SUCCESS); - } - - @Test - public void testArtificatTransformer() throws Exception { - ArtificatTransformer transformer = new ArtificatTransformer(); - String yamlData = IOUtils.toString(TestPropertyDefinitionNode.class.getClassLoader().getResourceAsStream("parser/pd.yaml"), Charset.defaultCharset()); - - PropertyDefinition propertyDefinition = transformer.convertYAMLToPD(yamlData); - String yaml = transformer.convertPDToYaml(propertyDefinition); - } - -} diff --git a/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestArtifactProcessor.java b/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestArtifactProcessor.java deleted file mode 100644 index 33845ddca..000000000 --- a/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestArtifactProcessor.java +++ /dev/null @@ -1,105 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.params.transformer.tosca; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.openecomp.sdnc.config.params.transformer.tosca.exceptions.ArtifactProcessorException; - -import java.io.*; - -public class TestArtifactProcessor{ - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @Test - public void testArtifactProcessor() throws IOException, ArtifactProcessorException { - - ArtifactProcessor arp = ArtifactProcessorFactory.getArtifactProcessor(); - - String pdString = getFileContent("tosca/ExamplePropertyDefinition.yml"); - OutputStream outstream=null; - - File tempFile = temporaryFolder.newFile("TestTosca.yml"); - outstream = new FileOutputStream(tempFile); - arp.generateArtifact(pdString,outstream); - outstream.flush(); - outstream.close(); - - String expectedTosca = getFileContent("tosca/ExpectedTosca.yml"); - String toscaString = getFileContent(tempFile); - Assert.assertEquals(expectedTosca,toscaString); - } - - @Test - public void testArtifactProcessorWithStringOutput() throws IOException, ArtifactProcessorException { - - ArtifactProcessor arp = ArtifactProcessorFactory.getArtifactProcessor(); - - String pdString = getFileContent("tosca/ExamplePropertyDefinition.yml"); - OutputStream outstream=null; - - outstream = new ByteArrayOutputStream(); - arp.generateArtifact(pdString,outstream); - outstream.flush(); - outstream.close(); - - String expectedTosca = getFileContent("tosca/ExpectedTosca.yml"); - String toscaString = outstream.toString(); - } - - private String getFileContent(String fileName) throws IOException{ - ClassLoader classLoader = new TestArtifactProcessor().getClass().getClassLoader(); - InputStream is = new FileInputStream(classLoader.getResource(fileName).getFile()); - BufferedReader buf = new BufferedReader(new InputStreamReader(is)); - String line = buf.readLine(); - StringBuilder sb = new StringBuilder(); - - while (line != null) { - sb.append(line).append("\n"); - line = buf.readLine(); - } - String fileString = sb.toString(); - is.close(); - return fileString; - } - - private String getFileContent(File file) throws IOException{ - InputStream is = new FileInputStream(file); - BufferedReader buf = new BufferedReader(new InputStreamReader(is)); - String line = buf.readLine(); - StringBuilder sb = new StringBuilder(); - - while (line != null) { - sb.append(line).append("\n"); - line = buf.readLine(); - } - String fileString = sb.toString(); - is.close(); - return fileString; - } -} diff --git a/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestGenerateArtifactObject.java b/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestGenerateArtifactObject.java deleted file mode 100644 index 950180262..000000000 --- a/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestGenerateArtifactObject.java +++ /dev/null @@ -1,254 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.params.transformer.tosca; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.openecomp.sdnc.config.params.data.Parameter; -import org.openecomp.sdnc.config.params.data.PropertyDefinition; -import org.openecomp.sdnc.config.params.data.RequestKey; -import org.openecomp.sdnc.config.params.data.ResponseKey; -import org.openecomp.sdnc.config.params.transformer.tosca.exceptions.ArtifactProcessorException; - -import java.io.*; -import java.util.ArrayList; -import java.util.List; - -public class TestGenerateArtifactObject -{ - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @Test - public void testObjectArtifactProcessor() throws IOException, ArtifactProcessorException { - - String expectedTosca="node_types:\n" + - " VNF:\n" + - " derived_from: org.openecomp.genericvnf\n" + - " version: V1\n" + - " description: ''\n" + - " properties:\n" + - " LOCAL_ACCESS_IP_ADDR:\n" + - " type: string\n" + - " required: false\n" + - " default: 0.0.0.0\n" + - " status: SUPPORTED\n" + - " LOCAL_CORE_ALT_IP_ADDR:\n" + - " type: String\n" + - " required: false\n" + - " default: value\n" + - " status: SUPPORTED\n" + - "topology_template:\n" + - " node_templates:\n" + - " VNF_Template:\n" + - " type: VNF\n" + - " properties:\n" + - " LOCAL_ACCESS_IP_ADDR: \n" + - " LOCAL_CORE_ALT_IP_ADDR: \n"; - //Create object - PropertyDefinition pd = new PropertyDefinition(); - pd.setKind("VNF"); - pd.setVersion("V1"); - pd.setParameters(createParameters()); - - //Call ArtifactProcessor - OutputStream outstream=null; - - File toscaFile =temporaryFolder.newFile("TestTosca.yml"); - outstream = new FileOutputStream(toscaFile); - ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); - arp.generateArtifact(pd,outstream); - outstream.flush(); - outstream.close(); - - String toscaString = getFileContent(toscaFile); - Assert.assertEquals(expectedTosca,toscaString); - - } - - @Test - public void testPDpropertiesSetNull() throws IOException, ArtifactProcessorException { - String expectedTosca = "node_types:\n" + - " PropertyDefinition:\n" + - " derived_from: org.openecomp.genericvnf\n" + - " version: V1\n" + - " description: ''\n" + - "topology_template:\n" + - " node_templates:\n" + - " PropertyDefinition_Template:\n" + - " type: PropertyDefinition\n"; - //Create object - PropertyDefinition pd = new PropertyDefinition(); - pd.setKind("PropertyDefinition"); - pd.setVersion("V1"); - OutputStream outstream=null; - - File toscaFile =temporaryFolder.newFile("TestTosca.yml"); - outstream = new FileOutputStream(toscaFile); - - ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); - arp.generateArtifact(pd,outstream); - outstream.flush(); - outstream.close(); - - String toscaString = getFileContent(toscaFile); - Assert.assertEquals(expectedTosca,toscaString); - } - - @Test - public void testArtifactGeneratorInvalidStream() throws IOException { - String expectedMsg = "java.io.IOException: Stream Closed"; - PropertyDefinition pd = new PropertyDefinition(); - pd.setKind("VNF"); - pd.setVersion("V1"); - pd.setParameters(createParameters()); - - //Call ArtifactProcessor - OutputStream outstream=null; - try { - File toscaFile =temporaryFolder.newFile("TestTosca.yml"); - outstream = new FileOutputStream(toscaFile); - outstream.close(); - ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); - arp.generateArtifact(pd,outstream); - Assert.fail(); - } - catch (ArtifactProcessorException e) - { - Assert.assertEquals(expectedMsg,e.getMessage()); - } - } - - private List createParameters() - { - //Create single Parameter object 1 - Parameter singleParameter1 = new Parameter(); - singleParameter1.setName("LOCAL_ACCESS_IP_ADDR"); - singleParameter1.setRequired(false); - singleParameter1.setSource("source"); - singleParameter1.setDefaultValue("0.0.0.0"); - singleParameter1.setRuleType("myRule1"); - singleParameter1.setRequestKeys(createRequestKeys()); - - //Create single Parameter object 2 - Parameter singleParameter2 = new Parameter(); - singleParameter2.setName("LOCAL_CORE_ALT_IP_ADDR"); - singleParameter2.setType("String"); - singleParameter2.setRequired(false); - singleParameter2.setSource("source"); - singleParameter2.setDefaultValue("value"); - singleParameter2.setRuleType("myRule2"); - singleParameter2.setResponseKeys(createResponseKeys()); - - //Add the Parameter objects to the List - List parameterList = new ArrayList(); - parameterList.add(singleParameter1); - parameterList.add(singleParameter2); - return parameterList; - } - - private List createRequestKeys() - { - //Create RequestKey object 1 - RequestKey requestKey1 = new RequestKey(); - requestKey1.setKeyName("class-type"); - requestKey1.setKeyValue("interface-ip-address"); - - //Create RequestKey object 2 - RequestKey requestKey2 = new RequestKey(); - requestKey2.setKeyName("address_fqdn"); - requestKey2.setKeyValue("someVal"); - - //Create RequestKey object 3 - RequestKey requestKey3 = new RequestKey(); - requestKey3.setKeyName("address_type"); - requestKey3.setKeyValue("v4"); - - //Add the RequestKey Objects to the List - List requestKeyList = new ArrayList(); - requestKeyList.add(requestKey1); - requestKeyList.add(requestKey2); - requestKeyList.add(requestKey3); - return requestKeyList; - } - - private List createResponseKeys() - { - //Create RequestKey object 1 - ResponseKey responseKey1 = new ResponseKey(); - - responseKey1.setUniqueKeyName("name1"); - responseKey1.setUniqueKeyValue("value1"); - responseKey1.setFieldKeyName("field1"); - - //Add the RequestKey Objects to the List - List responseKeyList = new ArrayList(); - responseKeyList.add(responseKey1); - - return responseKeyList; - } - - private Parameter createParameter() - { - Parameter singleParameter1 = new Parameter(); - singleParameter1.setName("LOCAL_ACCESS_IP_ADDR"); - singleParameter1.setRequired(false); - singleParameter1.setSource("source"); - singleParameter1.setDefaultValue("0.0.0.0"); - singleParameter1.setRequestKeys(createRequestKeys()); - singleParameter1.setResponseKeys(createResponseKeys()); - return singleParameter1; - } - - @Test(expected =Exception.class) - public void testPDnull() throws IOException, ArtifactProcessorException { - PropertyDefinition pd = null; - OutputStream outstream=null; - - outstream = new FileOutputStream(".\\TestTosca.yml"); - ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); - arp.generateArtifact(pd,outstream); - outstream.flush(); - outstream.close(); - } - - private String getFileContent(File file) throws IOException - { - InputStream is = new FileInputStream(file); - BufferedReader buf = new BufferedReader(new InputStreamReader(is)); - String line = buf.readLine(); - StringBuilder sb = new StringBuilder(); - - while (line != null) { - sb.append(line).append("\n"); - line = buf.readLine(); - } - String fileString = sb.toString(); - is.close(); - return fileString; - } -} diff --git a/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestGenerateArtifactString.java b/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestGenerateArtifactString.java deleted file mode 100644 index 4ffbe5298..000000000 --- a/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestGenerateArtifactString.java +++ /dev/null @@ -1,155 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.params.transformer.tosca; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.openecomp.sdnc.config.params.transformer.tosca.exceptions.ArtifactProcessorException; - -import java.io.*; -import java.net.URL; - -public class TestGenerateArtifactString{ - - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @Test - public void testStringArtifactGenerator() throws IOException, ArtifactProcessorException { - - String pdString = getFileContent("tosca/ExamplePropertyDefinition.yml"); - OutputStream outstream=null; - - File tempFile = temporaryFolder.newFile("TestTosca.yml"); - outstream = new FileOutputStream(tempFile); - ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); - arp.generateArtifact(pdString,outstream); - outstream.flush(); - outstream.close(); - - String expectedTosca = getFileContent("tosca/ExpectedTosca.yml"); - String toscaString = getFileContent(tempFile); - Assert.assertEquals(expectedTosca,toscaString); - - } - - @Test - public void testArtifactGeneratorWithParameterNameBlank() throws IOException, ArtifactProcessorException { - - String pdString = getFileContent("tosca/ExamplePropertyDefinition2.yml"); - OutputStream outstream=null; - String expectedMsg ="Parameter name is empty,null or contains whitespace"; - - File tempFile = temporaryFolder.newFile("TestTosca.yml"); - outstream = new FileOutputStream(tempFile); - ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); - try { - arp.generateArtifact(pdString, outstream); - } - catch (ArtifactProcessorException e) - { - Assert.assertEquals(expectedMsg,e.getMessage()); - } - outstream.flush(); - outstream.close(); - } - - @Test - public void testArtifactGeneratorWithParameterNameNull() throws IOException, ArtifactProcessorException { - - String pdString = getFileContent("tosca/ExamplePropertyDefinition3.yml"); - OutputStream outstream=null; - String expectedMsg ="Parameter name is empty,null or contains whitespace"; - - File tempFile = temporaryFolder.newFile("TestTosca.yml"); - outstream = new FileOutputStream(tempFile); - ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); - try { - arp.generateArtifact(pdString, outstream); - } - catch (ArtifactProcessorException e) - { - Assert.assertEquals(expectedMsg,e.getMessage()); - } - outstream.flush(); - outstream.close(); - } - - @Test - public void testArtifactGeneratorWithKindNull() throws IOException, ArtifactProcessorException { - - String pdString = getFileContent("tosca/ExamplePropertyDefinition4.yml"); - OutputStream outstream=null; - String expectedMsg ="Kind in PropertyDefinition is blank or null"; - - File tempFile = temporaryFolder.newFile("TestTosca.yml"); - outstream = new FileOutputStream(tempFile); - ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); - try { - arp.generateArtifact(pdString, outstream); - } - catch (ArtifactProcessorException e) - { - Assert.assertEquals(expectedMsg,e.getMessage()); - } - outstream.flush(); - outstream.close(); - } - - private String getFileContent(String fileName) throws IOException - { - ClassLoader classLoader = new TestGenerateArtifactString().getClass().getClassLoader(); - InputStream is = new FileInputStream(classLoader.getResource(fileName).getFile()); - BufferedReader buf = new BufferedReader(new InputStreamReader(is)); - String line = buf.readLine(); - StringBuilder sb = new StringBuilder(); - - while (line != null) { - sb.append(line).append("\n"); - line = buf.readLine(); - } - String fileString = sb.toString(); - is.close(); - return fileString; - } - - private String getFileContent(File file) throws IOException - { - InputStream is = new FileInputStream(file); - BufferedReader buf = new BufferedReader(new InputStreamReader(is)); - String line = buf.readLine(); - StringBuilder sb = new StringBuilder(); - - while (line != null) { - sb.append(line).append("\n"); - line = buf.readLine(); - } - String fileString = sb.toString(); - is.close(); - return fileString; - } -} diff --git a/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestPropertyQueryString.java b/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestPropertyQueryString.java deleted file mode 100644 index 3eb231ae9..000000000 --- a/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestPropertyQueryString.java +++ /dev/null @@ -1,171 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.config.params.transformer.tosca; - -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.sdnc.config.params.data.RequestKey; -import org.openecomp.sdnc.config.params.data.ResponseKey; - -import java.util.ArrayList; -import java.util.List; - -public class TestPropertyQueryString -{ - @Test - public void testBuildResponseKeys() - { - ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); - String properties= arp.buildResponseKeyExpression(createResponseKeys()); - Assert.assertEquals("",properties); - } - - @Test - public void testBuildRequestKeys() - { - ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); - String properties= arp.buildRequestKeyExpression(createRequestKeys()); - Assert.assertEquals("",properties); - } - - @Test - public void testEncoding() - { - ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); - - String expected1 = "<class-type>"; - String encoded1 = arp.encode(""); - Assert.assertEquals(expected1,encoded1); - - String expected2 = "<<<metallica<>iron_maiden>>>"; - String encoded2 = arp.encode("<<iron_maiden>>>"); - Assert.assertEquals(expected2,encoded2); - - String expected3 = "band-list:metallica,ironmaiden"; - String encoded3 = arp.encode("band-list:metallica,ironmaiden"); - Assert.assertEquals(expected3,encoded3); - - String expected4 = "motorhead=lemmy"; - String encoded4 = arp.encode("motorhead=lemmy"); - Assert.assertEquals(expected4,encoded4); - - String expected5 = "DreamTheater"; - String encoded5 = arp.encode(" DreamTheater "); - Assert.assertEquals(expected5,encoded5); - } - - @Test - public void testBuildRuleType() - { - ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); - String input = "IPV4"; - String expected = ""; - Assert.assertEquals(expected,arp.buildRuleType(input)); - } - - @Test - public void testRuleTypeSetNull() - { - ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); - String expected = ""; - Assert.assertEquals(expected,arp.buildRuleType(null)); - } - - @Test - public void testBuildRequestKeysWithKeyNull() - { - ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); - List requestKeyList = new ArrayList(); - requestKeyList.add(null); - String properties= arp.buildRequestKeyExpression(requestKeyList); - Assert.assertEquals("",properties); - } - - @Test - public void testBuildResponseKeysWithKeyNull() - { - ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); - List responseKeyList = new ArrayList(); - responseKeyList.add(null); - String properties= arp.buildResponseKeyExpression(responseKeyList); - Assert.assertEquals("",properties); - } - - @Test - public void testBuildSourceSystem() - { - ArtifactProcessorImpl arp = new ArtifactProcessorImpl(); - Assert.assertEquals("",arp.buildSourceSystem("source")); - } - - //@Test - private List createRequestKeys() - { - //Create RequestKey object 1 - RequestKey requestKey1 = new RequestKey(); - requestKey1.setKeyName("class-type"); - requestKey1.setKeyValue("interface-ip-address"); - - //Create RequestKey object 2 - RequestKey requestKey2 = new RequestKey(); - requestKey2.setKeyName("address_fqdn"); - requestKey2.setKeyValue("00000000000000"); - - //Create RequestKey object 3 - RequestKey requestKey3 = new RequestKey(); - requestKey3.setKeyName("address_type"); - requestKey3.setKeyValue("v4"); - - //Add the RequestKey Objects to the List - List requestKeyList = new ArrayList(); - requestKeyList.add(requestKey1); - requestKeyList.add(requestKey2); - requestKeyList.add(requestKey3); - return requestKeyList; - } - - //@Test - private List createResponseKeys() - { - //Create RequestKey object 1 - ResponseKey responseKey1 = new ResponseKey(); - - responseKey1.setUniqueKeyName("address-fqdn"); - responseKey1.setUniqueKeyValue("0000000000000"); - responseKey1.setFieldKeyName("ipaddress-v4"); - - ResponseKey responseKey2 = new ResponseKey(); - responseKey2.setUniqueKeyName("key2"); - responseKey2.setUniqueKeyValue("value2"); - responseKey2.setFieldKeyName("field2"); - - //Add the RequestKey Objects to the List - List responseKeyList = new ArrayList(); - responseKeyList.add(responseKey1); - responseKeyList.add(responseKey2); - - return responseKeyList; - } -} diff --git a/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestReadArtifact.java b/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestReadArtifact.java deleted file mode 100644 index 1b65a21f6..000000000 --- a/appc-config/appc-config-params/provider/src/test/java/org/openecomp/sdnc/config/params/transformer/tosca/TestReadArtifact.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.openecomp.sdnc.config.params.transformer.tosca; - -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.sdnc.config.params.data.PropertyDefinition; -import org.openecomp.sdnc.config.params.transformer.tosca.exceptions.ArtifactProcessorException; - -import java.io.*; - -public class TestReadArtifact { - @Test - public void testReadArtifactPositive() throws ArtifactProcessorException, IOException { - - String toscaArtifact = getFileContent("tosca/ReadArtifactPositiveInputTosca.yml"); - ArtifactProcessorImpl artifact = new ArtifactProcessorImpl(); - PropertyDefinition ouptPD = artifact.readArtifact(toscaArtifact); - Assert.assertEquals(ouptPD.getKind(),"Property Definition"); - Assert.assertEquals(ouptPD.getVersion(),"V1"); - - Assert.assertEquals(ouptPD.getParameters().get(0).getDefaultValue(),"0.0.0.0"); - Assert.assertEquals(ouptPD.getParameters().get(0).getName(),"abc"); - Assert.assertEquals(ouptPD.getParameters().get(0).getSource(),"source"); - Assert.assertEquals(ouptPD.getParameters().get(0).getRuleType(),"interface-ip-address"); - Assert.assertEquals(ouptPD.getParameters().get(0).getDescription(),"param_desc"); - Assert.assertEquals(ouptPD.getParameters().get(0).getType(),"param1_type"); - Assert.assertEquals(ouptPD.getParameters().get(1).getRequestKeys().get(0).getKeyName(),"address_fqdn"); - Assert.assertEquals(ouptPD.getParameters().get(1).getRequestKeys().get(0).getKeyValue(),"0"); - Assert.assertEquals(ouptPD.getParameters().get(1).getRequestKeys().get(0).getKeyName(),"address_fqdn"); - Assert.assertEquals(ouptPD.getParameters().get(1).getRequestKeys().get(0).getKeyValue(),"0"); - Assert.assertEquals(ouptPD.getParameters().get(0).getResponseKeys().get(0).getUniqueKeyName(),"address-0"); - Assert.assertEquals(ouptPD.getParameters().get(0).getResponseKeys().get(0).getFieldKeyName(),"0"); - - Assert.assertEquals(ouptPD.getParameters().get(1).getDefaultValue(),"value"); - Assert.assertEquals(ouptPD.getParameters().get(1).getName(),"param 2"); - Assert.assertEquals(ouptPD.getParameters().get(1).getSource(),"source"); - Assert.assertEquals(ouptPD.getParameters().get(1).getRuleType(),"interface-ip-address"); - Assert.assertEquals(ouptPD.getParameters().get(1).getDescription(),"param2"); - Assert.assertEquals(ouptPD.getParameters().get(1).getType(),"param2 type"); - Assert.assertEquals(ouptPD.getParameters().get(1).getRequestKeys().get(0).getKeyName(),"address_fqdn"); - Assert.assertEquals(ouptPD.getParameters().get(1).getRequestKeys().get(0).getKeyValue(),"0"); - Assert.assertEquals(ouptPD.getParameters().get(1).getRequestKeys().get(1).getKeyName(),"address_type"); - Assert.assertEquals(ouptPD.getParameters().get(1).getRequestKeys().get(1).getKeyValue(),"v4"); - Assert.assertEquals(ouptPD.getParameters().get(1).getResponseKeys().get(0).getUniqueKeyName(),"address-0"); - Assert.assertEquals(ouptPD.getParameters().get(1).getResponseKeys().get(0).getUniqueKeyValue(),"0"); - Assert.assertEquals(ouptPD.getParameters().get(1).getResponseKeys().get(0).getFieldKeyName(),"0"); - - } - - @Test - public void testReadArtifactNegetive() throws IOException { - - String toscaArtifact = getFileContent("tosca/ReadArtifactNegetiveInputTosca.yml"); - ArtifactProcessorImpl artifact = new ArtifactProcessorImpl(); - try { - PropertyDefinition ouptPD = artifact.readArtifact(toscaArtifact); - } catch (ArtifactProcessorException e) { - Assert.assertNotNull(e); - Assert.assertEquals(e.getMessage(),"Invalid input found <> source1 "); - } - } - - private String getFileContent(String fileName) throws IOException - { - ClassLoader classLoader = new TestReadArtifact().getClass().getClassLoader(); - InputStream is = new FileInputStream(classLoader.getResource(fileName).getFile()); - BufferedReader buf = new BufferedReader(new InputStreamReader(is)); - String line = buf.readLine(); - StringBuilder sb = new StringBuilder(); - - while (line != null) { - sb.append(line).append("\n"); - line = buf.readLine(); - } - String fileString = sb.toString(); - is.close(); - return fileString; - } - -} diff --git a/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/AppcDataServiceActivator.java b/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/AppcDataServiceActivator.java new file mode 100644 index 000000000..698924853 --- /dev/null +++ b/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/AppcDataServiceActivator.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.data.services; + +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; + +import org.onap.appc.data.services.node.ConfigResourceNode; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class AppcDataServiceActivator implements BundleActivator { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(AppcDataServiceActivator.class); + private List registrations = new LinkedList(); + + @Override + public void start(BundleContext ctx) throws Exception { + + ConfigResourceNode configResourceNode = new ConfigResourceNode(); + log.info("Registering service-- " + configResourceNode.getClass().getName()); + registrations.add(ctx.registerService(configResourceNode.getClass().getName(), configResourceNode, null)); + + + + + } + + @Override + public void stop(BundleContext arg0) throws Exception { + for (ServiceRegistration registration : registrations) { + registration.unregister(); + registration = null; + } + } +} diff --git a/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/AppcDataServiceConstant.java b/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/AppcDataServiceConstant.java new file mode 100644 index 000000000..9add56b5e --- /dev/null +++ b/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/AppcDataServiceConstant.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.data.services; + +public class AppcDataServiceConstant { + + + + + public static String INPUT_PARAM_RESPONSE_PREFIX = "responsePrefix"; + public static String OUTPUT_STATUS_SUCCESS = "success"; + public static String OUTPUT_STATUS_FAILURE = "failure"; + public static final String INPUT_PARAM_MESSAGE = "message"; + public static final String INPUT_PARAM_MESSAGE_TYPE = "messageType"; + public static String OUTPUT_PARAM_STATUS = "status"; + public static String OUTPUT_PARAM_ERROR_MESSAGE = "error-message"; + public static final String INPUT_PARAM_FILE_CATEGORY = "fileCategory"; + public static final String INPUT_PARAM_VM_INSTANCE = "vmInstance"; + public static final String INPUT_PARAM_SDC_ARTIFACT_IND = "asdcArtifactInd"; + public static final Object INPUT_PARAM_VNF_ID = "vnfId"; + public static final Object INPUT_PARAM_VM_NAME = "vmName"; + + public static final String INPUT_PARAM_FILE_ID = "fileId"; + + public static String INPUT_PARAM_UPLOAD_CONFIG_ID= "uploadConfigId"; + public static String CAPABILITY_VM_LEVEL="vm"; + public enum ACTIONS + { + Start, Stop, Restart; + } + + +} diff --git a/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/db/DGGeneralDBService.java b/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/db/DGGeneralDBService.java new file mode 100644 index 000000000..87e5506a2 --- /dev/null +++ b/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/db/DGGeneralDBService.java @@ -0,0 +1,446 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.data.services.db; + +import java.util.Set; + +import org.apache.commons.lang3.StringUtils; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; +import org.onap.ccsdk.sli.adaptors.resource.sql.SqlResource; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class DGGeneralDBService { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(DGGeneralDBService.class); + private SvcLogicResource serviceLogic; + private static DGGeneralDBService dgGeneralDBService = null; + + public static DGGeneralDBService initialise() { + if (dgGeneralDBService == null) { + dgGeneralDBService = new DGGeneralDBService(); + } + return dgGeneralDBService; + } + + private DGGeneralDBService() { + if (serviceLogic == null) { + serviceLogic = new SqlResource(); + } + } + + public QueryStatus getDeviceProtocolByVnfType(SvcLogicContext ctx, String prefix) throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + String key = "SELECT * FROM DEVICE_INTERFACE_PROTOCOL WHERE vnf_type = $vnf-type ;"; + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + } + return status; + } + + public QueryStatus getDeviceAuthenticationByVnfType(SvcLogicContext ctx, String prefix) throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + String key = "SELECT * FROM DEVICE_AUTHENTICATION WHERE vnf_type = $vnf-type ;"; + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + + } + return status; + } + + public QueryStatus getConfigFileReferenceByVnfType(SvcLogicContext ctx, String prefix) throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + String key = "SELECT * FROM CONFIG_FILE_REFERENCE WHERE vnf_type = $vnf-type ;"; + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + } + return status; + } + + public QueryStatus getConfigFileReferenceByFileTypeNVnfType(SvcLogicContext ctx, String prefix, String fileType) + throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + String key = "SELECT * FROM CONFIG_FILE_REFERENCE WHERE file_type = '" + fileType + + "' and vnf_type = $vnf-type ;"; + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + } + return status; + } + + public QueryStatus getTemplate(SvcLogicContext ctx, String prefix, String fileCategory) throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + String key = "SELECT artifact_content file_content , asdc_artifacts_id config_file_id " + + " FROM ASDC_ARTIFACTS " + + " WHERE asdc_artifacts_id = ( SELECT MAX(a.asdc_artifacts_id) configfileid " + + " FROM ASDC_ARTIFACTS a, ASDC_REFERENCE b " + " WHERE a.artifact_name = b.artifact_name " + + " AND file_category = '" + fileCategory + "'" + " AND action = $request-action " + + " AND vnf_type = $vnf-type " + " AND vnfc_type = $vnfc-type ) ; "; + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + } + return status; + } + + public QueryStatus getTemplateByVnfTypeNAction(SvcLogicContext ctx, String prefix, String fileCategory) + throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + String key = "SELECT artifact_content file_content , asdc_artifacts_id config_file_id " + + " FROM ASDC_ARTIFACTS " + + " WHERE asdc_artifacts_id = (SELECT MAX(a.asdc_artifacts_id) configfileid " + + " FROM ASDC_ARTIFACTS a, ASDC_REFERENCE b " + " WHERE a.artifact_name = b.artifact_name " + + " AND file_category = '" + fileCategory + "'" + " AND action = $request-action " + + " AND vnf_type = $vnf-type ) ; "; + + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + } + return status; + } + + public QueryStatus getTemplateByVnfType(SvcLogicContext ctx, String prefix, String fileCategory) + throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + String key = "SELECT artifact_content file_content , asdc_artifacts_id config_file_id " + + " FROM ASDC_ARTIFACTS " + + " WHERE asdc_artifacts_id = (SELECT MAX(a.asdc_artifacts_id) configfileid " + + " FROM ASDC_ARTIFACTS a, ASDC_REFERENCE b " + " WHERE a.artifact_name = b.artifact_name " + + " AND file_category = '" + fileCategory + "'" + " AND vnf_type = $vnf-type ) ; "; + + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + } + return status; + } + + public QueryStatus getTemplateByTemplateName(SvcLogicContext ctx, String prefix, String templateName) + throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + String key = "SELECT artifact_content file_content , asdc_artifacts_id config_file_id " + + " FROM ASDC_ARTIFACTS " + + " WHERE asdc_artifacts_id = (SELECT MAX(asdc_artifacts_id) configfileid " + + " FROM ASDC_ARTIFACTS " + " WHERE artifact_name = '" + templateName + "' ) ; "; + + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + } + return status; + } + + public QueryStatus getConfigureActionDGByVnfTypeNAction(SvcLogicContext ctx, String prefix) + throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + String key = "SELECT * " + " FROM CONFIGURE_ACTION_DG " + + " where vnf_type = $vnf-type and action = $request-action ; "; + + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + } + return status; + } + + public QueryStatus getConfigureActionDGByVnfType(SvcLogicContext ctx, String prefix) throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + String key = "SELECT * " + " FROM CONFIGURE_ACTION_DG " + + " where vnf_type = $vnf-type and action IS NULL ; "; + + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + } + return status; + } + + public QueryStatus getMaxConfigFileId(SvcLogicContext ctx, String prefix, String fileCategory) + throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + String key = "SELECT MAX(config_file_id) configfileid " + " FROM CONFIGFILES " + " WHERE file_category = '" + + fileCategory + "'" + " AND vnf_id = $vnf-id AND vm_name = $vm-name ; "; + + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + } + return status; + } + + public QueryStatus saveConfigFiles(SvcLogicContext ctx, String prefix) throws SvcLogicException { + + QueryStatus status = null; + + if (serviceLogic != null && ctx != null) { + String key = "INSERT INTO CONFIGFILES " + " SET data_source = $data-source , " + + " service_instance_id = $service-instance-id ," + " action = $request-action ," + + " vnf_type = $vnf-type ," + " vnfc_type = $vnfc-type ," + + " vnf_id = $vnf-id , " + " vnf_name = $vnf-name ," + + " vm_name = $vm-name ," + " file_category = $file-category ," + + " file_content = $file-content ; "; + + status = serviceLogic.save("SQL", false, false, key, null, prefix, ctx); + + } + return status; + + } + + public QueryStatus savePrepareRelationship(SvcLogicContext ctx, String prefix, String fileId, String sdcInd) + throws SvcLogicException { + + QueryStatus status = null; + String key = null; + + if (serviceLogic != null && ctx != null) { + + if ("Y".equals(sdcInd)) + + key = "INSERT INTO PREPARE_FILE_RELATIONSHIP " + " SET service_instance_id = $service-instance-id , " + + " request_id = $request-id , " + " asdc_artifacts_id = " + fileId + " ;"; + else + key = "INSERT INTO PREPARE_FILE_RELATIONSHIP " + " SET service_instance_id = $service-instance-id , " + + " request_id = $request-id , " + " config_file_id = " + fileId + " ;"; + + status = serviceLogic.save("SQL", false, false, key, null, prefix, ctx); + + log.info("DGGeneralDBService.savePrepareRelationship()" + ctx.getAttributeKeySet()); + } + return status; + + } + + public void cleanContextPropertyByPrefix(SvcLogicContext ctx, String prefix) { + if (ctx != null && ctx.getAttributeKeySet() != null && StringUtils.isNotBlank(prefix)) { + + Set keySet = ctx.getAttributeKeySet(); + for (String key : keySet) { + if (StringUtils.isNotBlank(key) && key.startsWith(prefix = ".")) { + ctx.getAttributeKeySet().remove(key); + } + } + } + } + + public QueryStatus saveUploadConfig(SvcLogicContext ctx, String prefix) throws SvcLogicException { + + QueryStatus status = null; + + if (serviceLogic != null && ctx != null) { + String key = "INSERT INTO UPLOAD_CONFIG " + " SET request_id = $request-id , " + + " action = $request-action , " + " originator_id = $originator-id , " + " vnf_id = $vnf-id , " + + " vnf_name = $vnf-name , " + " vm_name = $vm-name , " + + " host_ip_address = $vnf-host-ip-address , " + " vnf_type = $vnf-type , " + + " vnfc_type = $vnfc-type , " + " config_indicator = 'Current' , " + + " content = $tmp.escaped.devicerunningconfig ; "; + + status = serviceLogic.save("SQL", false, false, key, null, prefix, ctx); + + log.info("DGGeneralDBService.saveUploadConfig()" + ctx.getAttributeKeySet()); + + } + return status; + + } + + /*public QueryStatus getMaxUploadConfigFileId(SvcLogicContext ctx, String prefix) throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + String key = "SELECT MAX(upload_config_id) uploadconfigid " + " FROM UPLOAD_CONFIG " + + " WHERE vnf_id = $vnf-id AND vm_name = $vm-name ; "; + + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + log.info("DGGeneralDBService.getMaxUploadConfigFileId()" + ctx.getAttributeKeySet()); + } + return status; + }*/ + + public QueryStatus updateUploadConfig(SvcLogicContext ctx, String prefix, int maxId) throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + String key = "UPDATE UPLOAD_CONFIG " + " SET config_indicator = null " + + " WHERE upload_config_id != " + maxId + " AND config_indicator = 'Current' " + + " AND vnf_id = $vnf-id " + " AND vm_name = $vm-name ; "; + + status = serviceLogic.save("SQL", false, false, key, null, prefix, ctx); + + log.info("DGGeneralDBService.updateUploadConfig()" + ctx.getAttributeKeySet()); + + } + return status; + + } + + + public QueryStatus getTemplateByArtifactType(SvcLogicContext ctx, String prefix, String fileCategory, String artifactType) + throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + String key = "SELECT artifact_content file_content , asdc_artifacts_id config_file_id " + + " FROM ASDC_ARTIFACTS " + + " WHERE asdc_artifacts_id = (SELECT MAX(a.asdc_artifacts_id) configfileid " + + " FROM ASDC_ARTIFACTS a, ASDC_REFERENCE b " + " WHERE a.artifact_name = b.artifact_name " + + " AND file_category = '" + fileCategory + "'" + " AND action = $request-action " + + " AND artifactType = '" + artifactType + "'" + " AND vnf_type = $vnf-type ) ; "; + + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + } + return status; + } + + + public QueryStatus getConfigFilesByVnfVmNCategory(SvcLogicContext ctx, String prefix, String fileCategory, String vnfId, String vmName) + throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + + String key = "SELECT file_content , config_file_id " + + " FROM CONFIGFILES " + + " WHERE config_file_id = ( SELECT MAX(config_file_id) configfileid " + " FROM CONFIGFILES " + + " WHERE file_category = '" + fileCategory + "'" + + " AND vnf_id = '" + vnfId + "'" + + " AND vm_name = '" + vmName + "' ) ; "; + + + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + } + return status; + } + + + public QueryStatus getDownloadConfigTemplateByVnf(SvcLogicContext ctx, String prefix) + throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + String key = "SELECT * FROM DOWNLOAD_CONFIG_TEMPLATE WHERE vnf_type = $vnf-type ; "; + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + } + return status; + } + + + + public QueryStatus saveConfigTransactionLog(SvcLogicContext ctx, String prefix) throws SvcLogicException { + + QueryStatus status = null; + + if (serviceLogic != null && ctx != null) { + + + String key = "INSERT INTO CONFIG_TRANSACTION_LOG " + " SET request_id = $request-id , " + + " message_type = $log-message-type , " + + " message = $log-message ;"; + + + status = serviceLogic.save("SQL", false, false, key, null, prefix, ctx); + + + + } + return status; + + } + + + public QueryStatus getVnfcReferenceByVnfcTypeNAction(SvcLogicContext ctx, String prefix) + throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + + String key = "SELECT * " + + " FROM VNFC_REFERENCE " + + " WHERE vnf_type = $vnf-type " + + " AND vnfc_type = $vnfc-type " + + " AND action = $request-action " + + " ORDER BY vm_instance, vnfc_instance ; "; + + + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + } + return status; + } + + + public QueryStatus getVnfcReferenceByVnfTypeNAction(SvcLogicContext ctx, String prefix) + throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + + String key = "SELECT * " + + " FROM VNFC_REFERENCE " + + " WHERE vnf_type = $vnf-type " + + " AND action = $request-action " + + " ORDER BY vm_instance, vnfc_instance ; "; + + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + } + return status; + } + + + public QueryStatus getUploadConfigInfo(SvcLogicContext ctx, String prefix) + throws SvcLogicException { + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + + String key = "SELECT * , UNIX_TIMESTAMP(UPLOAD_DATE) UPLOAD_TIMESTAMP " + + " FROM UPLOAD_CONFIG " + + " WHERE upload_config_id = " + + "( SELECT MAX(upload_config_id) uploadconfigid " + " FROM UPLOAD_CONFIG " + + " WHERE vnf_id = $vnf-id AND vm_name = $vm-name ) ; "; + + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + } + return status; + } + public String getCapability(SvcLogicContext ctx, String vnf_type) throws SvcLogicException { + + //{"capabilities":{"vnfc":[],"vm":[],"vf-module":[],"vnf":["ConfigureTest","ConfigModify","HealthCheck"]}} + String fn = "getCapability "; + QueryStatus status = null; + SvcLogicContext localContext = new SvcLogicContext(); + localContext.setAttribute("vnf-type", vnf_type); + if (serviceLogic != null) { + String queryString = "select max(internal_version) as maxInternalVersion, artifact_name as artifactName from ASDC_ARTIFACTS " + + " where artifact_name in (select artifact_name from ASDC_REFERENCE where vnf_type= $vnf-type " + + " and file_category = 'capability' )" ; + + log.info(fn + "Query String : " + queryString); + status = serviceLogic.query("SQL", false, null, queryString, null, null, localContext); + + if(status.toString().equals("FAILURE")) + throw new SvcLogicException("Error - while getting capabilitiesData "); + + String queryString1 = "select artifact_content from ASDC_ARTIFACTS " + + " where artifact_name = $artifactName and internal_version = $maxInternalVersion "; + + log.debug(fn + "Query String : " + queryString1); + status = serviceLogic.query("SQL", false, null, queryString1, null, null, localContext); + if (status.toString().equals("NOT_FOUND")) + return null; + + if(status.toString().equals("FAILURE")) + throw new SvcLogicException("Error - while getting capabilitiesData "); + } + + return localContext.getAttribute("artifact-content"); + } + +} diff --git a/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/db/GeneralDataService.java b/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/db/GeneralDataService.java new file mode 100644 index 000000000..d0b8726ad --- /dev/null +++ b/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/db/GeneralDataService.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.data.services.db; + +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang3.StringUtils; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; +import org.onap.ccsdk.sli.adaptors.resource.sql.SqlResource; + +import org.onap.appc.data.services.AppcDataServiceConstant; +import org.onap.appc.data.services.utils.EscapeUtils; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class GeneralDataService { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(GeneralDataService.class); + + public void saveTransactionLog(Map inParams, SvcLogicContext ctx) throws SvcLogicException + { + SvcLogicContext logger = new SvcLogicContext(); + String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); + String messageType = inParams.get(AppcDataServiceConstant.INPUT_PARAM_MESSAGE_TYPE); + String message = inParams.get(AppcDataServiceConstant.INPUT_PARAM_MESSAGE); + try + { + + String escapedMessage = EscapeUtils.escapeSql(message); + logger.setAttribute("request-id", ctx.getAttribute("request-id")); + logger.setAttribute("log-message-type", messageType); + logger.setAttribute("log-message", escapedMessage); + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + DGGeneralDBService db = DGGeneralDBService.initialise(); + QueryStatus status = db.saveConfigTransactionLog( logger, responsePrefix); + + logger.setAttribute("log-message", null); + logger.setAttribute("log-message-type", null); + logger.setAttribute("request-id", null); + + if (status == QueryStatus.FAILURE) + throw new Exception("Unable to insert into config_transaction_log"); + + + } + catch (Exception e) + { + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + } + +} diff --git a/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/node/ConfigResourceNode.java b/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/node/ConfigResourceNode.java new file mode 100644 index 000000000..abdb3e85b --- /dev/null +++ b/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/node/ConfigResourceNode.java @@ -0,0 +1,751 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.data.services.node; + +import java.util.Map; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +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.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import org.onap.appc.data.services.AppcDataServiceConstant; +import org.onap.appc.data.services.db.DGGeneralDBService; +import org.onap.appc.data.services.utils.EscapeUtils; + +import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; + +public class ConfigResourceNode implements SvcLogicJavaPlugin { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigResourceNode.class); + + public void getConfigFileReference(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + log.info("Received getConfigFiles call with params : " + inParams); + + String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); + + try { + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + DGGeneralDBService db = DGGeneralDBService.initialise(); + QueryStatus status = db.getConfigFileReferenceByFileTypeNVnfType(ctx, "configfilereference-deviceconfig", + "device_configuration"); + + if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) + throw new Exception("Unable to Read ConfigFileReference:device-configuration"); + + status = db.getConfigFileReferenceByFileTypeNVnfType(ctx, "configfilereference-success", + "configuration_success"); + + if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) + throw new Exception("Unable to Read ConfigFileReference:configuration_success"); + + status = db.getConfigFileReferenceByFileTypeNVnfType(ctx, "configfilereference-failure", + "configuration_error"); + + if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) + throw new Exception("Unable to Read ConfigFileReference:configuration_error"); + + status = db.getConfigFileReferenceByFileTypeNVnfType(ctx, "configfilereference-log", "log"); + + if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) + throw new Exception("Unable to Read ConfigFileReference:configuration_log"); + + + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); + log.info("GetConfigFileReference Successful "); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in GetConfigFileReference " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + public void getCommonConfigInfo(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + log.info("Received getDeviceInfo call with params : " + inParams); + + String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); + + try { + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + DGGeneralDBService db = DGGeneralDBService.initialise(); + QueryStatus status = db.getDeviceAuthenticationByVnfType(ctx, "device-authentication"); + + if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) + throw new Exception("Unable to Read device_authentication"); + + status = db.getDeviceProtocolByVnfType(ctx, "tmp.deviceinterfaceprotocol"); + + if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) + throw new Exception("Unable to Read device_interface_protocol"); + + status = db.getConfigureActionDGByVnfTypeNAction(ctx, "tmp.configureactiondg"); + if (status == QueryStatus.FAILURE) + throw new Exception("Unable to Read configure_action_dg"); + + if (status == QueryStatus.NOT_FOUND) { + status = db.getConfigureActionDGByVnfType(ctx, "tmp.configureactiondg"); + + if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) + throw new Exception("Unable to Read configure_action_dg"); + } + + + + + + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); + log.info("getCommonConfigInfo Successful "); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in getCommonConfigInfo " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + + // fileCategory Can be config_template, parameter_definitions, parameter_yang + public void getTemplate(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + log.info("Received getTemplate call with params : " + inParams); + + + String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); + String fileCategory = inParams.get(AppcDataServiceConstant.INPUT_PARAM_FILE_CATEGORY); + String templateName = ctx.getAttribute("template-name"); + QueryStatus status = null; + String responsePrefix1 = ""; + + try { + + responsePrefix1 = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + log.info("RESPONSEPREFIX : " + responsePrefix); + log.info("RESPONSEPREFIX1 : " + responsePrefix1); + + DGGeneralDBService db = DGGeneralDBService.initialise(); + + if (StringUtils.isBlank(templateName)) { + + //if ( !StringUtils.isBlank(ctx.getAttribute("vnfc-type"))) { + + + status = db.getTemplate(ctx, responsePrefix, fileCategory); + if (status == QueryStatus.FAILURE) + throw new Exception("Unable to Read " + fileCategory ); + //} + + if (status == QueryStatus.NOT_FOUND) { + + + status = db.getTemplateByVnfTypeNAction(ctx, responsePrefix, fileCategory); + + if (status == QueryStatus.FAILURE) + throw new Exception("Unable to Read " + fileCategory ); + + if (status == QueryStatus.NOT_FOUND) { + + //status = db.getTemplateByVnfType(ctx, responsePrefix, fileCategory); + + //if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) + throw new Exception("Unable to Read " + fileCategory ); + } + } + } else { + + status = db.getTemplateByTemplateName(ctx, responsePrefix, templateName); + + if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) + throw new Exception("Unable to Read " + fileCategory + " template"); + } + + + ctx.setAttribute(responsePrefix1 + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); + log.info("GetTemplate Successful "); + } catch (Exception e) { + ctx.setAttribute(responsePrefix1 + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix1 + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in getTemplate " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + public void saveConfigFiles(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + log.info("Received saveConfigFiles call with params : " + inParams); + + String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); + + try { + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + DGGeneralDBService db = DGGeneralDBService.initialise(); + QueryStatus status = db.saveConfigFiles(ctx, "tmp.configFiles"); + + if (status == QueryStatus.FAILURE) + throw new Exception("Unable to Save " + ctx.getAttribute("file-category") + " in configfiles"); + + status = db.getMaxConfigFileId(ctx, "tmp.configfilesmax", ctx.getAttribute("file-category")); + + if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) + throw new Exception("Unable to get " + ctx.getAttribute("file-category") + " from configfiles"); + + status = db.savePrepareRelationship(ctx, "tmp.preparerel", + ctx.getAttribute("tmp.configfilesmax.configfileid"), "N"); + if (status == QueryStatus.FAILURE) + throw new Exception("Unable to save prepare_relationship"); + + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); + log.info("saveConfigFiles Successful "); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in saveConfigFiles " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + public void updateUploadConfig(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + log.info("Received updateUploadConfig call with params : " + inParams); + + String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); + + try { + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + DGGeneralDBService db = DGGeneralDBService.initialise(); + + ctx.setAttribute("tmp.escaped.devicerunningconfig", + EscapeUtils.escapeSql(ctx.getAttribute("device-running-config"))); + + QueryStatus status = db.saveUploadConfig(ctx, "tmp.uploadConfig"); + + if (status == QueryStatus.FAILURE) + throw new Exception("Unable to Save configuration in upload_config"); + + /*status = db.getMaxUploadConfigFileId(ctx, "tmp.uploadconfigmax"); + + if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) + throw new Exception("Unable to get record from upload_config"); + + status = db.updateUploadConfig(ctx, "tmp.uploadConfig", + Integer.parseInt(ctx.getAttribute("tmp.uploadconfigmax.uploadconfigid"))); + if (status == QueryStatus.FAILURE) + throw new Exception("Unable to upload upload_config");*/ + + status = db.getUploadConfigInfo(ctx, "tmp.uploadConfigInfo"); + + if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) + throw new Exception("Unable to get record from upload_config"); + + status = db.updateUploadConfig(ctx, "tmp.uploadConfig", + Integer.parseInt(ctx.getAttribute("tmp.uploadConfigInfo.UPLOAD-CONFIG-ID"))); + if (status == QueryStatus.FAILURE) + throw new Exception("Unable to upload upload_config"); + + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); + log.info("updateUploadConfig Successful "); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in updateUploadConfig " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + public void savePrepareRelationship(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + log.info("Received savePrepareRelationship call with params : " + inParams); + + String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); + String sdcArtifactInd = inParams.get(AppcDataServiceConstant.INPUT_PARAM_SDC_ARTIFACT_IND); + String fileId = inParams.get(AppcDataServiceConstant.INPUT_PARAM_FILE_ID); + try { + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + DGGeneralDBService db = DGGeneralDBService.initialise(); + + QueryStatus status = db.savePrepareRelationship(ctx, "tmp.preparerel", fileId, sdcArtifactInd); + if (status == QueryStatus.FAILURE) + throw new Exception("Unable to save prepare_relationship"); + + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); + log.info("savePrepareRelationship Successful "); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in saveConfigFiles " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + public void saveConfigBlock(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + log.info("Received saveConfigBlock call with params : " + inParams); + + String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); + + try { + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + ctx.setAttribute("tmp.convertconfig.escapeData", + EscapeUtils.escapeSql(ctx.getAttribute("configuration"))); + DGGeneralDBService db = DGGeneralDBService.initialise(); + + if (StringUtils.isBlank(ctx.getAttribute("configuration-params"))) { + saveDeviceConfiguration(inParams, ctx, "Request", ctx.getAttribute("tmp.convertconfig.escapeData"), + ctx.getAttribute("configuration")); + } else { + + saveConfigurationBlock(inParams, ctx); + + ctx.setAttribute("tmp.convertconfig.escapeData", + EscapeUtils.escapeSql(ctx.getAttribute("tmp.merge.mergedData"))); + saveDeviceConfiguration(inParams, ctx, "Configurator", ctx.getAttribute("tmp.convertconfig.escapeData"), + ctx.getAttribute("tmp.merge.mergedData")); + + saveConfigurationData(inParams, ctx); + } + + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); + log.info("saveConfigBlock Successful "); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in saveConfigBlock " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + public void saveTemplateConfig(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + log.info("Received saveTemplateConfig call with params : " + inParams); + + String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); + + try { + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + DGGeneralDBService db = DGGeneralDBService.initialise(); + + if (StringUtils.isBlank(ctx.getAttribute("configuration-params"))) { + + ctx.setAttribute("tmp.convertconfig.escapeData", + EscapeUtils.escapeSql(ctx.getAttribute("config-template.file-content"))); + saveDeviceConfiguration(inParams, ctx, "Template", ctx.getAttribute("tmp.convertconfig.escapeData"), + ctx.getAttribute("config-template.file-content")); + + } else { + saveConfigurationData(inParams, ctx); + + ctx.setAttribute("tmp.convertconfig.escapeData", + EscapeUtils.escapeSql(ctx.getAttribute("tmp.merge.mergedData"))); + saveDeviceConfiguration(inParams, ctx, "Configurator", ctx.getAttribute("tmp.convertconfig.escapeData"), + ctx.getAttribute("tmp.merge.mergedData")); + + } + + QueryStatus status = db.savePrepareRelationship(ctx, "tmp.preparerel", + ctx.getAttribute("config-template.config-file-id"), "Y"); + if (status == QueryStatus.FAILURE) + throw new Exception("Unable to save prepare_relationship"); + + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); + log.info("saveTemplateConfig Successful "); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in saveTemplateConfig " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + + + + public void saveStyleSheetConfig(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + + log.info("Received saveStyleSheet call with params : " + inParams); + + String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); + + try { + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + ctx.setAttribute("tmp.convertconfig.escapeData", + EscapeUtils.escapeSql(ctx.getAttribute("tmp.merge.mergedData"))); + saveDeviceConfiguration(inParams, ctx, "StyleSheet", ctx.getAttribute("tmp.convertconfig.escapeData"), + ctx.getAttribute("tmp.merge.mergedData")); + + + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); + log.info("saveStyleSheet Successful "); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); + log.error("Failed in saveStyleSheet " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + + public void getSmmChainKeyFiles(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + + log.info("Received saveStyleSheet call with params : " + inParams); + + String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); + String siteLocation = ctx.getAttribute("site-location"); + + QueryStatus status = null; + + try{ + + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + DGGeneralDBService db = DGGeneralDBService.initialise(); + + + + status = db.getTemplateByArtifactType(ctx, "smm", "smm", siteLocation); + + if ( status == QueryStatus.FAILURE ) + throw new Exception("Unable to Read smm file"); + + + status = db.getTemplateByArtifactType(ctx, "intermediate-ca-chain", "intermediate_ca_chain", siteLocation); + + if ( status == QueryStatus.FAILURE ) + throw new Exception("Unable to Read intermediate_ca_chain file"); + + + + + status = db.getTemplateByArtifactType(ctx, "server-certificate-and-key", "server_certificate_and_key", siteLocation); + + if ( status == QueryStatus.FAILURE ) + throw new Exception("Unable to Read server_certificate_and_key file"); + + + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); + log.info("saveStyleSheet Successful "); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); + log.error("Failed in saveStyleSheet " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + + public void saveDeviceConfiguration(Map inParams, SvcLogicContext ctx, String dataSource, + String fileContent, String deviceConfig) throws SvcLogicException { + ctx.setAttribute("data-source", dataSource); + ctx.setAttribute("file-content", fileContent); + ctx.setAttribute("file-category", "device_configuration"); + ctx.setAttribute("deviceconfig-file-content", deviceConfig); + + saveConfigFiles(inParams, ctx); + } + + public void saveConfigurationBlock(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + ctx.setAttribute("data-source", "Request"); + ctx.setAttribute("file-content", ctx.getAttribute("tmp.convertconfig.escapeData")); + ctx.setAttribute("file-category", "configuration_block"); + saveConfigFiles(inParams, ctx); + } + + public void saveConfigurationData(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + ctx.setAttribute("data-source", ctx.getAttribute("originator-id")); + ctx.setAttribute("file-content", ctx.getAttribute("configuration-params")); + ctx.setAttribute("file-category", "config_data"); + saveConfigFiles(inParams, ctx); + } + + + public void getConfigFilesByVnfVmNCategory(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + log.info("Received getConfigFilesByVnfVmNCategory call with params : " + inParams); + + String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); + String fileCategory = inParams.get(AppcDataServiceConstant.INPUT_PARAM_FILE_CATEGORY); + String vnfId = inParams.get(AppcDataServiceConstant.INPUT_PARAM_VNF_ID); + String vmName = inParams.get(AppcDataServiceConstant.INPUT_PARAM_VM_NAME); + try { + + + DGGeneralDBService db = DGGeneralDBService.initialise(); + + QueryStatus status = db.getConfigFilesByVnfVmNCategory(ctx, responsePrefix, fileCategory, vnfId, vmName); + + if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) + throw new Exception("Unable to get " + ctx.getAttribute("fileCategory") + " from configfiles"); + + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); + log.info("getConfigFilesByVnfVmNCategory Successful " + ctx.getAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS)); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in getConfigFilesByVnfVmNCategory " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + + public void getDownloadConfigTemplateByVnf(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + log.info("Received getDownloadConfigTemplateByVnfNProtocol call with params : " + inParams); + + String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); + try { + DGGeneralDBService db = DGGeneralDBService.initialise(); + + QueryStatus status = db.getDownloadConfigTemplateByVnf(ctx, responsePrefix); + + if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) + throw new Exception("Unable to get download config template."); + + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); + log.info("getDownloadConfigTemplateByVnf Successful " + ctx.getAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS)); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in getDownloadConfigTemplateByVnf " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + + public void saveConfigTransactionLog(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + + + String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); + + String messageType = inParams.get(AppcDataServiceConstant.INPUT_PARAM_MESSAGE_TYPE); + String message = inParams.get(AppcDataServiceConstant.INPUT_PARAM_MESSAGE); + + try { + + SvcLogicContext logctx = new SvcLogicContext(); + + String escapedMessage = EscapeUtils.escapeSql(message); + + + logctx.setAttribute("request-id", ctx.getAttribute("request-id")); + logctx.setAttribute("log-message-type", messageType); + logctx.setAttribute("log-message", escapedMessage); + + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + DGGeneralDBService db = DGGeneralDBService.initialise(); + QueryStatus status = db.saveConfigTransactionLog( logctx, responsePrefix); + + logctx.setAttribute("log-message", null); + + if (status == QueryStatus.FAILURE) + throw new Exception("Unable to insert into config_transaction_log"); + + + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + + + throw new SvcLogicException(e.getMessage()); + } + } + + + + public void getVnfcReference(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + log.info("Received getVnfcReference call with params : " + inParams); + + String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); + + + QueryStatus status = null; + + try { + + + DGGeneralDBService db = DGGeneralDBService.initialise(); + + if ( !StringUtils.isBlank(ctx.getAttribute("vnfc-type"))) { + status = db.getVnfcReferenceByVnfcTypeNAction(ctx, responsePrefix); + + if ( status == QueryStatus.FAILURE) + throw new Exception("Unable to Read vnfc-reference"); + } + //else if (status == QueryStatus.NOT_FOUND ) { + status = db.getVnfcReferenceByVnfTypeNAction(ctx, responsePrefix); + + if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) + throw new Exception("Unable to Read vnfc reference"); + + //} + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); + log.info("getVnfcReference Successful "); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in getVnfcReference " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + public void getCapability(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + log.info("Received getCapability call with params : " + inParams); + String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + String caplevel = inParams.get("caplevel"); + String findCapability = inParams.get("checkCapability"); + + if (!checkIfCapabilityCheckNeeded(caplevel, findCapability)) + { + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); + log.info("getCapability Successful - No need for capability check for this action"); + return; + } + try { + DGGeneralDBService db = DGGeneralDBService.initialise(); + String cap = db.getCapability(ctx, inParams.get("vnf-type")); + log.info("getCapability::returned from DB::+cap"); + if (StringUtils.isBlank(cap)) { + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); + log.info("getCapability Successful - No capability blocks found"); + return; + } + + ObjectMapper mapper = new ObjectMapper(); + JsonNode caps = mapper.readTree(cap); + log.info("From DB = " + caps); + JsonNode capabilities = caps.get("capabilities"); + log.info("capabilities = " + capabilities); + if(caplevel !=null && !caplevel.isEmpty()){ + JsonNode subCapabilities = capabilities.get(caplevel); + log.info("subCapabilities = " + caplevel + " : " + subCapabilities); + if(findCapability !=null && !findCapability.isEmpty()){ + if(subCapabilities != null && subCapabilities.toString().contains(findCapability)) + ctx.setAttribute(responsePrefix + "capabilities." + caplevel + "." + findCapability, + "Supported"); + else + ctx.setAttribute(responsePrefix + "capabilities." + caplevel + "." + findCapability, + "Not-Supported"); + } + else + { + ctx.setAttribute(responsePrefix + "capabilities." + caplevel, + subCapabilities.toString()); + } + + } + else + ctx.setAttribute(responsePrefix + "capabilities", + capabilities.toString()); + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); + log.info("getCapability Successful "); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, + AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in getCapability " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + public boolean checkIfCapabilityCheckNeeded(String caplevel, String findCapability) { + boolean capabilityCheckNeeded = true; + if (!StringUtils.equalsIgnoreCase(caplevel, AppcDataServiceConstant.CAPABILITY_VM_LEVEL)) { + List actionList = new ArrayList( + Arrays.asList(AppcDataServiceConstant.ACTIONS.values())); + for (AppcDataServiceConstant.ACTIONS action : actionList) { + if (StringUtils.equalsIgnoreCase(action.toString(), findCapability)) { + capabilityCheckNeeded = false; + break; + } + } + } + return capabilityCheckNeeded; + } + + +} diff --git a/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/utils/EscapeUtils.java b/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/utils/EscapeUtils.java new file mode 100644 index 000000000..56e776c7c --- /dev/null +++ b/appc-config/appc-data-services/provider/src/main/java/org/onap/appc/data/services/utils/EscapeUtils.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.data.services.utils; + +import org.apache.commons.lang3.StringUtils; + +public class EscapeUtils { + + public EscapeUtils() { + // TODO Auto-generated constructor stub + } + + public static String escapeSql(String str) { + if (str == null) { + return null; + } + String searchList[] = new String[]{"'","\\"}; + String replacementList[] = new String[]{ "''","\\\\"}; + return StringUtils.replaceEach(str,searchList, replacementList); + } +} diff --git a/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/AppcDataServiceActivator.java b/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/AppcDataServiceActivator.java deleted file mode 100644 index 698924853..000000000 --- a/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/AppcDataServiceActivator.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.data.services; - -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; - -import org.onap.appc.data.services.node.ConfigResourceNode; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class AppcDataServiceActivator implements BundleActivator { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(AppcDataServiceActivator.class); - private List registrations = new LinkedList(); - - @Override - public void start(BundleContext ctx) throws Exception { - - ConfigResourceNode configResourceNode = new ConfigResourceNode(); - log.info("Registering service-- " + configResourceNode.getClass().getName()); - registrations.add(ctx.registerService(configResourceNode.getClass().getName(), configResourceNode, null)); - - - - - } - - @Override - public void stop(BundleContext arg0) throws Exception { - for (ServiceRegistration registration : registrations) { - registration.unregister(); - registration = null; - } - } -} diff --git a/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/AppcDataServiceConstant.java b/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/AppcDataServiceConstant.java deleted file mode 100644 index 9add56b5e..000000000 --- a/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/AppcDataServiceConstant.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.data.services; - -public class AppcDataServiceConstant { - - - - - public static String INPUT_PARAM_RESPONSE_PREFIX = "responsePrefix"; - public static String OUTPUT_STATUS_SUCCESS = "success"; - public static String OUTPUT_STATUS_FAILURE = "failure"; - public static final String INPUT_PARAM_MESSAGE = "message"; - public static final String INPUT_PARAM_MESSAGE_TYPE = "messageType"; - public static String OUTPUT_PARAM_STATUS = "status"; - public static String OUTPUT_PARAM_ERROR_MESSAGE = "error-message"; - public static final String INPUT_PARAM_FILE_CATEGORY = "fileCategory"; - public static final String INPUT_PARAM_VM_INSTANCE = "vmInstance"; - public static final String INPUT_PARAM_SDC_ARTIFACT_IND = "asdcArtifactInd"; - public static final Object INPUT_PARAM_VNF_ID = "vnfId"; - public static final Object INPUT_PARAM_VM_NAME = "vmName"; - - public static final String INPUT_PARAM_FILE_ID = "fileId"; - - public static String INPUT_PARAM_UPLOAD_CONFIG_ID= "uploadConfigId"; - public static String CAPABILITY_VM_LEVEL="vm"; - public enum ACTIONS - { - Start, Stop, Restart; - } - - -} diff --git a/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/db/DGGeneralDBService.java b/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/db/DGGeneralDBService.java deleted file mode 100644 index 87e5506a2..000000000 --- a/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/db/DGGeneralDBService.java +++ /dev/null @@ -1,446 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.data.services.db; - -import java.util.Set; - -import org.apache.commons.lang3.StringUtils; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; -import org.onap.ccsdk.sli.adaptors.resource.sql.SqlResource; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class DGGeneralDBService { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(DGGeneralDBService.class); - private SvcLogicResource serviceLogic; - private static DGGeneralDBService dgGeneralDBService = null; - - public static DGGeneralDBService initialise() { - if (dgGeneralDBService == null) { - dgGeneralDBService = new DGGeneralDBService(); - } - return dgGeneralDBService; - } - - private DGGeneralDBService() { - if (serviceLogic == null) { - serviceLogic = new SqlResource(); - } - } - - public QueryStatus getDeviceProtocolByVnfType(SvcLogicContext ctx, String prefix) throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - String key = "SELECT * FROM DEVICE_INTERFACE_PROTOCOL WHERE vnf_type = $vnf-type ;"; - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - } - return status; - } - - public QueryStatus getDeviceAuthenticationByVnfType(SvcLogicContext ctx, String prefix) throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - String key = "SELECT * FROM DEVICE_AUTHENTICATION WHERE vnf_type = $vnf-type ;"; - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - - } - return status; - } - - public QueryStatus getConfigFileReferenceByVnfType(SvcLogicContext ctx, String prefix) throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - String key = "SELECT * FROM CONFIG_FILE_REFERENCE WHERE vnf_type = $vnf-type ;"; - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - } - return status; - } - - public QueryStatus getConfigFileReferenceByFileTypeNVnfType(SvcLogicContext ctx, String prefix, String fileType) - throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - String key = "SELECT * FROM CONFIG_FILE_REFERENCE WHERE file_type = '" + fileType - + "' and vnf_type = $vnf-type ;"; - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - } - return status; - } - - public QueryStatus getTemplate(SvcLogicContext ctx, String prefix, String fileCategory) throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - String key = "SELECT artifact_content file_content , asdc_artifacts_id config_file_id " - + " FROM ASDC_ARTIFACTS " - + " WHERE asdc_artifacts_id = ( SELECT MAX(a.asdc_artifacts_id) configfileid " - + " FROM ASDC_ARTIFACTS a, ASDC_REFERENCE b " + " WHERE a.artifact_name = b.artifact_name " - + " AND file_category = '" + fileCategory + "'" + " AND action = $request-action " - + " AND vnf_type = $vnf-type " + " AND vnfc_type = $vnfc-type ) ; "; - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - } - return status; - } - - public QueryStatus getTemplateByVnfTypeNAction(SvcLogicContext ctx, String prefix, String fileCategory) - throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - String key = "SELECT artifact_content file_content , asdc_artifacts_id config_file_id " - + " FROM ASDC_ARTIFACTS " - + " WHERE asdc_artifacts_id = (SELECT MAX(a.asdc_artifacts_id) configfileid " - + " FROM ASDC_ARTIFACTS a, ASDC_REFERENCE b " + " WHERE a.artifact_name = b.artifact_name " - + " AND file_category = '" + fileCategory + "'" + " AND action = $request-action " - + " AND vnf_type = $vnf-type ) ; "; - - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - } - return status; - } - - public QueryStatus getTemplateByVnfType(SvcLogicContext ctx, String prefix, String fileCategory) - throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - String key = "SELECT artifact_content file_content , asdc_artifacts_id config_file_id " - + " FROM ASDC_ARTIFACTS " - + " WHERE asdc_artifacts_id = (SELECT MAX(a.asdc_artifacts_id) configfileid " - + " FROM ASDC_ARTIFACTS a, ASDC_REFERENCE b " + " WHERE a.artifact_name = b.artifact_name " - + " AND file_category = '" + fileCategory + "'" + " AND vnf_type = $vnf-type ) ; "; - - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - } - return status; - } - - public QueryStatus getTemplateByTemplateName(SvcLogicContext ctx, String prefix, String templateName) - throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - String key = "SELECT artifact_content file_content , asdc_artifacts_id config_file_id " - + " FROM ASDC_ARTIFACTS " - + " WHERE asdc_artifacts_id = (SELECT MAX(asdc_artifacts_id) configfileid " - + " FROM ASDC_ARTIFACTS " + " WHERE artifact_name = '" + templateName + "' ) ; "; - - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - } - return status; - } - - public QueryStatus getConfigureActionDGByVnfTypeNAction(SvcLogicContext ctx, String prefix) - throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - String key = "SELECT * " + " FROM CONFIGURE_ACTION_DG " - + " where vnf_type = $vnf-type and action = $request-action ; "; - - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - } - return status; - } - - public QueryStatus getConfigureActionDGByVnfType(SvcLogicContext ctx, String prefix) throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - String key = "SELECT * " + " FROM CONFIGURE_ACTION_DG " - + " where vnf_type = $vnf-type and action IS NULL ; "; - - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - } - return status; - } - - public QueryStatus getMaxConfigFileId(SvcLogicContext ctx, String prefix, String fileCategory) - throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - String key = "SELECT MAX(config_file_id) configfileid " + " FROM CONFIGFILES " + " WHERE file_category = '" - + fileCategory + "'" + " AND vnf_id = $vnf-id AND vm_name = $vm-name ; "; - - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - } - return status; - } - - public QueryStatus saveConfigFiles(SvcLogicContext ctx, String prefix) throws SvcLogicException { - - QueryStatus status = null; - - if (serviceLogic != null && ctx != null) { - String key = "INSERT INTO CONFIGFILES " + " SET data_source = $data-source , " - + " service_instance_id = $service-instance-id ," + " action = $request-action ," - + " vnf_type = $vnf-type ," + " vnfc_type = $vnfc-type ," - + " vnf_id = $vnf-id , " + " vnf_name = $vnf-name ," - + " vm_name = $vm-name ," + " file_category = $file-category ," - + " file_content = $file-content ; "; - - status = serviceLogic.save("SQL", false, false, key, null, prefix, ctx); - - } - return status; - - } - - public QueryStatus savePrepareRelationship(SvcLogicContext ctx, String prefix, String fileId, String sdcInd) - throws SvcLogicException { - - QueryStatus status = null; - String key = null; - - if (serviceLogic != null && ctx != null) { - - if ("Y".equals(sdcInd)) - - key = "INSERT INTO PREPARE_FILE_RELATIONSHIP " + " SET service_instance_id = $service-instance-id , " - + " request_id = $request-id , " + " asdc_artifacts_id = " + fileId + " ;"; - else - key = "INSERT INTO PREPARE_FILE_RELATIONSHIP " + " SET service_instance_id = $service-instance-id , " - + " request_id = $request-id , " + " config_file_id = " + fileId + " ;"; - - status = serviceLogic.save("SQL", false, false, key, null, prefix, ctx); - - log.info("DGGeneralDBService.savePrepareRelationship()" + ctx.getAttributeKeySet()); - } - return status; - - } - - public void cleanContextPropertyByPrefix(SvcLogicContext ctx, String prefix) { - if (ctx != null && ctx.getAttributeKeySet() != null && StringUtils.isNotBlank(prefix)) { - - Set keySet = ctx.getAttributeKeySet(); - for (String key : keySet) { - if (StringUtils.isNotBlank(key) && key.startsWith(prefix = ".")) { - ctx.getAttributeKeySet().remove(key); - } - } - } - } - - public QueryStatus saveUploadConfig(SvcLogicContext ctx, String prefix) throws SvcLogicException { - - QueryStatus status = null; - - if (serviceLogic != null && ctx != null) { - String key = "INSERT INTO UPLOAD_CONFIG " + " SET request_id = $request-id , " - + " action = $request-action , " + " originator_id = $originator-id , " + " vnf_id = $vnf-id , " - + " vnf_name = $vnf-name , " + " vm_name = $vm-name , " - + " host_ip_address = $vnf-host-ip-address , " + " vnf_type = $vnf-type , " - + " vnfc_type = $vnfc-type , " + " config_indicator = 'Current' , " - + " content = $tmp.escaped.devicerunningconfig ; "; - - status = serviceLogic.save("SQL", false, false, key, null, prefix, ctx); - - log.info("DGGeneralDBService.saveUploadConfig()" + ctx.getAttributeKeySet()); - - } - return status; - - } - - /*public QueryStatus getMaxUploadConfigFileId(SvcLogicContext ctx, String prefix) throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - String key = "SELECT MAX(upload_config_id) uploadconfigid " + " FROM UPLOAD_CONFIG " - + " WHERE vnf_id = $vnf-id AND vm_name = $vm-name ; "; - - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - log.info("DGGeneralDBService.getMaxUploadConfigFileId()" + ctx.getAttributeKeySet()); - } - return status; - }*/ - - public QueryStatus updateUploadConfig(SvcLogicContext ctx, String prefix, int maxId) throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - String key = "UPDATE UPLOAD_CONFIG " + " SET config_indicator = null " - + " WHERE upload_config_id != " + maxId + " AND config_indicator = 'Current' " - + " AND vnf_id = $vnf-id " + " AND vm_name = $vm-name ; "; - - status = serviceLogic.save("SQL", false, false, key, null, prefix, ctx); - - log.info("DGGeneralDBService.updateUploadConfig()" + ctx.getAttributeKeySet()); - - } - return status; - - } - - - public QueryStatus getTemplateByArtifactType(SvcLogicContext ctx, String prefix, String fileCategory, String artifactType) - throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - String key = "SELECT artifact_content file_content , asdc_artifacts_id config_file_id " - + " FROM ASDC_ARTIFACTS " - + " WHERE asdc_artifacts_id = (SELECT MAX(a.asdc_artifacts_id) configfileid " - + " FROM ASDC_ARTIFACTS a, ASDC_REFERENCE b " + " WHERE a.artifact_name = b.artifact_name " - + " AND file_category = '" + fileCategory + "'" + " AND action = $request-action " - + " AND artifactType = '" + artifactType + "'" + " AND vnf_type = $vnf-type ) ; "; - - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - } - return status; - } - - - public QueryStatus getConfigFilesByVnfVmNCategory(SvcLogicContext ctx, String prefix, String fileCategory, String vnfId, String vmName) - throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - - String key = "SELECT file_content , config_file_id " - + " FROM CONFIGFILES " - + " WHERE config_file_id = ( SELECT MAX(config_file_id) configfileid " + " FROM CONFIGFILES " - + " WHERE file_category = '" + fileCategory + "'" - + " AND vnf_id = '" + vnfId + "'" - + " AND vm_name = '" + vmName + "' ) ; "; - - - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - } - return status; - } - - - public QueryStatus getDownloadConfigTemplateByVnf(SvcLogicContext ctx, String prefix) - throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - String key = "SELECT * FROM DOWNLOAD_CONFIG_TEMPLATE WHERE vnf_type = $vnf-type ; "; - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - } - return status; - } - - - - public QueryStatus saveConfigTransactionLog(SvcLogicContext ctx, String prefix) throws SvcLogicException { - - QueryStatus status = null; - - if (serviceLogic != null && ctx != null) { - - - String key = "INSERT INTO CONFIG_TRANSACTION_LOG " + " SET request_id = $request-id , " - + " message_type = $log-message-type , " - + " message = $log-message ;"; - - - status = serviceLogic.save("SQL", false, false, key, null, prefix, ctx); - - - - } - return status; - - } - - - public QueryStatus getVnfcReferenceByVnfcTypeNAction(SvcLogicContext ctx, String prefix) - throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - - String key = "SELECT * " - + " FROM VNFC_REFERENCE " - + " WHERE vnf_type = $vnf-type " - + " AND vnfc_type = $vnfc-type " - + " AND action = $request-action " - + " ORDER BY vm_instance, vnfc_instance ; "; - - - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - } - return status; - } - - - public QueryStatus getVnfcReferenceByVnfTypeNAction(SvcLogicContext ctx, String prefix) - throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - - String key = "SELECT * " - + " FROM VNFC_REFERENCE " - + " WHERE vnf_type = $vnf-type " - + " AND action = $request-action " - + " ORDER BY vm_instance, vnfc_instance ; "; - - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - } - return status; - } - - - public QueryStatus getUploadConfigInfo(SvcLogicContext ctx, String prefix) - throws SvcLogicException { - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - - String key = "SELECT * , UNIX_TIMESTAMP(UPLOAD_DATE) UPLOAD_TIMESTAMP " - + " FROM UPLOAD_CONFIG " - + " WHERE upload_config_id = " + - "( SELECT MAX(upload_config_id) uploadconfigid " + " FROM UPLOAD_CONFIG " - + " WHERE vnf_id = $vnf-id AND vm_name = $vm-name ) ; "; - - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - } - return status; - } - public String getCapability(SvcLogicContext ctx, String vnf_type) throws SvcLogicException { - - //{"capabilities":{"vnfc":[],"vm":[],"vf-module":[],"vnf":["ConfigureTest","ConfigModify","HealthCheck"]}} - String fn = "getCapability "; - QueryStatus status = null; - SvcLogicContext localContext = new SvcLogicContext(); - localContext.setAttribute("vnf-type", vnf_type); - if (serviceLogic != null) { - String queryString = "select max(internal_version) as maxInternalVersion, artifact_name as artifactName from ASDC_ARTIFACTS " + - " where artifact_name in (select artifact_name from ASDC_REFERENCE where vnf_type= $vnf-type " + - " and file_category = 'capability' )" ; - - log.info(fn + "Query String : " + queryString); - status = serviceLogic.query("SQL", false, null, queryString, null, null, localContext); - - if(status.toString().equals("FAILURE")) - throw new SvcLogicException("Error - while getting capabilitiesData "); - - String queryString1 = "select artifact_content from ASDC_ARTIFACTS " + - " where artifact_name = $artifactName and internal_version = $maxInternalVersion "; - - log.debug(fn + "Query String : " + queryString1); - status = serviceLogic.query("SQL", false, null, queryString1, null, null, localContext); - if (status.toString().equals("NOT_FOUND")) - return null; - - if(status.toString().equals("FAILURE")) - throw new SvcLogicException("Error - while getting capabilitiesData "); - } - - return localContext.getAttribute("artifact-content"); - } - -} diff --git a/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/db/GeneralDataService.java b/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/db/GeneralDataService.java deleted file mode 100644 index d0b8726ad..000000000 --- a/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/db/GeneralDataService.java +++ /dev/null @@ -1,80 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.data.services.db; - -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang3.StringUtils; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; -import org.onap.ccsdk.sli.adaptors.resource.sql.SqlResource; - -import org.onap.appc.data.services.AppcDataServiceConstant; -import org.onap.appc.data.services.utils.EscapeUtils; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class GeneralDataService { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(GeneralDataService.class); - - public void saveTransactionLog(Map inParams, SvcLogicContext ctx) throws SvcLogicException - { - SvcLogicContext logger = new SvcLogicContext(); - String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); - String messageType = inParams.get(AppcDataServiceConstant.INPUT_PARAM_MESSAGE_TYPE); - String message = inParams.get(AppcDataServiceConstant.INPUT_PARAM_MESSAGE); - try - { - - String escapedMessage = EscapeUtils.escapeSql(message); - logger.setAttribute("request-id", ctx.getAttribute("request-id")); - logger.setAttribute("log-message-type", messageType); - logger.setAttribute("log-message", escapedMessage); - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - DGGeneralDBService db = DGGeneralDBService.initialise(); - QueryStatus status = db.saveConfigTransactionLog( logger, responsePrefix); - - logger.setAttribute("log-message", null); - logger.setAttribute("log-message-type", null); - logger.setAttribute("request-id", null); - - if (status == QueryStatus.FAILURE) - throw new Exception("Unable to insert into config_transaction_log"); - - - } - catch (Exception e) - { - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - } - -} diff --git a/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/node/ConfigResourceNode.java b/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/node/ConfigResourceNode.java deleted file mode 100644 index abdb3e85b..000000000 --- a/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/node/ConfigResourceNode.java +++ /dev/null @@ -1,751 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.data.services.node; - -import java.util.Map; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -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.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import org.onap.appc.data.services.AppcDataServiceConstant; -import org.onap.appc.data.services.db.DGGeneralDBService; -import org.onap.appc.data.services.utils.EscapeUtils; - -import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; - -public class ConfigResourceNode implements SvcLogicJavaPlugin { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigResourceNode.class); - - public void getConfigFileReference(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - log.info("Received getConfigFiles call with params : " + inParams); - - String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); - - try { - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - DGGeneralDBService db = DGGeneralDBService.initialise(); - QueryStatus status = db.getConfigFileReferenceByFileTypeNVnfType(ctx, "configfilereference-deviceconfig", - "device_configuration"); - - if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) - throw new Exception("Unable to Read ConfigFileReference:device-configuration"); - - status = db.getConfigFileReferenceByFileTypeNVnfType(ctx, "configfilereference-success", - "configuration_success"); - - if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) - throw new Exception("Unable to Read ConfigFileReference:configuration_success"); - - status = db.getConfigFileReferenceByFileTypeNVnfType(ctx, "configfilereference-failure", - "configuration_error"); - - if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) - throw new Exception("Unable to Read ConfigFileReference:configuration_error"); - - status = db.getConfigFileReferenceByFileTypeNVnfType(ctx, "configfilereference-log", "log"); - - if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) - throw new Exception("Unable to Read ConfigFileReference:configuration_log"); - - - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); - log.info("GetConfigFileReference Successful "); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in GetConfigFileReference " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - public void getCommonConfigInfo(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - log.info("Received getDeviceInfo call with params : " + inParams); - - String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); - - try { - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - DGGeneralDBService db = DGGeneralDBService.initialise(); - QueryStatus status = db.getDeviceAuthenticationByVnfType(ctx, "device-authentication"); - - if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) - throw new Exception("Unable to Read device_authentication"); - - status = db.getDeviceProtocolByVnfType(ctx, "tmp.deviceinterfaceprotocol"); - - if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) - throw new Exception("Unable to Read device_interface_protocol"); - - status = db.getConfigureActionDGByVnfTypeNAction(ctx, "tmp.configureactiondg"); - if (status == QueryStatus.FAILURE) - throw new Exception("Unable to Read configure_action_dg"); - - if (status == QueryStatus.NOT_FOUND) { - status = db.getConfigureActionDGByVnfType(ctx, "tmp.configureactiondg"); - - if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) - throw new Exception("Unable to Read configure_action_dg"); - } - - - - - - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); - log.info("getCommonConfigInfo Successful "); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in getCommonConfigInfo " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - - // fileCategory Can be config_template, parameter_definitions, parameter_yang - public void getTemplate(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - log.info("Received getTemplate call with params : " + inParams); - - - String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); - String fileCategory = inParams.get(AppcDataServiceConstant.INPUT_PARAM_FILE_CATEGORY); - String templateName = ctx.getAttribute("template-name"); - QueryStatus status = null; - String responsePrefix1 = ""; - - try { - - responsePrefix1 = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - log.info("RESPONSEPREFIX : " + responsePrefix); - log.info("RESPONSEPREFIX1 : " + responsePrefix1); - - DGGeneralDBService db = DGGeneralDBService.initialise(); - - if (StringUtils.isBlank(templateName)) { - - //if ( !StringUtils.isBlank(ctx.getAttribute("vnfc-type"))) { - - - status = db.getTemplate(ctx, responsePrefix, fileCategory); - if (status == QueryStatus.FAILURE) - throw new Exception("Unable to Read " + fileCategory ); - //} - - if (status == QueryStatus.NOT_FOUND) { - - - status = db.getTemplateByVnfTypeNAction(ctx, responsePrefix, fileCategory); - - if (status == QueryStatus.FAILURE) - throw new Exception("Unable to Read " + fileCategory ); - - if (status == QueryStatus.NOT_FOUND) { - - //status = db.getTemplateByVnfType(ctx, responsePrefix, fileCategory); - - //if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) - throw new Exception("Unable to Read " + fileCategory ); - } - } - } else { - - status = db.getTemplateByTemplateName(ctx, responsePrefix, templateName); - - if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) - throw new Exception("Unable to Read " + fileCategory + " template"); - } - - - ctx.setAttribute(responsePrefix1 + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); - log.info("GetTemplate Successful "); - } catch (Exception e) { - ctx.setAttribute(responsePrefix1 + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix1 + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in getTemplate " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - public void saveConfigFiles(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - log.info("Received saveConfigFiles call with params : " + inParams); - - String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); - - try { - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - DGGeneralDBService db = DGGeneralDBService.initialise(); - QueryStatus status = db.saveConfigFiles(ctx, "tmp.configFiles"); - - if (status == QueryStatus.FAILURE) - throw new Exception("Unable to Save " + ctx.getAttribute("file-category") + " in configfiles"); - - status = db.getMaxConfigFileId(ctx, "tmp.configfilesmax", ctx.getAttribute("file-category")); - - if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) - throw new Exception("Unable to get " + ctx.getAttribute("file-category") + " from configfiles"); - - status = db.savePrepareRelationship(ctx, "tmp.preparerel", - ctx.getAttribute("tmp.configfilesmax.configfileid"), "N"); - if (status == QueryStatus.FAILURE) - throw new Exception("Unable to save prepare_relationship"); - - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); - log.info("saveConfigFiles Successful "); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in saveConfigFiles " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - public void updateUploadConfig(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - log.info("Received updateUploadConfig call with params : " + inParams); - - String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); - - try { - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - DGGeneralDBService db = DGGeneralDBService.initialise(); - - ctx.setAttribute("tmp.escaped.devicerunningconfig", - EscapeUtils.escapeSql(ctx.getAttribute("device-running-config"))); - - QueryStatus status = db.saveUploadConfig(ctx, "tmp.uploadConfig"); - - if (status == QueryStatus.FAILURE) - throw new Exception("Unable to Save configuration in upload_config"); - - /*status = db.getMaxUploadConfigFileId(ctx, "tmp.uploadconfigmax"); - - if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) - throw new Exception("Unable to get record from upload_config"); - - status = db.updateUploadConfig(ctx, "tmp.uploadConfig", - Integer.parseInt(ctx.getAttribute("tmp.uploadconfigmax.uploadconfigid"))); - if (status == QueryStatus.FAILURE) - throw new Exception("Unable to upload upload_config");*/ - - status = db.getUploadConfigInfo(ctx, "tmp.uploadConfigInfo"); - - if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) - throw new Exception("Unable to get record from upload_config"); - - status = db.updateUploadConfig(ctx, "tmp.uploadConfig", - Integer.parseInt(ctx.getAttribute("tmp.uploadConfigInfo.UPLOAD-CONFIG-ID"))); - if (status == QueryStatus.FAILURE) - throw new Exception("Unable to upload upload_config"); - - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); - log.info("updateUploadConfig Successful "); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in updateUploadConfig " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - public void savePrepareRelationship(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - log.info("Received savePrepareRelationship call with params : " + inParams); - - String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); - String sdcArtifactInd = inParams.get(AppcDataServiceConstant.INPUT_PARAM_SDC_ARTIFACT_IND); - String fileId = inParams.get(AppcDataServiceConstant.INPUT_PARAM_FILE_ID); - try { - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - DGGeneralDBService db = DGGeneralDBService.initialise(); - - QueryStatus status = db.savePrepareRelationship(ctx, "tmp.preparerel", fileId, sdcArtifactInd); - if (status == QueryStatus.FAILURE) - throw new Exception("Unable to save prepare_relationship"); - - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); - log.info("savePrepareRelationship Successful "); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in saveConfigFiles " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - public void saveConfigBlock(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - log.info("Received saveConfigBlock call with params : " + inParams); - - String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); - - try { - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - ctx.setAttribute("tmp.convertconfig.escapeData", - EscapeUtils.escapeSql(ctx.getAttribute("configuration"))); - DGGeneralDBService db = DGGeneralDBService.initialise(); - - if (StringUtils.isBlank(ctx.getAttribute("configuration-params"))) { - saveDeviceConfiguration(inParams, ctx, "Request", ctx.getAttribute("tmp.convertconfig.escapeData"), - ctx.getAttribute("configuration")); - } else { - - saveConfigurationBlock(inParams, ctx); - - ctx.setAttribute("tmp.convertconfig.escapeData", - EscapeUtils.escapeSql(ctx.getAttribute("tmp.merge.mergedData"))); - saveDeviceConfiguration(inParams, ctx, "Configurator", ctx.getAttribute("tmp.convertconfig.escapeData"), - ctx.getAttribute("tmp.merge.mergedData")); - - saveConfigurationData(inParams, ctx); - } - - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); - log.info("saveConfigBlock Successful "); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in saveConfigBlock " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - public void saveTemplateConfig(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - log.info("Received saveTemplateConfig call with params : " + inParams); - - String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); - - try { - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - DGGeneralDBService db = DGGeneralDBService.initialise(); - - if (StringUtils.isBlank(ctx.getAttribute("configuration-params"))) { - - ctx.setAttribute("tmp.convertconfig.escapeData", - EscapeUtils.escapeSql(ctx.getAttribute("config-template.file-content"))); - saveDeviceConfiguration(inParams, ctx, "Template", ctx.getAttribute("tmp.convertconfig.escapeData"), - ctx.getAttribute("config-template.file-content")); - - } else { - saveConfigurationData(inParams, ctx); - - ctx.setAttribute("tmp.convertconfig.escapeData", - EscapeUtils.escapeSql(ctx.getAttribute("tmp.merge.mergedData"))); - saveDeviceConfiguration(inParams, ctx, "Configurator", ctx.getAttribute("tmp.convertconfig.escapeData"), - ctx.getAttribute("tmp.merge.mergedData")); - - } - - QueryStatus status = db.savePrepareRelationship(ctx, "tmp.preparerel", - ctx.getAttribute("config-template.config-file-id"), "Y"); - if (status == QueryStatus.FAILURE) - throw new Exception("Unable to save prepare_relationship"); - - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); - log.info("saveTemplateConfig Successful "); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in saveTemplateConfig " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - - - - public void saveStyleSheetConfig(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - - log.info("Received saveStyleSheet call with params : " + inParams); - - String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); - - try { - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - ctx.setAttribute("tmp.convertconfig.escapeData", - EscapeUtils.escapeSql(ctx.getAttribute("tmp.merge.mergedData"))); - saveDeviceConfiguration(inParams, ctx, "StyleSheet", ctx.getAttribute("tmp.convertconfig.escapeData"), - ctx.getAttribute("tmp.merge.mergedData")); - - - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); - log.info("saveStyleSheet Successful "); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); - log.error("Failed in saveStyleSheet " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - - public void getSmmChainKeyFiles(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - - log.info("Received saveStyleSheet call with params : " + inParams); - - String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); - String siteLocation = ctx.getAttribute("site-location"); - - QueryStatus status = null; - - try{ - - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - DGGeneralDBService db = DGGeneralDBService.initialise(); - - - - status = db.getTemplateByArtifactType(ctx, "smm", "smm", siteLocation); - - if ( status == QueryStatus.FAILURE ) - throw new Exception("Unable to Read smm file"); - - - status = db.getTemplateByArtifactType(ctx, "intermediate-ca-chain", "intermediate_ca_chain", siteLocation); - - if ( status == QueryStatus.FAILURE ) - throw new Exception("Unable to Read intermediate_ca_chain file"); - - - - - status = db.getTemplateByArtifactType(ctx, "server-certificate-and-key", "server_certificate_and_key", siteLocation); - - if ( status == QueryStatus.FAILURE ) - throw new Exception("Unable to Read server_certificate_and_key file"); - - - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); - log.info("saveStyleSheet Successful "); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE,e.getMessage()); - log.error("Failed in saveStyleSheet " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - - public void saveDeviceConfiguration(Map inParams, SvcLogicContext ctx, String dataSource, - String fileContent, String deviceConfig) throws SvcLogicException { - ctx.setAttribute("data-source", dataSource); - ctx.setAttribute("file-content", fileContent); - ctx.setAttribute("file-category", "device_configuration"); - ctx.setAttribute("deviceconfig-file-content", deviceConfig); - - saveConfigFiles(inParams, ctx); - } - - public void saveConfigurationBlock(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - ctx.setAttribute("data-source", "Request"); - ctx.setAttribute("file-content", ctx.getAttribute("tmp.convertconfig.escapeData")); - ctx.setAttribute("file-category", "configuration_block"); - saveConfigFiles(inParams, ctx); - } - - public void saveConfigurationData(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - ctx.setAttribute("data-source", ctx.getAttribute("originator-id")); - ctx.setAttribute("file-content", ctx.getAttribute("configuration-params")); - ctx.setAttribute("file-category", "config_data"); - saveConfigFiles(inParams, ctx); - } - - - public void getConfigFilesByVnfVmNCategory(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - log.info("Received getConfigFilesByVnfVmNCategory call with params : " + inParams); - - String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); - String fileCategory = inParams.get(AppcDataServiceConstant.INPUT_PARAM_FILE_CATEGORY); - String vnfId = inParams.get(AppcDataServiceConstant.INPUT_PARAM_VNF_ID); - String vmName = inParams.get(AppcDataServiceConstant.INPUT_PARAM_VM_NAME); - try { - - - DGGeneralDBService db = DGGeneralDBService.initialise(); - - QueryStatus status = db.getConfigFilesByVnfVmNCategory(ctx, responsePrefix, fileCategory, vnfId, vmName); - - if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) - throw new Exception("Unable to get " + ctx.getAttribute("fileCategory") + " from configfiles"); - - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); - log.info("getConfigFilesByVnfVmNCategory Successful " + ctx.getAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS)); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in getConfigFilesByVnfVmNCategory " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - - public void getDownloadConfigTemplateByVnf(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - log.info("Received getDownloadConfigTemplateByVnfNProtocol call with params : " + inParams); - - String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); - try { - DGGeneralDBService db = DGGeneralDBService.initialise(); - - QueryStatus status = db.getDownloadConfigTemplateByVnf(ctx, responsePrefix); - - if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) - throw new Exception("Unable to get download config template."); - - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); - log.info("getDownloadConfigTemplateByVnf Successful " + ctx.getAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS)); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in getDownloadConfigTemplateByVnf " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - - public void saveConfigTransactionLog(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - - - String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); - - String messageType = inParams.get(AppcDataServiceConstant.INPUT_PARAM_MESSAGE_TYPE); - String message = inParams.get(AppcDataServiceConstant.INPUT_PARAM_MESSAGE); - - try { - - SvcLogicContext logctx = new SvcLogicContext(); - - String escapedMessage = EscapeUtils.escapeSql(message); - - - logctx.setAttribute("request-id", ctx.getAttribute("request-id")); - logctx.setAttribute("log-message-type", messageType); - logctx.setAttribute("log-message", escapedMessage); - - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - DGGeneralDBService db = DGGeneralDBService.initialise(); - QueryStatus status = db.saveConfigTransactionLog( logctx, responsePrefix); - - logctx.setAttribute("log-message", null); - - if (status == QueryStatus.FAILURE) - throw new Exception("Unable to insert into config_transaction_log"); - - - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - - - throw new SvcLogicException(e.getMessage()); - } - } - - - - public void getVnfcReference(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - log.info("Received getVnfcReference call with params : " + inParams); - - String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); - - - QueryStatus status = null; - - try { - - - DGGeneralDBService db = DGGeneralDBService.initialise(); - - if ( !StringUtils.isBlank(ctx.getAttribute("vnfc-type"))) { - status = db.getVnfcReferenceByVnfcTypeNAction(ctx, responsePrefix); - - if ( status == QueryStatus.FAILURE) - throw new Exception("Unable to Read vnfc-reference"); - } - //else if (status == QueryStatus.NOT_FOUND ) { - status = db.getVnfcReferenceByVnfTypeNAction(ctx, responsePrefix); - - if (status == QueryStatus.NOT_FOUND || status == QueryStatus.FAILURE) - throw new Exception("Unable to Read vnfc reference"); - - //} - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); - log.info("getVnfcReference Successful "); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in getVnfcReference " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - public void getCapability(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - log.info("Received getCapability call with params : " + inParams); - String responsePrefix = inParams.get(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX); - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - String caplevel = inParams.get("caplevel"); - String findCapability = inParams.get("checkCapability"); - - if (!checkIfCapabilityCheckNeeded(caplevel, findCapability)) - { - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); - log.info("getCapability Successful - No need for capability check for this action"); - return; - } - try { - DGGeneralDBService db = DGGeneralDBService.initialise(); - String cap = db.getCapability(ctx, inParams.get("vnf-type")); - log.info("getCapability::returned from DB::+cap"); - if (StringUtils.isBlank(cap)) { - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); - log.info("getCapability Successful - No capability blocks found"); - return; - } - - ObjectMapper mapper = new ObjectMapper(); - JsonNode caps = mapper.readTree(cap); - log.info("From DB = " + caps); - JsonNode capabilities = caps.get("capabilities"); - log.info("capabilities = " + capabilities); - if(caplevel !=null && !caplevel.isEmpty()){ - JsonNode subCapabilities = capabilities.get(caplevel); - log.info("subCapabilities = " + caplevel + " : " + subCapabilities); - if(findCapability !=null && !findCapability.isEmpty()){ - if(subCapabilities != null && subCapabilities.toString().contains(findCapability)) - ctx.setAttribute(responsePrefix + "capabilities." + caplevel + "." + findCapability, - "Supported"); - else - ctx.setAttribute(responsePrefix + "capabilities." + caplevel + "." + findCapability, - "Not-Supported"); - } - else - { - ctx.setAttribute(responsePrefix + "capabilities." + caplevel, - subCapabilities.toString()); - } - - } - else - ctx.setAttribute(responsePrefix + "capabilities", - capabilities.toString()); - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_SUCCESS); - log.info("getCapability Successful "); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_STATUS, - AppcDataServiceConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcDataServiceConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in getCapability " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - public boolean checkIfCapabilityCheckNeeded(String caplevel, String findCapability) { - boolean capabilityCheckNeeded = true; - if (!StringUtils.equalsIgnoreCase(caplevel, AppcDataServiceConstant.CAPABILITY_VM_LEVEL)) { - List actionList = new ArrayList( - Arrays.asList(AppcDataServiceConstant.ACTIONS.values())); - for (AppcDataServiceConstant.ACTIONS action : actionList) { - if (StringUtils.equalsIgnoreCase(action.toString(), findCapability)) { - capabilityCheckNeeded = false; - break; - } - } - } - return capabilityCheckNeeded; - } - - -} diff --git a/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/utils/EscapeUtils.java b/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/utils/EscapeUtils.java deleted file mode 100644 index 56e776c7c..000000000 --- a/appc-config/appc-data-services/provider/src/main/java/org/openecomp/appc/data/services/utils/EscapeUtils.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.data.services.utils; - -import org.apache.commons.lang3.StringUtils; - -public class EscapeUtils { - - public EscapeUtils() { - // TODO Auto-generated constructor stub - } - - public static String escapeSql(String str) { - if (str == null) { - return null; - } - String searchList[] = new String[]{"'","\\"}; - String replacementList[] = new String[]{ "''","\\\\"}; - return StringUtils.replaceEach(str,searchList, replacementList); - } -} diff --git a/appc-config/appc-data-services/provider/src/test/java/org/onap/appc/data/services/db/TestConfigResourceNode.java b/appc-config/appc-data-services/provider/src/test/java/org/onap/appc/data/services/db/TestConfigResourceNode.java new file mode 100644 index 000000000..fb44e8799 --- /dev/null +++ b/appc-config/appc-data-services/provider/src/test/java/org/onap/appc/data/services/db/TestConfigResourceNode.java @@ -0,0 +1,170 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.data.services.db; + +import java.util.HashMap; +import java.util.Map; +import static org.junit.Assert.assertFalse; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.appc.data.services.AppcDataServiceConstant; +import org.onap.appc.data.services.node.ConfigResourceNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +public class TestConfigResourceNode { + + @Ignore("Test is taking 60 seconds") + @Test(expected = Exception.class) + public void testgetConfigFileReferenc() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + ConfigResourceNode dbService = new ConfigResourceNode(); + Map map = new HashMap(); + dbService.getConfigFileReference(map, ctx); + } + + @Ignore("Test is taking 60 seconds") + @Test(expected = Exception.class) + public void testgetTemplate() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + ctx.setAttribute(AppcDataServiceConstant.INPUT_PARAM_FILE_CATEGORY, "test"); + ctx.setAttribute(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX, "tmp.test"); + ctx.setAttribute("template-name", "test.json"); + + ConfigResourceNode dbService = new ConfigResourceNode(); + Map map = new HashMap(); + dbService.getTemplate(map, ctx); + + } + + @Ignore("Test is taking 60 seconds") + @Test(expected = Exception.class) + public void testgetVnfcReference() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + ConfigResourceNode dbService = new ConfigResourceNode(); + Map map = new HashMap(); + map.put(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX, "tmp.test"); + dbService.getVnfcReference(map, ctx); + } + + @Ignore("Test is taking 60 seconds") + @Test(expected = Exception.class) + public void testgetSmmChainKeyFiles() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + ctx.setAttribute("site-location","test/location"); + ConfigResourceNode dbService = new ConfigResourceNode(); + Map map = new HashMap(); + map.put(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX, "tmp.test"); + dbService.getSmmChainKeyFiles(map, ctx); + } + + @Ignore("Test is taking 60 seconds") + @Test(expected = Exception.class) + public void testgetDownloadConfigTemplateByVnf() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + ConfigResourceNode dbService = new ConfigResourceNode(); + Map map = new HashMap(); + map.put(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX, "tmp.test"); + dbService.getDownloadConfigTemplateByVnf(map, ctx); + + } + + @Ignore("Test is taking 60 seconds") + @Test(expected = Exception.class) + public void testgetCommonConfigInfo() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + ConfigResourceNode dbService = new ConfigResourceNode(); + Map map = new HashMap(); + dbService.getCommonConfigInfo(map, ctx); + + } + + @Ignore("Test is taking 60 seconds") + @Test(expected = Exception.class) + public void testupdateUploadConfigss() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + ConfigResourceNode dbService = new ConfigResourceNode(); + Map map = new HashMap(); + dbService.updateUploadConfig(map, ctx); + + } + + @Ignore("Test is taking 60 seconds") + @Test(expected = Exception.class) + public void testgetConfigFilesByVnfVmNCategory() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + ConfigResourceNode node = new ConfigResourceNode(); + Map inParams = new HashMap(); + inParams.put(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX, "response-prefix"); + inParams.put(AppcDataServiceConstant.INPUT_PARAM_FILE_CATEGORY, "config_template"); + inParams.put((String) AppcDataServiceConstant.INPUT_PARAM_VNF_ID, "test"); + inParams.put((String) AppcDataServiceConstant.INPUT_PARAM_VM_NAME, "test"); + node.getConfigFilesByVnfVmNCategory(inParams, ctx); + } + + @Ignore("Test is taking 60 seconds") + @Test(expected = Exception.class) + public void testsaveConfigTransactionLog() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + ConfigResourceNode node = new ConfigResourceNode(); + Map inParams = new HashMap(); + inParams.put(AppcDataServiceConstant.INPUT_PARAM_MESSAGE, "testMessage"); + inParams.put(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX, "response-prefix"); + inParams.put(AppcDataServiceConstant.INPUT_PARAM_MESSAGE_TYPE, "testmessage"); + ctx.setAttribute("request-id", "tets-id"); + node.saveConfigTransactionLog(inParams, ctx); + + } + + @Ignore("Test is taking 60 seconds") + @Test(expected = Exception.class) + public void testsaveConfigBlock() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + ConfigResourceNode node = new ConfigResourceNode(); + Map inParams = new HashMap(); + inParams.put(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX, "tmp"); + ctx.setAttribute("configuration", "test"); + ctx.setAttribute("tmp.convertconfig.escapeData", "test"); + ctx.setAttribute("tmp.merge.mergedData", "test"); + node.saveConfigBlock(inParams, ctx); + } + + @Test + public void testcheckIfCapabilityCheckNeeded () throws Exception { + ConfigResourceNode node = new ConfigResourceNode(); + String findCapability="Start"; + String capLevel="vnf"; + boolean result=node.checkIfCapabilityCheckNeeded(capLevel,findCapability); + assertFalse(result); + } + +} diff --git a/appc-config/appc-data-services/provider/src/test/java/org/onap/appc/data/services/db/TestDGGeneralDBService.java b/appc-config/appc-data-services/provider/src/test/java/org/onap/appc/data/services/db/TestDGGeneralDBService.java new file mode 100644 index 000000000..91f05c1d4 --- /dev/null +++ b/appc-config/appc-data-services/provider/src/test/java/org/onap/appc/data/services/db/TestDGGeneralDBService.java @@ -0,0 +1,210 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ +package org.onap.appc.data.services.db; + +import static org.junit.Assert.assertEquals; +import java.io.IOException; +import java.io.InputStream; +import java.util.Enumeration; +import java.util.Properties; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringEscapeUtils; +import org.junit.Test; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; +import org.onap.appc.data.services.db.DGGeneralDBService; + +public class TestDGGeneralDBService { + DGGeneralDBService dbService; + private static String STRING_ENCODING = "utf-8"; + + // @Before + public void setUp() { + Properties props = new Properties(); + InputStream propStr = getClass().getResourceAsStream("/svclogic.properties"); + if (propStr == null) { + System.err.println("src/test/resources/svclogic.properties missing"); + } + try { + props.load(propStr); + propStr.close(); + } catch (Exception e) { + e.printStackTrace(); + System.err.println("Could not initialize properties"); + } + // Add properties to global properties + Enumeration propNames = props.keys(); + while (propNames.hasMoreElements()) { + String propName = (String) propNames.nextElement(); + System.setProperty(propName, props.getProperty(propName)); + } + dbService = DGGeneralDBService.initialise(); + } + + @Test(expected = Exception.class) + public void testGetUploadConfig() throws SvcLogicException { + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("vnf-name", "test"); + ctx.setAttribute("vnf-id", "test"); + QueryStatus status = dbService.getUploadConfigInfo(ctx, "test"); + assertEquals(status, "SUCCESS"); + + } + + @Test(expected = Exception.class) + public void testGetDeviceProtocolByVnfType() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("vnf-type", "test"); + QueryStatus status = dbService.getDeviceProtocolByVnfType(ctx, "test"); + assertEquals(status, "SUCCESS"); + } + + @Test(expected = Exception.class) + public void testGettConfigFileReferenceByFileTypeNVnfType() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("vnf-type", "test"); + QueryStatus status = dbService.getConfigFileReferenceByFileTypeNVnfType(ctx, "test", "device_configuration"); + assertEquals(status, "SUCCESS"); + + } + + @Test(expected = Exception.class) + public void testGetDeviceAuthenticationByVnfType() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("vnf-type", "test"); + QueryStatus status = dbService.getDeviceAuthenticationByVnfType(ctx, "test"); + assertEquals(status, "SUCCESS"); + + } + + @Test(expected = Exception.class) + public void testGetTemplate() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("vnfc-type", "test"); + ctx.setAttribute("request-action", "Configure"); + QueryStatus status = dbService.getTemplate(ctx, "test", "config_template"); + assertEquals(status, "SUCCESS"); + + } + + @Test(expected = Exception.class) + public void testGetTemplateByVnfTypeNAction() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("vnf-type", "test"); + ctx.setAttribute("request-action", "Configure"); + QueryStatus status = dbService.getTemplateByVnfTypeNAction(ctx, "test", "config_template"); + assertEquals(status, "SUCCESS"); + + } + + @Test(expected = Exception.class) + public void testGetTemplateByTemplateName() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("request-action", "Configure"); + ctx.setAttribute("vnf-type", "test"); + QueryStatus status = dbService.getTemplateByTemplateName(ctx, "test", "template.json"); + assertEquals(status, "SUCCESS"); + + } + + @Test(expected = Exception.class) + public void testGetTemplateByVnfType() throws SvcLogicException { + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("vnf-type", "test"); + QueryStatus status = dbService.getTemplateByVnfType(ctx, "test", "config_template"); + assertEquals(status, "SUCCESS"); + + } + + @Test(expected = Exception.class) + public void testGetConfigureActionDGByVnfTypeNAction() throws SvcLogicException { + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("vnf-type", "test"); + ctx.setAttribute("request-action", "ConfigModify"); + QueryStatus status = dbService.getConfigureActionDGByVnfTypeNAction(ctx, "test"); + assertEquals(status, "SUCCESS"); + + } + + @Test(expected = Exception.class) + public void testGetConfigureActionDGByVnfType() throws SvcLogicException { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("vnf-type", "test"); + QueryStatus status = dbService.getConfigureActionDGByVnfType(ctx, "test"); + assertEquals(status, "SUCCESS"); + + } + + @Test(expected = Exception.class) + public void testGetMaxConfigFileId() throws SvcLogicException { + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("vnf-id", "test"); + ctx.setAttribute("vm-name", "test"); + QueryStatus status = dbService.getMaxConfigFileId(ctx, "test", "device_configuration"); + assertEquals(status, "SUCCESS"); + + } + + @Test(expected = Exception.class) + public void testGetConfigFilesByVnfVmNCategory() throws SvcLogicException { + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("vnf-id", "test"); + ctx.setAttribute("vm-name", "test"); + QueryStatus status = dbService.getConfigFilesByVnfVmNCategory(ctx, "test", "device_configuration", "test", + "ibcx0001vm001"); + assertEquals(status, "SUCCESS"); + + } + + @Test(expected = Exception.class) + public void testGetDownloadConfigTemplateByVnf() throws SvcLogicException { + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("vnf-type", "test"); + QueryStatus status = dbService.getDownloadConfigTemplateByVnf(ctx, "test"); + assertEquals(status, "SUCCESS"); + } + + @Test(expected = Exception.class) + public void testSaveConfigTxLog() throws SvcLogicException, IOException { + + SvcLogicContext ctx = new SvcLogicContext(); + String message = IOUtils.toString( + TestDGGeneralDBService.class.getClassLoader().getResourceAsStream("query/message3.txt"), + STRING_ENCODING); + ctx.setAttribute("request-id", "1234"); + String escapedMessage = StringEscapeUtils.escapeSql(message); + ctx.setAttribute("log-message", escapedMessage); + ctx.setAttribute("log-message-type", "request"); + QueryStatus status = dbService.saveConfigTransactionLog(ctx, "test"); + assertEquals(status, "SUCCESS"); + } + +} diff --git a/appc-config/appc-data-services/provider/src/test/java/org/onap/appc/data/services/db/TestSQLSaveQuery.java b/appc-config/appc-data-services/provider/src/test/java/org/onap/appc/data/services/db/TestSQLSaveQuery.java new file mode 100644 index 000000000..2a8115336 --- /dev/null +++ b/appc-config/appc-data-services/provider/src/test/java/org/onap/appc/data/services/db/TestSQLSaveQuery.java @@ -0,0 +1,140 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.data.services.db; + +import java.io.File; +import java.io.IOException; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang.StringEscapeUtils; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class TestSQLSaveQuery { + + private static final Logger LOG = LoggerFactory.getLogger(TestSQLSaveQuery.class); + private static String CRYPT_KEY = ""; + + @Test + public void testSQLSaveQuery() { + try { + String message = FileUtils.readFileToString(new File("src/test/resources/query/sampledata.txt")); + System.out.println("TestSQLSaveQuery.testSQLSaveQuery()" + message); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("request-id", "1234"); + String escapedMessage = StringEscapeUtils.escapeSql(message); + ctx.setAttribute("log_message", escapedMessage); + String key = "INSERT INTO CONFIG_TRANSACTION_LOG " + + " SET request_id = $request-id , message_type = 'request' , message = $log_message ;"; + String resolvedContext = resolveCtxVars(key, ctx); + ctx.setAttribute("log_message", null); + } catch (IOException e) { + + } + + } + + private String resolveCtxVars(String key, SvcLogicContext ctx) { + if (key == null) { + return (null); + } + if (key.startsWith("'") && key.endsWith("'")) { + key = key.substring(1, key.length() - 1); + LOG.debug("Stripped outer single quotes - key is now [" + key + "]"); + } + String[] keyTerms = key.split("\\s+"); + StringBuffer sqlBuffer = new StringBuffer(); + for (int i = 0; i < keyTerms.length; i++) { + sqlBuffer.append(resolveTerm(keyTerms[i], ctx)); + sqlBuffer.append(" "); + } + return (sqlBuffer.toString()); + } + + private String resolveTerm(String term, SvcLogicContext ctx) { + if (term == null) { + return (null); + } + LOG.debug("resolveTerm: term is " + term); + if (term.startsWith("$") && (ctx != null)) { + // Resolve any index variables. + return ("'" + resolveCtxVariable(term.substring(1), ctx) + "'"); + + } else { + return (term); + } + + } + + private String resolveCtxVariable(String ctxVarName, SvcLogicContext ctx) { + + if (ctxVarName.indexOf('[') == -1) { + // Ctx variable contains no arrays + if ("CRYPT_KEY".equals(ctxVarName)) { + // Handle crypt key as special case. If it's set as a context + // variable, use it. Otherwise, use + // configured crypt key. + String cryptKey = ctx.getAttribute(ctxVarName); + if ((cryptKey != null) && (cryptKey.length() > 0)) { + return (cryptKey); + } else { + return (CRYPT_KEY); + } + + } + return (ctx.getAttribute(ctxVarName)); + } + // Resolve any array references + StringBuffer sbuff = new StringBuffer(); + String[] ctxVarParts = ctxVarName.split("\\["); + sbuff.append(ctxVarParts[0]); + for (int i = 1; i < ctxVarParts.length; i++) { + if (ctxVarParts[i].startsWith("$")) { + int endBracketLoc = ctxVarParts[i].indexOf("]"); + if (endBracketLoc == -1) { + // Missing end bracket ... give up parsing + LOG.warn("Variable reference " + ctxVarName + " seems to be missing a ']'"); + return (ctx.getAttribute(ctxVarName)); + } + + String idxVarName = ctxVarParts[i].substring(1, endBracketLoc); + String remainder = ctxVarParts[i].substring(endBracketLoc); + sbuff.append("["); + sbuff.append(ctx.getAttribute(idxVarName)); + sbuff.append(remainder); + + } else { + // Index is not a variable reference + sbuff.append("["); + sbuff.append(ctxVarParts[i]); + } + } + return (ctx.getAttribute(sbuff.toString())); + } + +} diff --git a/appc-config/appc-data-services/provider/src/test/java/org/openecomp/appc/data/services/db/TestConfigResourceNode.java b/appc-config/appc-data-services/provider/src/test/java/org/openecomp/appc/data/services/db/TestConfigResourceNode.java deleted file mode 100644 index fb44e8799..000000000 --- a/appc-config/appc-data-services/provider/src/test/java/org/openecomp/appc/data/services/db/TestConfigResourceNode.java +++ /dev/null @@ -1,170 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.data.services.db; - -import java.util.HashMap; -import java.util.Map; -import static org.junit.Assert.assertFalse; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.appc.data.services.AppcDataServiceConstant; -import org.onap.appc.data.services.node.ConfigResourceNode; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; - -public class TestConfigResourceNode { - - @Ignore("Test is taking 60 seconds") - @Test(expected = Exception.class) - public void testgetConfigFileReferenc() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - ConfigResourceNode dbService = new ConfigResourceNode(); - Map map = new HashMap(); - dbService.getConfigFileReference(map, ctx); - } - - @Ignore("Test is taking 60 seconds") - @Test(expected = Exception.class) - public void testgetTemplate() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - ctx.setAttribute(AppcDataServiceConstant.INPUT_PARAM_FILE_CATEGORY, "test"); - ctx.setAttribute(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX, "tmp.test"); - ctx.setAttribute("template-name", "test.json"); - - ConfigResourceNode dbService = new ConfigResourceNode(); - Map map = new HashMap(); - dbService.getTemplate(map, ctx); - - } - - @Ignore("Test is taking 60 seconds") - @Test(expected = Exception.class) - public void testgetVnfcReference() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - ConfigResourceNode dbService = new ConfigResourceNode(); - Map map = new HashMap(); - map.put(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX, "tmp.test"); - dbService.getVnfcReference(map, ctx); - } - - @Ignore("Test is taking 60 seconds") - @Test(expected = Exception.class) - public void testgetSmmChainKeyFiles() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - ctx.setAttribute("site-location","test/location"); - ConfigResourceNode dbService = new ConfigResourceNode(); - Map map = new HashMap(); - map.put(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX, "tmp.test"); - dbService.getSmmChainKeyFiles(map, ctx); - } - - @Ignore("Test is taking 60 seconds") - @Test(expected = Exception.class) - public void testgetDownloadConfigTemplateByVnf() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - ConfigResourceNode dbService = new ConfigResourceNode(); - Map map = new HashMap(); - map.put(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX, "tmp.test"); - dbService.getDownloadConfigTemplateByVnf(map, ctx); - - } - - @Ignore("Test is taking 60 seconds") - @Test(expected = Exception.class) - public void testgetCommonConfigInfo() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - ConfigResourceNode dbService = new ConfigResourceNode(); - Map map = new HashMap(); - dbService.getCommonConfigInfo(map, ctx); - - } - - @Ignore("Test is taking 60 seconds") - @Test(expected = Exception.class) - public void testupdateUploadConfigss() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - ConfigResourceNode dbService = new ConfigResourceNode(); - Map map = new HashMap(); - dbService.updateUploadConfig(map, ctx); - - } - - @Ignore("Test is taking 60 seconds") - @Test(expected = Exception.class) - public void testgetConfigFilesByVnfVmNCategory() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - ConfigResourceNode node = new ConfigResourceNode(); - Map inParams = new HashMap(); - inParams.put(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX, "response-prefix"); - inParams.put(AppcDataServiceConstant.INPUT_PARAM_FILE_CATEGORY, "config_template"); - inParams.put((String) AppcDataServiceConstant.INPUT_PARAM_VNF_ID, "test"); - inParams.put((String) AppcDataServiceConstant.INPUT_PARAM_VM_NAME, "test"); - node.getConfigFilesByVnfVmNCategory(inParams, ctx); - } - - @Ignore("Test is taking 60 seconds") - @Test(expected = Exception.class) - public void testsaveConfigTransactionLog() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - ConfigResourceNode node = new ConfigResourceNode(); - Map inParams = new HashMap(); - inParams.put(AppcDataServiceConstant.INPUT_PARAM_MESSAGE, "testMessage"); - inParams.put(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX, "response-prefix"); - inParams.put(AppcDataServiceConstant.INPUT_PARAM_MESSAGE_TYPE, "testmessage"); - ctx.setAttribute("request-id", "tets-id"); - node.saveConfigTransactionLog(inParams, ctx); - - } - - @Ignore("Test is taking 60 seconds") - @Test(expected = Exception.class) - public void testsaveConfigBlock() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - ConfigResourceNode node = new ConfigResourceNode(); - Map inParams = new HashMap(); - inParams.put(AppcDataServiceConstant.INPUT_PARAM_RESPONSE_PREFIX, "tmp"); - ctx.setAttribute("configuration", "test"); - ctx.setAttribute("tmp.convertconfig.escapeData", "test"); - ctx.setAttribute("tmp.merge.mergedData", "test"); - node.saveConfigBlock(inParams, ctx); - } - - @Test - public void testcheckIfCapabilityCheckNeeded () throws Exception { - ConfigResourceNode node = new ConfigResourceNode(); - String findCapability="Start"; - String capLevel="vnf"; - boolean result=node.checkIfCapabilityCheckNeeded(capLevel,findCapability); - assertFalse(result); - } - -} diff --git a/appc-config/appc-data-services/provider/src/test/java/org/openecomp/appc/data/services/db/TestDGGeneralDBService.java b/appc-config/appc-data-services/provider/src/test/java/org/openecomp/appc/data/services/db/TestDGGeneralDBService.java deleted file mode 100644 index 91f05c1d4..000000000 --- a/appc-config/appc-data-services/provider/src/test/java/org/openecomp/appc/data/services/db/TestDGGeneralDBService.java +++ /dev/null @@ -1,210 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ -package org.onap.appc.data.services.db; - -import static org.junit.Assert.assertEquals; -import java.io.IOException; -import java.io.InputStream; -import java.util.Enumeration; -import java.util.Properties; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringEscapeUtils; -import org.junit.Test; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; -import org.onap.appc.data.services.db.DGGeneralDBService; - -public class TestDGGeneralDBService { - DGGeneralDBService dbService; - private static String STRING_ENCODING = "utf-8"; - - // @Before - public void setUp() { - Properties props = new Properties(); - InputStream propStr = getClass().getResourceAsStream("/svclogic.properties"); - if (propStr == null) { - System.err.println("src/test/resources/svclogic.properties missing"); - } - try { - props.load(propStr); - propStr.close(); - } catch (Exception e) { - e.printStackTrace(); - System.err.println("Could not initialize properties"); - } - // Add properties to global properties - Enumeration propNames = props.keys(); - while (propNames.hasMoreElements()) { - String propName = (String) propNames.nextElement(); - System.setProperty(propName, props.getProperty(propName)); - } - dbService = DGGeneralDBService.initialise(); - } - - @Test(expected = Exception.class) - public void testGetUploadConfig() throws SvcLogicException { - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("vnf-name", "test"); - ctx.setAttribute("vnf-id", "test"); - QueryStatus status = dbService.getUploadConfigInfo(ctx, "test"); - assertEquals(status, "SUCCESS"); - - } - - @Test(expected = Exception.class) - public void testGetDeviceProtocolByVnfType() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("vnf-type", "test"); - QueryStatus status = dbService.getDeviceProtocolByVnfType(ctx, "test"); - assertEquals(status, "SUCCESS"); - } - - @Test(expected = Exception.class) - public void testGettConfigFileReferenceByFileTypeNVnfType() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("vnf-type", "test"); - QueryStatus status = dbService.getConfigFileReferenceByFileTypeNVnfType(ctx, "test", "device_configuration"); - assertEquals(status, "SUCCESS"); - - } - - @Test(expected = Exception.class) - public void testGetDeviceAuthenticationByVnfType() throws Exception { - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("vnf-type", "test"); - QueryStatus status = dbService.getDeviceAuthenticationByVnfType(ctx, "test"); - assertEquals(status, "SUCCESS"); - - } - - @Test(expected = Exception.class) - public void testGetTemplate() throws Exception { - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("vnfc-type", "test"); - ctx.setAttribute("request-action", "Configure"); - QueryStatus status = dbService.getTemplate(ctx, "test", "config_template"); - assertEquals(status, "SUCCESS"); - - } - - @Test(expected = Exception.class) - public void testGetTemplateByVnfTypeNAction() throws Exception { - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("vnf-type", "test"); - ctx.setAttribute("request-action", "Configure"); - QueryStatus status = dbService.getTemplateByVnfTypeNAction(ctx, "test", "config_template"); - assertEquals(status, "SUCCESS"); - - } - - @Test(expected = Exception.class) - public void testGetTemplateByTemplateName() throws Exception { - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("request-action", "Configure"); - ctx.setAttribute("vnf-type", "test"); - QueryStatus status = dbService.getTemplateByTemplateName(ctx, "test", "template.json"); - assertEquals(status, "SUCCESS"); - - } - - @Test(expected = Exception.class) - public void testGetTemplateByVnfType() throws SvcLogicException { - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("vnf-type", "test"); - QueryStatus status = dbService.getTemplateByVnfType(ctx, "test", "config_template"); - assertEquals(status, "SUCCESS"); - - } - - @Test(expected = Exception.class) - public void testGetConfigureActionDGByVnfTypeNAction() throws SvcLogicException { - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("vnf-type", "test"); - ctx.setAttribute("request-action", "ConfigModify"); - QueryStatus status = dbService.getConfigureActionDGByVnfTypeNAction(ctx, "test"); - assertEquals(status, "SUCCESS"); - - } - - @Test(expected = Exception.class) - public void testGetConfigureActionDGByVnfType() throws SvcLogicException { - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("vnf-type", "test"); - QueryStatus status = dbService.getConfigureActionDGByVnfType(ctx, "test"); - assertEquals(status, "SUCCESS"); - - } - - @Test(expected = Exception.class) - public void testGetMaxConfigFileId() throws SvcLogicException { - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("vnf-id", "test"); - ctx.setAttribute("vm-name", "test"); - QueryStatus status = dbService.getMaxConfigFileId(ctx, "test", "device_configuration"); - assertEquals(status, "SUCCESS"); - - } - - @Test(expected = Exception.class) - public void testGetConfigFilesByVnfVmNCategory() throws SvcLogicException { - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("vnf-id", "test"); - ctx.setAttribute("vm-name", "test"); - QueryStatus status = dbService.getConfigFilesByVnfVmNCategory(ctx, "test", "device_configuration", "test", - "ibcx0001vm001"); - assertEquals(status, "SUCCESS"); - - } - - @Test(expected = Exception.class) - public void testGetDownloadConfigTemplateByVnf() throws SvcLogicException { - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("vnf-type", "test"); - QueryStatus status = dbService.getDownloadConfigTemplateByVnf(ctx, "test"); - assertEquals(status, "SUCCESS"); - } - - @Test(expected = Exception.class) - public void testSaveConfigTxLog() throws SvcLogicException, IOException { - - SvcLogicContext ctx = new SvcLogicContext(); - String message = IOUtils.toString( - TestDGGeneralDBService.class.getClassLoader().getResourceAsStream("query/message3.txt"), - STRING_ENCODING); - ctx.setAttribute("request-id", "1234"); - String escapedMessage = StringEscapeUtils.escapeSql(message); - ctx.setAttribute("log-message", escapedMessage); - ctx.setAttribute("log-message-type", "request"); - QueryStatus status = dbService.saveConfigTransactionLog(ctx, "test"); - assertEquals(status, "SUCCESS"); - } - -} diff --git a/appc-config/appc-data-services/provider/src/test/java/org/openecomp/appc/data/services/db/TestSQLSaveQuery.java b/appc-config/appc-data-services/provider/src/test/java/org/openecomp/appc/data/services/db/TestSQLSaveQuery.java deleted file mode 100644 index 2a8115336..000000000 --- a/appc-config/appc-data-services/provider/src/test/java/org/openecomp/appc/data/services/db/TestSQLSaveQuery.java +++ /dev/null @@ -1,140 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.data.services.db; - -import java.io.File; -import java.io.IOException; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang.StringEscapeUtils; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class TestSQLSaveQuery { - - private static final Logger LOG = LoggerFactory.getLogger(TestSQLSaveQuery.class); - private static String CRYPT_KEY = ""; - - @Test - public void testSQLSaveQuery() { - try { - String message = FileUtils.readFileToString(new File("src/test/resources/query/sampledata.txt")); - System.out.println("TestSQLSaveQuery.testSQLSaveQuery()" + message); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("request-id", "1234"); - String escapedMessage = StringEscapeUtils.escapeSql(message); - ctx.setAttribute("log_message", escapedMessage); - String key = "INSERT INTO CONFIG_TRANSACTION_LOG " - + " SET request_id = $request-id , message_type = 'request' , message = $log_message ;"; - String resolvedContext = resolveCtxVars(key, ctx); - ctx.setAttribute("log_message", null); - } catch (IOException e) { - - } - - } - - private String resolveCtxVars(String key, SvcLogicContext ctx) { - if (key == null) { - return (null); - } - if (key.startsWith("'") && key.endsWith("'")) { - key = key.substring(1, key.length() - 1); - LOG.debug("Stripped outer single quotes - key is now [" + key + "]"); - } - String[] keyTerms = key.split("\\s+"); - StringBuffer sqlBuffer = new StringBuffer(); - for (int i = 0; i < keyTerms.length; i++) { - sqlBuffer.append(resolveTerm(keyTerms[i], ctx)); - sqlBuffer.append(" "); - } - return (sqlBuffer.toString()); - } - - private String resolveTerm(String term, SvcLogicContext ctx) { - if (term == null) { - return (null); - } - LOG.debug("resolveTerm: term is " + term); - if (term.startsWith("$") && (ctx != null)) { - // Resolve any index variables. - return ("'" + resolveCtxVariable(term.substring(1), ctx) + "'"); - - } else { - return (term); - } - - } - - private String resolveCtxVariable(String ctxVarName, SvcLogicContext ctx) { - - if (ctxVarName.indexOf('[') == -1) { - // Ctx variable contains no arrays - if ("CRYPT_KEY".equals(ctxVarName)) { - // Handle crypt key as special case. If it's set as a context - // variable, use it. Otherwise, use - // configured crypt key. - String cryptKey = ctx.getAttribute(ctxVarName); - if ((cryptKey != null) && (cryptKey.length() > 0)) { - return (cryptKey); - } else { - return (CRYPT_KEY); - } - - } - return (ctx.getAttribute(ctxVarName)); - } - // Resolve any array references - StringBuffer sbuff = new StringBuffer(); - String[] ctxVarParts = ctxVarName.split("\\["); - sbuff.append(ctxVarParts[0]); - for (int i = 1; i < ctxVarParts.length; i++) { - if (ctxVarParts[i].startsWith("$")) { - int endBracketLoc = ctxVarParts[i].indexOf("]"); - if (endBracketLoc == -1) { - // Missing end bracket ... give up parsing - LOG.warn("Variable reference " + ctxVarName + " seems to be missing a ']'"); - return (ctx.getAttribute(ctxVarName)); - } - - String idxVarName = ctxVarParts[i].substring(1, endBracketLoc); - String remainder = ctxVarParts[i].substring(endBracketLoc); - sbuff.append("["); - sbuff.append(ctx.getAttribute(idxVarName)); - sbuff.append(remainder); - - } else { - // Index is not a variable reference - sbuff.append("["); - sbuff.append(ctxVarParts[i]); - } - } - return (ctx.getAttribute(sbuff.toString())); - } - -} diff --git a/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/EncryptionToolActivator.java b/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/EncryptionToolActivator.java new file mode 100644 index 000000000..9942ef5ee --- /dev/null +++ b/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/EncryptionToolActivator.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.encryptiontool; + +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; + +import org.onap.appc.encryptiontool.wrapper.EncryptionToolDGWrapper; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class EncryptionToolActivator implements BundleActivator { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(EncryptionToolActivator.class); + private List registrations = new LinkedList(); + + @Override + public void start(BundleContext ctx) throws Exception { + EncryptionToolDGWrapper encryptionToolWrapper = new EncryptionToolDGWrapper(); + log.info("Registering service-- " + encryptionToolWrapper.getClass().getName()); + registrations.add(ctx.registerService(encryptionToolWrapper.getClass().getName(), encryptionToolWrapper, null)); + + } + + @Override + public void stop(BundleContext arg0) throws Exception { + for (ServiceRegistration registration : registrations) { + registration.unregister(); + registration = null; + } + } +} diff --git a/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/Constants.java b/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/Constants.java new file mode 100644 index 000000000..9289b1be5 --- /dev/null +++ b/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/Constants.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.encryptiontool.wrapper; + +public class Constants +{ + + public static final String DBLIB_SERVICE = "org.openecomp.sdnctl.sli.resource.dblib.DBResourceManager"; + public static final String DEVICE_AUTHENTICATION="DEVICE_AUTHENTICATION"; + public static final String SCHEMA_SDNCTL="SDNCTL"; + + private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; + + public static final String APPC_CONFIG_DIR="/opt/app/bvc/properties"; +} diff --git a/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/DbServiceUtil.java b/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/DbServiceUtil.java new file mode 100644 index 000000000..5e5d37e66 --- /dev/null +++ b/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/DbServiceUtil.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.encryptiontool.wrapper; + +import java.io.File; +import java.net.URL; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Properties; + +import javax.sql.rowset.CachedRowSet; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.onap.ccsdk.sli.core.dblib.DBResourceManager; +import org.onap.ccsdk.sli.core.dblib.DbLibService; + +public class DbServiceUtil +{ + private static final Logger log = LoggerFactory + .getLogger(DbServiceUtil.class); + + private static Properties props; + private static DBResourceManager jdbcDataSource = null; + + public static boolean updateDB(String tableName, ArrayList inputArgs, + String scema, String whereClause, String setCluase) throws SQLException + { + String updatePasswordString = "update " + tableName + " set " + setCluase + " where " + whereClause ; + boolean result = jdbcDataSource.writeData(updatePasswordString, inputArgs,Constants.SCHEMA_SDNCTL); + return result; + } + + public static CachedRowSet getData(String tableName, ArrayList argList, String schema, + String getselectData, String getDataClasue ) throws SQLException + { + String selectQuery = "select " + getselectData + "from " + tableName + " where " + getDataClasue ; + CachedRowSet data = jdbcDataSource.getData(selectQuery, argList, schema); + return data; + } + + + public static DBResourceManager initDbLibService() throws Exception + { + props = new Properties(); + File file = new File("/opt/app/bvc/properties/dblib.properties"); + URL propURL = file.toURI().toURL(); + props.load(propURL.openStream()); + jdbcDataSource = new DBResourceManager(props); + return jdbcDataSource; + } + +} diff --git a/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/EncryptionTool.java b/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/EncryptionTool.java new file mode 100644 index 000000000..d05a99be8 --- /dev/null +++ b/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/EncryptionTool.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.encryptiontool.wrapper; + +import java.security.Provider; +import java.security.Provider.Service; +import java.security.Security; + +import org.jasypt.contrib.org.apache.commons.codec_1_3.binary.Base64; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class is used to encapsulate the encryption and decryption support in one place and to + * provide a utility to encrypt and decrypt data. + */ +public class EncryptionTool { + + /** + * The prefix we insert onto any data we encrypt so that we can tell if it is encrpyted later and + * therefore decrypt it + */ + public static final String ENCRYPTED_VALUE_PREFIX = "enc:"; + + /** + * The instance of the encryption utility object + */ + private static EncryptionTool instance = null; + + /** + * The logger for this class. + */ + private static final Logger LOG = LoggerFactory.getLogger(EncryptionTool.class); + + /** + * The secret passphrase (PBE) that we use to perform encryption and decryption. The algorithm we + * are using is a symmetrical cipher. + */ + private static char[] secret = {'C', '_', 'z', 'l', '!', 'K', '!', '4', '?', 'O', 'z', 'E', 'K', 'E', '>', 'U', 'R', + '/', '%', 'Y', '\\', 'f', 'b', '"', 'e', 'n', '{', '"', 'l', 'U', 'F', '+', 'E', '\'', 'R', 'T', 'p', '1', + 'V', '4', 'l', 'a', '9', 'w', 'v', '5', 'Z', '#', 'i', 'V', '"', 'd', 'l', '!', 'L', 'M', 'g', 'L', 'Q', + '{', 'v', 'v', 'K', 'V'}; + + + + /** + * Get an instance of the EncryptionTool + * + * @return The encryption tool to be used + */ + public static final synchronized EncryptionTool getInstance() { + if (instance == null) { + instance = new EncryptionTool(); + } + return instance; + } + + /** + * Create the EncryptionTool instance + */ + private EncryptionTool() { + + StringBuilder sb = new StringBuilder("Found the following security algorithms:"); + for (Provider p : Security.getProviders()) { + for (Service s : p.getServices()) { + String algo = s.getAlgorithm(); + sb.append(String.format("%n -Algorithm [ %s ] in provider [ %s ] and service [ %s ]", algo, p.getName(), + s.getClassName())); + } + } + if (LOG.isDebugEnabled()) { + LOG.debug(sb.toString()); + } + } + + /** + * Decrypt the provided encrypted text + * + * @param cipherText THe cipher text to be decrypted. If the ciphertext is not encrypted, then it is + * returned as is. + * @return the clear test of the (possibly) encrypted value. The original value if the string is not + * encrypted. + */ + public synchronized String decrypt(String cipherText) { + if (isEncrypted(cipherText)) { + String encValue = cipherText.substring(ENCRYPTED_VALUE_PREFIX.length()); + byte[] plainByte = Base64.decodeBase64(encValue.getBytes()); + byte[] decryptByte = xorWithSecret(plainByte); + return new String(decryptByte); + } else { + return cipherText; + } + + } + + /** + * Encrypt the provided clear text + * + * @param clearText The clear text to be encrypted + * @return the encrypted text. If the clear text is empty (null or zero length), then an empty + * string is returned. If the clear text is already encrypted, it is not encrypted again and + * is returned as is. Otherwise, the clear text is encrypted and returned. + */ + public synchronized String encrypt(String clearText) { + if (clearText != null) { + byte[] encByte = xorWithSecret(clearText.getBytes()); + String encryptedValue = new String(Base64.encodeBase64(encByte)); + return ENCRYPTED_VALUE_PREFIX + encryptedValue; + } else { + return null; + } + } + + /** + * Is a value encrypted? A value is considered to be encrypted if it begins with the + * {@linkplain #ENCRYPTED_VALUE_PREFIX encrypted value prefix}. + * + * @param value the value to check. + * @return true/false; + */ + private static boolean isEncrypted(final String value) { + return value != null && value.startsWith(ENCRYPTED_VALUE_PREFIX); + } + + /** + * XORs the input byte array with the secret key, padding 0x0 to the end of the secret key if the + * input is longer and returns a byte array the same size as input + * + * @param inp The byte array to be XORed with secret + * @return A byte array the same size as inp or null if input is null. + */ + private byte[] xorWithSecret(byte[] inp) { + if (inp == null) { + return new byte[0]; + } + + byte[] secretBytes = new String(secret).getBytes(); + int size = inp.length; + + byte[] out = new byte[size]; + for (int i = 0; i < size; i++) { + out[i] = (byte) ((inp[i]) ^ (secretBytes[i % secretBytes.length])); + } + return out; + } + +} diff --git a/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/EncryptionToolDGWrapper.java b/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/EncryptionToolDGWrapper.java new file mode 100644 index 000000000..c30f05033 --- /dev/null +++ b/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/EncryptionToolDGWrapper.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.encryptiontool.wrapper; + +import java.util.Map; + +import org.apache.commons.configuration.PropertiesConfiguration; +import org.apache.commons.lang.StringUtils; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class EncryptionToolDGWrapper implements SvcLogicJavaPlugin { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(EncryptionToolDGWrapper.class); + + public void runEncryption(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + String userName = inParams.get("userName"); + String password = inParams.get("password"); + String vnfType = inParams.get("vnf_type"); + + try { + if (StringUtils.isBlank(userName) || StringUtils.isBlank(password) || StringUtils.isBlank(vnfType)) { + throw new SvcLogicException("username or Password is missing"); + } + + String[] input = new String[] {vnfType, userName, password}; + WrapperEncryptionTool.main(input); + + } catch (Exception e) { + throw new SvcLogicException(e.getMessage()); + } + + } + + public void getProperty(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + String responsePrefix = inParams.get("prefix"); + String propertyName = inParams.get("propertyName"); + + try { + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix + ".") : ""; + PropertiesConfiguration conf = + new PropertiesConfiguration(Constants.APPC_CONFIG_DIR + "/appc_southbound.properties"); + conf.setBasePath(null); + EncryptionTool et = EncryptionTool.getInstance(); + + ctx.setAttribute(responsePrefix + "propertyName", et.decrypt(conf.getProperty(propertyName).toString())); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + "status", "failure"); + ctx.setAttribute(responsePrefix + "error-message", e.getMessage()); + log.info("Caught exception", e); + throw new SvcLogicException(e.getMessage()); + } + } +} diff --git a/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/WrapperEncryptionTool.java b/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/WrapperEncryptionTool.java new file mode 100644 index 000000000..9cc322259 --- /dev/null +++ b/appc-config/appc-encryption-tool/provider/src/main/java/org/onap/appc/encryptiontool/wrapper/WrapperEncryptionTool.java @@ -0,0 +1,129 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.encryptiontool.wrapper; + +import java.util.ArrayList; + +import javax.sql.rowset.CachedRowSet; + +import org.apache.commons.configuration.PropertiesConfiguration; +import org.onap.ccsdk.sli.core.dblib.DBResourceManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class WrapperEncryptionTool { + + private static final Logger log = LoggerFactory.getLogger(WrapperEncryptionTool.class); + + public static void main(String[] args) { + int rowCount = 0; + String vnfType = args[0]; + String user = args[1]; + String password = args[2]; + String action = args[3]; + String port = args[4]; + String url = args[5]; + + if ("".equals(vnfType)) { + log.info("ERROR-VNF_TYPE can not be null"); + return; + } + if ("".equals(user)) { + log.info("ERROR-USER can not be null"); + return; + } + if ("".equals(password)) { + log.info("ERROR-PASSWORD can not be null"); + return; + } + + EncryptionTool et = EncryptionTool.getInstance(); + String enPass = et.encrypt(password); + + if (action != null && !action.isEmpty()) { + updateProperties(user, vnfType, enPass, action, port, url); + return; + } + + ArrayList argList = new ArrayList<>(); + argList.add(vnfType); + argList.add(user); + String clause = " vnfType = ? and user_name = ? "; + String setClause = " password = ? "; + String getselectData = " * "; + DBResourceManager dbResourceManager = null; + try { + dbResourceManager = DbServiceUtil.initDbLibService(); + CachedRowSet data = DbServiceUtil.getData(Constants.DEVICE_AUTHENTICATION, argList,Constants.SCHEMA_SDNCTL, getselectData, clause); + + while (data.next()) { + rowCount++; + } + if (rowCount == 0) + log.info("APPC-MESSAGE: ERROR - No record Found for VNF_TYPE: %, User % ", vnfType, user); + else { + argList.clear(); + argList.add(enPass); + argList.add(vnfType); + argList.add(user); + DbServiceUtil.updateDB(Constants.DEVICE_AUTHENTICATION, argList, Constants.SCHEMA_SDNCTL, clause, + setClause); + log.info("APPC-MESSAGE: Password Updated Successfully"); + } + } catch (Exception e) { + log.info("Caught exception", e); + log.info("APPC-MESSAGE:" + e.getMessage()); + } finally { + if (dbResourceManager != null) { + dbResourceManager.cleanUp(); + } + } + } + + private static void updateProperties(String user, String vnfType, String password, String action, String port, + String url) { + + log.info("Received Inputs User:%s vnfType:%s action:%s", user, vnfType, action); + String property = vnfType + "." + action + "."; + + + try { + PropertiesConfiguration conf = + new PropertiesConfiguration(Constants.APPC_CONFIG_DIR + "/appc_southbound.properties"); + conf.setProperty(property + "user", user); + if (port != null && !port.isEmpty()) + conf.setProperty(property + "port", port); + if (password != null && !password.isEmpty()) + conf.setProperty(property + "password", password); + if (url != null && !url.isEmpty()) + conf.setProperty(property + "url", url); + + conf.save(); + + } catch (Exception e) { + log.info("Caught Exception", e); + } + } +} diff --git a/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/EncryptionToolActivator.java b/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/EncryptionToolActivator.java deleted file mode 100644 index 9942ef5ee..000000000 --- a/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/EncryptionToolActivator.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.encryptiontool; - -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; - -import org.onap.appc.encryptiontool.wrapper.EncryptionToolDGWrapper; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class EncryptionToolActivator implements BundleActivator { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(EncryptionToolActivator.class); - private List registrations = new LinkedList(); - - @Override - public void start(BundleContext ctx) throws Exception { - EncryptionToolDGWrapper encryptionToolWrapper = new EncryptionToolDGWrapper(); - log.info("Registering service-- " + encryptionToolWrapper.getClass().getName()); - registrations.add(ctx.registerService(encryptionToolWrapper.getClass().getName(), encryptionToolWrapper, null)); - - } - - @Override - public void stop(BundleContext arg0) throws Exception { - for (ServiceRegistration registration : registrations) { - registration.unregister(); - registration = null; - } - } -} diff --git a/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/Constants.java b/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/Constants.java deleted file mode 100644 index 9289b1be5..000000000 --- a/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/Constants.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.encryptiontool.wrapper; - -public class Constants -{ - - public static final String DBLIB_SERVICE = "org.openecomp.sdnctl.sli.resource.dblib.DBResourceManager"; - public static final String DEVICE_AUTHENTICATION="DEVICE_AUTHENTICATION"; - public static final String SCHEMA_SDNCTL="SDNCTL"; - - private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; - - public static final String APPC_CONFIG_DIR="/opt/app/bvc/properties"; -} diff --git a/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/DbServiceUtil.java b/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/DbServiceUtil.java deleted file mode 100644 index 5e5d37e66..000000000 --- a/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/DbServiceUtil.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.encryptiontool.wrapper; - -import java.io.File; -import java.net.URL; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Properties; - -import javax.sql.rowset.CachedRowSet; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.onap.ccsdk.sli.core.dblib.DBResourceManager; -import org.onap.ccsdk.sli.core.dblib.DbLibService; - -public class DbServiceUtil -{ - private static final Logger log = LoggerFactory - .getLogger(DbServiceUtil.class); - - private static Properties props; - private static DBResourceManager jdbcDataSource = null; - - public static boolean updateDB(String tableName, ArrayList inputArgs, - String scema, String whereClause, String setCluase) throws SQLException - { - String updatePasswordString = "update " + tableName + " set " + setCluase + " where " + whereClause ; - boolean result = jdbcDataSource.writeData(updatePasswordString, inputArgs,Constants.SCHEMA_SDNCTL); - return result; - } - - public static CachedRowSet getData(String tableName, ArrayList argList, String schema, - String getselectData, String getDataClasue ) throws SQLException - { - String selectQuery = "select " + getselectData + "from " + tableName + " where " + getDataClasue ; - CachedRowSet data = jdbcDataSource.getData(selectQuery, argList, schema); - return data; - } - - - public static DBResourceManager initDbLibService() throws Exception - { - props = new Properties(); - File file = new File("/opt/app/bvc/properties/dblib.properties"); - URL propURL = file.toURI().toURL(); - props.load(propURL.openStream()); - jdbcDataSource = new DBResourceManager(props); - return jdbcDataSource; - } - -} diff --git a/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/EncryptionTool.java b/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/EncryptionTool.java deleted file mode 100644 index d05a99be8..000000000 --- a/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/EncryptionTool.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.encryptiontool.wrapper; - -import java.security.Provider; -import java.security.Provider.Service; -import java.security.Security; - -import org.jasypt.contrib.org.apache.commons.codec_1_3.binary.Base64; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class is used to encapsulate the encryption and decryption support in one place and to - * provide a utility to encrypt and decrypt data. - */ -public class EncryptionTool { - - /** - * The prefix we insert onto any data we encrypt so that we can tell if it is encrpyted later and - * therefore decrypt it - */ - public static final String ENCRYPTED_VALUE_PREFIX = "enc:"; - - /** - * The instance of the encryption utility object - */ - private static EncryptionTool instance = null; - - /** - * The logger for this class. - */ - private static final Logger LOG = LoggerFactory.getLogger(EncryptionTool.class); - - /** - * The secret passphrase (PBE) that we use to perform encryption and decryption. The algorithm we - * are using is a symmetrical cipher. - */ - private static char[] secret = {'C', '_', 'z', 'l', '!', 'K', '!', '4', '?', 'O', 'z', 'E', 'K', 'E', '>', 'U', 'R', - '/', '%', 'Y', '\\', 'f', 'b', '"', 'e', 'n', '{', '"', 'l', 'U', 'F', '+', 'E', '\'', 'R', 'T', 'p', '1', - 'V', '4', 'l', 'a', '9', 'w', 'v', '5', 'Z', '#', 'i', 'V', '"', 'd', 'l', '!', 'L', 'M', 'g', 'L', 'Q', - '{', 'v', 'v', 'K', 'V'}; - - - - /** - * Get an instance of the EncryptionTool - * - * @return The encryption tool to be used - */ - public static final synchronized EncryptionTool getInstance() { - if (instance == null) { - instance = new EncryptionTool(); - } - return instance; - } - - /** - * Create the EncryptionTool instance - */ - private EncryptionTool() { - - StringBuilder sb = new StringBuilder("Found the following security algorithms:"); - for (Provider p : Security.getProviders()) { - for (Service s : p.getServices()) { - String algo = s.getAlgorithm(); - sb.append(String.format("%n -Algorithm [ %s ] in provider [ %s ] and service [ %s ]", algo, p.getName(), - s.getClassName())); - } - } - if (LOG.isDebugEnabled()) { - LOG.debug(sb.toString()); - } - } - - /** - * Decrypt the provided encrypted text - * - * @param cipherText THe cipher text to be decrypted. If the ciphertext is not encrypted, then it is - * returned as is. - * @return the clear test of the (possibly) encrypted value. The original value if the string is not - * encrypted. - */ - public synchronized String decrypt(String cipherText) { - if (isEncrypted(cipherText)) { - String encValue = cipherText.substring(ENCRYPTED_VALUE_PREFIX.length()); - byte[] plainByte = Base64.decodeBase64(encValue.getBytes()); - byte[] decryptByte = xorWithSecret(plainByte); - return new String(decryptByte); - } else { - return cipherText; - } - - } - - /** - * Encrypt the provided clear text - * - * @param clearText The clear text to be encrypted - * @return the encrypted text. If the clear text is empty (null or zero length), then an empty - * string is returned. If the clear text is already encrypted, it is not encrypted again and - * is returned as is. Otherwise, the clear text is encrypted and returned. - */ - public synchronized String encrypt(String clearText) { - if (clearText != null) { - byte[] encByte = xorWithSecret(clearText.getBytes()); - String encryptedValue = new String(Base64.encodeBase64(encByte)); - return ENCRYPTED_VALUE_PREFIX + encryptedValue; - } else { - return null; - } - } - - /** - * Is a value encrypted? A value is considered to be encrypted if it begins with the - * {@linkplain #ENCRYPTED_VALUE_PREFIX encrypted value prefix}. - * - * @param value the value to check. - * @return true/false; - */ - private static boolean isEncrypted(final String value) { - return value != null && value.startsWith(ENCRYPTED_VALUE_PREFIX); - } - - /** - * XORs the input byte array with the secret key, padding 0x0 to the end of the secret key if the - * input is longer and returns a byte array the same size as input - * - * @param inp The byte array to be XORed with secret - * @return A byte array the same size as inp or null if input is null. - */ - private byte[] xorWithSecret(byte[] inp) { - if (inp == null) { - return new byte[0]; - } - - byte[] secretBytes = new String(secret).getBytes(); - int size = inp.length; - - byte[] out = new byte[size]; - for (int i = 0; i < size; i++) { - out[i] = (byte) ((inp[i]) ^ (secretBytes[i % secretBytes.length])); - } - return out; - } - -} diff --git a/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/EncryptionToolDGWrapper.java b/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/EncryptionToolDGWrapper.java deleted file mode 100644 index c30f05033..000000000 --- a/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/EncryptionToolDGWrapper.java +++ /dev/null @@ -1,79 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.encryptiontool.wrapper; - -import java.util.Map; - -import org.apache.commons.configuration.PropertiesConfiguration; -import org.apache.commons.lang.StringUtils; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class EncryptionToolDGWrapper implements SvcLogicJavaPlugin { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(EncryptionToolDGWrapper.class); - - public void runEncryption(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - String userName = inParams.get("userName"); - String password = inParams.get("password"); - String vnfType = inParams.get("vnf_type"); - - try { - if (StringUtils.isBlank(userName) || StringUtils.isBlank(password) || StringUtils.isBlank(vnfType)) { - throw new SvcLogicException("username or Password is missing"); - } - - String[] input = new String[] {vnfType, userName, password}; - WrapperEncryptionTool.main(input); - - } catch (Exception e) { - throw new SvcLogicException(e.getMessage()); - } - - } - - public void getProperty(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - String responsePrefix = inParams.get("prefix"); - String propertyName = inParams.get("propertyName"); - - try { - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix + ".") : ""; - PropertiesConfiguration conf = - new PropertiesConfiguration(Constants.APPC_CONFIG_DIR + "/appc_southbound.properties"); - conf.setBasePath(null); - EncryptionTool et = EncryptionTool.getInstance(); - - ctx.setAttribute(responsePrefix + "propertyName", et.decrypt(conf.getProperty(propertyName).toString())); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + "status", "failure"); - ctx.setAttribute(responsePrefix + "error-message", e.getMessage()); - log.info("Caught exception", e); - throw new SvcLogicException(e.getMessage()); - } - } -} diff --git a/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/WrapperEncryptionTool.java b/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/WrapperEncryptionTool.java deleted file mode 100644 index 9cc322259..000000000 --- a/appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/WrapperEncryptionTool.java +++ /dev/null @@ -1,129 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.encryptiontool.wrapper; - -import java.util.ArrayList; - -import javax.sql.rowset.CachedRowSet; - -import org.apache.commons.configuration.PropertiesConfiguration; -import org.onap.ccsdk.sli.core.dblib.DBResourceManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class WrapperEncryptionTool { - - private static final Logger log = LoggerFactory.getLogger(WrapperEncryptionTool.class); - - public static void main(String[] args) { - int rowCount = 0; - String vnfType = args[0]; - String user = args[1]; - String password = args[2]; - String action = args[3]; - String port = args[4]; - String url = args[5]; - - if ("".equals(vnfType)) { - log.info("ERROR-VNF_TYPE can not be null"); - return; - } - if ("".equals(user)) { - log.info("ERROR-USER can not be null"); - return; - } - if ("".equals(password)) { - log.info("ERROR-PASSWORD can not be null"); - return; - } - - EncryptionTool et = EncryptionTool.getInstance(); - String enPass = et.encrypt(password); - - if (action != null && !action.isEmpty()) { - updateProperties(user, vnfType, enPass, action, port, url); - return; - } - - ArrayList argList = new ArrayList<>(); - argList.add(vnfType); - argList.add(user); - String clause = " vnfType = ? and user_name = ? "; - String setClause = " password = ? "; - String getselectData = " * "; - DBResourceManager dbResourceManager = null; - try { - dbResourceManager = DbServiceUtil.initDbLibService(); - CachedRowSet data = DbServiceUtil.getData(Constants.DEVICE_AUTHENTICATION, argList,Constants.SCHEMA_SDNCTL, getselectData, clause); - - while (data.next()) { - rowCount++; - } - if (rowCount == 0) - log.info("APPC-MESSAGE: ERROR - No record Found for VNF_TYPE: %, User % ", vnfType, user); - else { - argList.clear(); - argList.add(enPass); - argList.add(vnfType); - argList.add(user); - DbServiceUtil.updateDB(Constants.DEVICE_AUTHENTICATION, argList, Constants.SCHEMA_SDNCTL, clause, - setClause); - log.info("APPC-MESSAGE: Password Updated Successfully"); - } - } catch (Exception e) { - log.info("Caught exception", e); - log.info("APPC-MESSAGE:" + e.getMessage()); - } finally { - if (dbResourceManager != null) { - dbResourceManager.cleanUp(); - } - } - } - - private static void updateProperties(String user, String vnfType, String password, String action, String port, - String url) { - - log.info("Received Inputs User:%s vnfType:%s action:%s", user, vnfType, action); - String property = vnfType + "." + action + "."; - - - try { - PropertiesConfiguration conf = - new PropertiesConfiguration(Constants.APPC_CONFIG_DIR + "/appc_southbound.properties"); - conf.setProperty(property + "user", user); - if (port != null && !port.isEmpty()) - conf.setProperty(property + "port", port); - if (password != null && !password.isEmpty()) - conf.setProperty(property + "password", password); - if (url != null && !url.isEmpty()) - conf.setProperty(property + "url", url); - - conf.save(); - - } catch (Exception e) { - log.info("Caught Exception", e); - } - } -} diff --git a/appc-config/appc-encryption-tool/provider/src/test/java/org/onap/appc/encryptiontool/TestEncryptionTool.java b/appc-config/appc-encryption-tool/provider/src/test/java/org/onap/appc/encryptiontool/TestEncryptionTool.java new file mode 100644 index 000000000..5c1d2d17c --- /dev/null +++ b/appc-config/appc-encryption-tool/provider/src/test/java/org/onap/appc/encryptiontool/TestEncryptionTool.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.encryptiontool; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import org.onap.appc.encryptiontool.wrapper.DbServiceUtil; +import org.onap.appc.encryptiontool.wrapper.EncryptionToolDGWrapper; +import org.onap.appc.encryptiontool.wrapper.WrapperEncryptionTool; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class TestEncryptionTool { + + @Test + public void testEncryptionTool() throws Exception{ + String [] input = new String[] {"testVnf_Type","testUser","testPassword11", "testAction1", "8080", "http://localhost:8080/restconf/healthcheck"}; + WrapperEncryptionTool.main(input); + + } +// @Test(expected=Exception.class) + public void testgetPropertyDG() throws Exception{ + EncryptionToolDGWrapper et = new EncryptionToolDGWrapper(); + SvcLogicContext ctx = new SvcLogicContext(); + Map inParams = new HashMap(); + inParams.put("prefix", "test"); + inParams.put("propertyName", "testVnf_Type.testAction1.url"); + et.getProperty(inParams, ctx); + } + @Test(expected=Exception.class) + public void testgetData() throws Exception + { + DbServiceUtil d = new DbServiceUtil(); + ArrayList argList = null; + String schema ="sdnctl"; + String tableName ="dual"; + String getselectData ="123"; + String getDataClasue="123='123'"; + d.getData(tableName, argList, schema, getselectData, getDataClasue); + } + @Test(expected=Exception.class) + public void testupdateDB() throws Exception + { + DbServiceUtil d = new DbServiceUtil(); + String setCluase = null; + String schema ="sdnctl"; + String tableName ="dual"; + ArrayList inputArgs = null; + String whereClause="123='123'"; + d.updateDB(tableName, inputArgs, schema, whereClause, setCluase); + } +} diff --git a/appc-config/appc-encryption-tool/provider/src/test/java/org/openecomp/appc/encryptiontool/TestEncryptionTool.java b/appc-config/appc-encryption-tool/provider/src/test/java/org/openecomp/appc/encryptiontool/TestEncryptionTool.java deleted file mode 100644 index 5c1d2d17c..000000000 --- a/appc-config/appc-encryption-tool/provider/src/test/java/org/openecomp/appc/encryptiontool/TestEncryptionTool.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.encryptiontool; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import org.junit.Test; -import org.onap.appc.encryptiontool.wrapper.DbServiceUtil; -import org.onap.appc.encryptiontool.wrapper.EncryptionToolDGWrapper; -import org.onap.appc.encryptiontool.wrapper.WrapperEncryptionTool; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class TestEncryptionTool { - - @Test - public void testEncryptionTool() throws Exception{ - String [] input = new String[] {"testVnf_Type","testUser","testPassword11", "testAction1", "8080", "http://localhost:8080/restconf/healthcheck"}; - WrapperEncryptionTool.main(input); - - } -// @Test(expected=Exception.class) - public void testgetPropertyDG() throws Exception{ - EncryptionToolDGWrapper et = new EncryptionToolDGWrapper(); - SvcLogicContext ctx = new SvcLogicContext(); - Map inParams = new HashMap(); - inParams.put("prefix", "test"); - inParams.put("propertyName", "testVnf_Type.testAction1.url"); - et.getProperty(inParams, ctx); - } - @Test(expected=Exception.class) - public void testgetData() throws Exception - { - DbServiceUtil d = new DbServiceUtil(); - ArrayList argList = null; - String schema ="sdnctl"; - String tableName ="dual"; - String getselectData ="123"; - String getDataClasue="123='123'"; - d.getData(tableName, argList, schema, getselectData, getDataClasue); - } - @Test(expected=Exception.class) - public void testupdateDB() throws Exception - { - DbServiceUtil d = new DbServiceUtil(); - String setCluase = null; - String schema ="sdnctl"; - String tableName ="dual"; - ArrayList inputArgs = null; - String whereClause="123='123'"; - d.updateDB(tableName, inputArgs, schema, whereClause, setCluase); - } -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/FlowControllerActivator.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/FlowControllerActivator.java new file mode 100644 index 000000000..4e8370024 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/FlowControllerActivator.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller; + +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; + +import org.onap.appc.flow.controller.node.FlowControlNode; +import org.onap.appc.flow.controller.node.JsonParsingNode; +import org.onap.appc.flow.controller.node.RestServiceNode; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class FlowControllerActivator implements BundleActivator{ + + private List registrations = new LinkedList(); + + + private static final EELFLogger log = EELFManager.getInstance().getLogger(FlowControllerActivator.class); + + @Override + public void start(BundleContext ctx) throws Exception + { + + try { + + FlowControlNode flowExecutorNode = new FlowControlNode(); + log.debug("Registering service "+ flowExecutorNode.getClass().getName()); + registrations.add(ctx.registerService(flowExecutorNode.getClass().getName(), flowExecutorNode, null)); + log.debug("Registering service sccessful for "+ flowExecutorNode.getClass().getName()); + + RestServiceNode restServiceNode = new RestServiceNode(); + log.debug("Registering service "+ restServiceNode.getClass().getName()); + registrations.add(ctx.registerService(restServiceNode.getClass().getName(), restServiceNode, null)); + log.debug("Registering service sccessful for "+ restServiceNode.getClass().getName()); + + JsonParsingNode jsonParsingNode = new JsonParsingNode(); + log.debug("Registering service "+ jsonParsingNode.getClass().getName()); + registrations.add(ctx.registerService(jsonParsingNode.getClass().getName(), jsonParsingNode, null)); + log.debug("Registering service sccessful for "+ jsonParsingNode.getClass().getName()); + + } catch (Exception e) { + e.printStackTrace(); + } + + } + @Override + public void stop(BundleContext arg0) throws Exception + { + for (ServiceRegistration registration: registrations) + { + registration.unregister(); + registration = null; + } + + } +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/ResponseHandlerImpl/DefaultResponseHandler.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/ResponseHandlerImpl/DefaultResponseHandler.java new file mode 100644 index 000000000..2a0edb086 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/ResponseHandlerImpl/DefaultResponseHandler.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.ResponseHandlerImpl; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.appc.flow.controller.data.Response; +import org.onap.appc.flow.controller.data.ResponseAction; +import org.onap.appc.flow.controller.data.Transaction; +import org.onap.appc.flow.controller.utils.FlowControllerConstants; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +public class DefaultResponseHandler { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(DefaultResponseHandler.class); + + public ResponseAction handlerResponse(Transaction transaction){ + + log.info("Transaction Input params " + transaction.toString()); + ResponseAction responseAction = new ResponseAction(); + if(transaction.getResponses() != null && !transaction.getResponses().isEmpty()){ + for(Response response : transaction.getResponses()){ + if(response.getResponseCode() != null && response.getResponseCode().equals(transaction.getStatusCode())){ + responseAction = response.getResponseAction(); + break; + } + + } + + } + return responseAction ; + } +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/ActionIdentifier.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/ActionIdentifier.java new file mode 100644 index 000000000..abce46862 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/ActionIdentifier.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.data; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ActionIdentifier { + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((vnfId == null) ? 0 : vnfId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ActionIdentifier other = (ActionIdentifier) obj; + if (vnfId == null) { + if (other.vnfId != null) + return false; + } else if (!vnfId.equals(other.vnfId)) + return false; + return true; + } + + @JsonProperty("vnf-id") + private String vnfId ; + + public String getVnfId() { + return vnfId; + } + + public void setVnfId(String vnfId) { + this.vnfId = vnfId; + } + + @Override + public String toString() { + return "ActionIdentifier [vnfId=" + vnfId + "]"; + } + + + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/Parameters.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/Parameters.java new file mode 100644 index 000000000..8320b15fe --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/Parameters.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.data; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Parameters { + + + @JsonProperty("name") + private String paramName ; + + @JsonProperty("value") + private String paramValue ; + + + public String getParamValue() { + return paramValue; + } + public void setParamValue(String paramValue) { + this.paramValue = paramValue; + } + public String getParamName() { + return paramName; + } + public void setParamName(String paramName) { + this.paramName = paramName; + } + @Override + public String toString() { + return "Parameters [paramName=" + paramName + ", paramValue=" + paramValue + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((paramName == null) ? 0 : paramName.hashCode()); + result = prime * result + ((paramValue == null) ? 0 : paramValue.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Parameters other = (Parameters) obj; + if (paramName == null) { + if (other.paramName != null) + return false; + } else if (!paramName.equals(other.paramName)) + return false; + if (paramValue == null) { + if (other.paramValue != null) + return false; + } else if (!paramValue.equals(other.paramValue)) + return false; + return true; + } + + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/PreCheck.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/PreCheck.java new file mode 100644 index 000000000..db76895ab --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/PreCheck.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.data; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class PreCheck { + + + @JsonProperty("precheck-operator") + private String precheckOperator; + + public String getPrecheckOperator() { + return precheckOperator; + } + + public void setPrecheckOperator(String precheckOperator) { + this.precheckOperator = precheckOperator; + } + + @JsonProperty("precheck-options") + private List precheckOptions; + + public List getPrecheckOptions() { + return precheckOptions; + } + + public void setPrecheckOptions(List precheckOptions) { + this.precheckOptions = precheckOptions; + } + + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((precheckOperator == null) ? 0 : precheckOperator.hashCode()); + result = prime * result + ((precheckOptions == null) ? 0 : precheckOptions.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + PreCheck other = (PreCheck) obj; + if (precheckOperator == null) { + if (other.precheckOperator != null) + return false; + } else if (!precheckOperator.equals(other.precheckOperator)) + return false; + if (precheckOptions == null) { + if (other.precheckOptions != null) + return false; + } else if (!precheckOptions.equals(other.precheckOptions)) + return false; + return true; + } + + @Override + public String toString() { + return "PreCheck [precheckOperator=" + precheckOperator + ", precheckOptions=" + precheckOptions + "]"; + } + + + + + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/PrecheckOption.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/PrecheckOption.java new file mode 100644 index 000000000..b3f146fdb --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/PrecheckOption.java @@ -0,0 +1,120 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.data; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class PrecheckOption { + + + @JsonProperty("pre-transaction-id") + private int pTransactionID ; + + @JsonProperty("param-name") + private String paramName ; + + + @JsonProperty("param-value") + private String paramValue ; + + @JsonProperty("rule") + private String rule ; + + public int getpTransactionID() { + return pTransactionID; + } + + public void setpTransactionID(int pTransactionID) { + this.pTransactionID = pTransactionID; + } + + public String getParamName() { + return paramName; + } + + public void setParamName(String paramName) { + this.paramName = paramName; + } + + public String getParamValue() { + return paramValue; + } + + public void setParamValue(String paramValue) { + this.paramValue = paramValue; + } + + + + @Override + public String toString() { + return "PrecheckOption [pTransactionID=" + pTransactionID + ", paramName=" + paramName + ", paramValue=" + + paramValue + ", rule=" + rule + "]"; + } + + + public String getRule() { + return rule; + } + + public void setRule(String rule) { + this.rule = rule; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + this.pTransactionID; + result = prime * result + this.paramName.hashCode(); + result = prime * result + this.paramValue.hashCode(); + result = prime * result + this.rule.hashCode(); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + PrecheckOption other = (PrecheckOption) obj; + if (pTransactionID != other.pTransactionID) + return false; + if (paramName == null) { + if (other.paramName != null) + return false; + } else if (!paramName.equals(other.paramName)) + return false; + if (paramValue == null) { + if (other.paramValue != null) + return false; + } else if (!paramValue.equals(other.paramValue)) + return false; + if (rule != other.rule) + return false; + return true; + } + + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/Response.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/Response.java new file mode 100644 index 000000000..f5c6fe871 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/Response.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.data; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Response { + + @JsonProperty("response-code") + private String responseCode; + + @JsonProperty("response-message") + private String responseMessage; + + @JsonProperty("response-action") + private ResponseAction responseAction; + + private String responseActionHanlder; + + public String getResponseCode() { + return responseCode; + } + + public void setResponseCode(String responseCode) { + this.responseCode = responseCode; + } + + public String getResponseMessage() { + return responseMessage; + } + + public void setResponseMessage(String responseMessage) { + this.responseMessage = responseMessage; + } + + + public String getResponseActionHanlder() { + return responseActionHanlder; + } + + public void setResponseActionHanlder(String responseActionHanlder) { + this.responseActionHanlder = responseActionHanlder; + } + + public ResponseAction getResponseAction() { + return responseAction; + } + + public void setResponseAction(ResponseAction responseAction) { + this.responseAction = responseAction; + } + + @Override + public String toString() { + return "Response [responseCode=" + responseCode + ", responseMessage=" + responseMessage + ", responseAction=" + + responseAction + ", responseActionHanlder=" + responseActionHanlder + "]"; + } + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/ResponseAction.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/ResponseAction.java new file mode 100644 index 000000000..3768941df --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/ResponseAction.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.data; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ResponseAction { + + @JsonProperty("wait") + private String wait; + + @JsonProperty("retry") + private String retry; + + @JsonProperty("jump") + private String jump; + + @JsonProperty("ignore") + private boolean ignore; + + @JsonProperty("stop") + private boolean stop; + + @JsonProperty("intermediate-message") + private boolean intermediateMessage; + + public String getWait() { + return wait; + } + + public void setWait(String wait) { + this.wait = wait; + } + + public String getRetry() { + return retry; + } + + public void setRetry(String retry) { + this.retry = retry; + } + + public String getJump() { + return jump; + } + + public void setJump(String jump) { + this.jump = jump; + } + + public boolean isIgnore() { + return ignore; + } + + public void setIgnore(boolean ignore) { + this.ignore = ignore; + } + + public boolean isStop() { + return stop; + } + + public void setStop(boolean stop) { + this.stop = stop; + } + + + + @Override + public String toString() { + return "ResponseAction [wait=" + wait + ", retry=" + retry + ", jump=" + jump + ", ignore=" + ignore + ", stop=" + + stop + ", intermediateMessage=" + intermediateMessage + "]"; + } + + public boolean isIntermediateMessage() { + return intermediateMessage; + } + + public void setIntermediateMessage(boolean intermediateMessage) { + this.intermediateMessage = intermediateMessage; + } + + + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/Transaction.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/Transaction.java new file mode 100644 index 000000000..082e41b0d --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/Transaction.java @@ -0,0 +1,365 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.data; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class Transaction { + + @JsonProperty("transaction-id") + private int transactionId ; + + @JsonProperty("action") + private String action ; + + @JsonProperty("action-level") + private String actionLevel ; + + @JsonProperty("action-identifier") + private ActionIdentifier actionIdentifier ; + + @JsonProperty("parameters") + private List parameters ; + + private String executionType; + + private String uId; + + private String statusCode; + + private String pswd; + + private String executionEndPoint; + + private String executionModule; + + private String executionRPC; + + @JsonProperty("state") + private String state; + + @JsonProperty("precheck") + private PreCheck precheck; + + @JsonProperty("payload") + private String payload ; + + @JsonProperty("responses") + private List responses ; + + + private String status = "PENDING"; + + public String getuId() { + return uId; + } + + public void setuId(String uId) { + this.uId = uId; + } + + public String getPswd() { + return pswd; + } + + public void setPswd(String pswd) { + this.pswd = pswd; + } + + public String getExecutionEndPoint() { + return executionEndPoint; + } + + public void setExecutionEndPoint(String executionEndPoint) { + this.executionEndPoint = executionEndPoint; + } + + + public String getExecutionType() { + return executionType; + } + + public void setExecutionType(String executionType) { + this.executionType = executionType; + } + + public String getExecutionModule() { + return executionModule; + } + + + public void setExecutionModule(String executionModule) { + this.executionModule = executionModule; + } + + + public String getExecutionRPC() { + return executionRPC; + } + + + public void setExecutionRPC(String executionRPC) { + this.executionRPC = executionRPC; + } + + + public List getParameters() { + return parameters; + } + + + public void setParameters(List parameters) { + this.parameters = parameters; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public PreCheck getPrecheck() { + return precheck; + } + + public void setPrecheck(PreCheck precheck) { + this.precheck = precheck; + } + + public String getStatus() { + return status; + } + + + public void setStatus(String status) { + this.status = status; + } + + public List getResponses() { + return responses; + } + + + public void setResponses(List responses) { + this.responses = responses; + } + + public int getTransactionId() { + return transactionId; + } + + + public void setTransactionId(int transactionId) { + this.transactionId = transactionId; + } + + + public String getAction() { + return action; + } + + + public void setAction(String action) { + this.action = action; + } + + + public String getActionLevel() { + return actionLevel; + } + + + public void setActionLevel(String actionLevel) { + this.actionLevel = actionLevel; + } + + + + public String getPayload() { + return payload; + } + + + public void setPayload(String payload) { + this.payload = payload; + } + + + public ActionIdentifier getActionIdentifier() { + return actionIdentifier; + } + + + public void setActionIdentifier(ActionIdentifier actionIdentifier) { + this.actionIdentifier = actionIdentifier; + } + + public String getStatusCode() { + return statusCode; + } + + public void setStatusCode(String statusCode) { + this.statusCode = statusCode; + } + + @Override + public String toString() { + return "Transaction [transactionId=" + transactionId + ", action=" + action + ", actionLevel=" + actionLevel + + ", actionIdentifier=" + actionIdentifier + ", parameters=" + parameters + ", executionType=" + + executionType + ", uId=" + uId + ", statusCode=" + statusCode + ", pswd=" + pswd + + ", executionEndPoint=" + executionEndPoint + ", executionModule=" + executionModule + + ", executionRPC=" + executionRPC + ", state=" + state + ", precheck=" + precheck + ", payload=" + + payload + ", responses=" + responses + ", status=" + status + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((action == null) ? 0 : action.hashCode()); + result = prime * result + ((actionIdentifier == null) ? 0 : actionIdentifier.hashCode()); + result = prime * result + ((actionLevel == null) ? 0 : actionLevel.hashCode()); + result = prime * result + ((executionEndPoint == null) ? 0 : executionEndPoint.hashCode()); + result = prime * result + ((executionModule == null) ? 0 : executionModule.hashCode()); + result = prime * result + ((executionRPC == null) ? 0 : executionRPC.hashCode()); + result = prime * result + ((executionType == null) ? 0 : executionType.hashCode()); + result = prime * result + ((parameters == null) ? 0 : parameters.hashCode()); + result = prime * result + ((payload == null) ? 0 : payload.hashCode()); + result = prime * result + ((precheck == null) ? 0 : precheck.hashCode()); + result = prime * result + ((pswd == null) ? 0 : pswd.hashCode()); + result = prime * result + ((responses == null) ? 0 : responses.hashCode()); + result = prime * result + ((state == null) ? 0 : state.hashCode()); + result = prime * result + ((status == null) ? 0 : status.hashCode()); + result = prime * result + ((statusCode == null) ? 0 : statusCode.hashCode()); + result = prime * result + transactionId; + result = prime * result + ((uId == null) ? 0 : uId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Transaction other = (Transaction) obj; + if (action == null) { + if (other.action != null) + return false; + } else if (!action.equals(other.action)) + return false; + if (actionIdentifier == null) { + if (other.actionIdentifier != null) + return false; + } else if (!actionIdentifier.equals(other.actionIdentifier)) + return false; + if (actionLevel == null) { + if (other.actionLevel != null) + return false; + } else if (!actionLevel.equals(other.actionLevel)) + return false; + if (executionEndPoint == null) { + if (other.executionEndPoint != null) + return false; + } else if (!executionEndPoint.equals(other.executionEndPoint)) + return false; + if (executionModule == null) { + if (other.executionModule != null) + return false; + } else if (!executionModule.equals(other.executionModule)) + return false; + if (executionRPC == null) { + if (other.executionRPC != null) + return false; + } else if (!executionRPC.equals(other.executionRPC)) + return false; + if (executionType == null) { + if (other.executionType != null) + return false; + } else if (!executionType.equals(other.executionType)) + return false; + if (parameters == null) { + if (other.parameters != null) + return false; + } else if (!parameters.equals(other.parameters)) + return false; + if (payload == null) { + if (other.payload != null) + return false; + } else if (!payload.equals(other.payload)) + return false; + if (precheck == null) { + if (other.precheck != null) + return false; + } else if (!precheck.equals(other.precheck)) + return false; + if (pswd == null) { + if (other.pswd != null) + return false; + } else if (!pswd.equals(other.pswd)) + return false; + if (responses == null) { + if (other.responses != null) + return false; + } else if (!responses.equals(other.responses)) + return false; + if (state == null) { + if (other.state != null) + return false; + } else if (!state.equals(other.state)) + return false; + if (status == null) { + if (other.status != null) + return false; + } else if (!status.equals(other.status)) + return false; + if (statusCode == null) { + if (other.statusCode != null) + return false; + } else if (!statusCode.equals(other.statusCode)) + return false; + if (transactionId != other.transactionId) + return false; + if (uId == null) { + if (other.uId != null) + return false; + } else if (!uId.equals(other.uId)) + return false; + return true; + } + + +} + + + diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/Transactions.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/Transactions.java new file mode 100644 index 000000000..d8dc8472c --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/data/Transactions.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.data; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Transactions { + + + @JsonProperty("transactions") + private List transactions ; + + public List getTransactions() { + return transactions; + } + + public void setTransactions(List transactions) { + this.transactions = transactions; + } + + @Override + public String toString() { + return "Transactions [transactions=" + transactions + "]"; + } + + +} + + + diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/dbervices/FlowControlDBService.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/dbervices/FlowControlDBService.java new file mode 100644 index 000000000..618494167 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/dbervices/FlowControlDBService.java @@ -0,0 +1,222 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.dbervices; + +import java.util.HashMap; +import java.util.Map; + +import org.onap.appc.flow.controller.data.Transaction; +import org.onap.appc.flow.controller.utils.EscapeUtils; +import org.onap.appc.flow.controller.utils.FlowControllerConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; +import org.onap.ccsdk.sli.adaptors.resource.sql.SqlResource; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class FlowControlDBService { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(FlowControlDBService.class); + private SvcLogicResource serviceLogic; + private static FlowControlDBService dgGeneralDBService = null; + public static FlowControlDBService initialise() { + if (dgGeneralDBService == null) { + dgGeneralDBService = new FlowControlDBService(); + } + return dgGeneralDBService; + } + private FlowControlDBService() { + if (serviceLogic == null) { + serviceLogic = new SqlResource(); + } + } + + public void getFlowReferenceData(SvcLogicContext ctx, Map inParams, SvcLogicContext localContext) throws SvcLogicException { + + String fn = "DBService.getflowModelInfo"; + // log.debug("Testing " + ctx.getAttribute(FlowExecutorConstants.VNF_TYPE) + " and " + ctx.getAttribute(FlowExecutorConstants.ACTION_LEVEL)); + String whereClause = " where ACTION = $" +FlowControllerConstants.REQUEST_ACTION ; + + if(ctx.getAttribute(FlowControllerConstants.VNF_TYPE) !=null) + whereClause = whereClause.concat(" and VNF_TYPE = $" + FlowControllerConstants.VNF_TYPE); + + if(ctx.getAttribute(FlowControllerConstants.ACTION_LEVEL) !=null) + whereClause = whereClause.concat(" and ACTION_LEVEL = $" + FlowControllerConstants.ACTION_LEVEL); + + QueryStatus status = null; + if (serviceLogic != null && localContext != null) { + String key = "select SEQUENCE_TYPE, CATEGORY, GENERATION_NODE, EXECUTION_NODE from " + FlowControllerConstants.DB_MULTISTEP_FLOW_REFERENCE + + whereClause ; + log.debug(fn + "Query String : " + key); + status = serviceLogic.query("SQL", false, null, key, null, null, localContext); + if(status.toString().equals("FAILURE")) + throw new SvcLogicException("Error - while getting FlowReferenceData "); + } + } + public String getEndPointByAction(String action) { + // TODO Auto-generated method stub + return null; + } + public String getDesignTimeFlowModel(SvcLogicContext localContext) throws SvcLogicException { + String fn = "DBService.getDesignTimeFlowModel "; + QueryStatus status = null; + if (serviceLogic != null && localContext != null) { + String queryString = "select max(internal_version) as maxInternalVersion, artifact_name as artifactName from " + FlowControllerConstants.DB_SDC_ARTIFACTS + + " where artifact_name in (select artifact_name from " + FlowControllerConstants.DB_SDC_REFERENCE + + " where vnf_type= $" + FlowControllerConstants.VNF_TYPE + + " and vnfc_type = $" + FlowControllerConstants.VNFC_TYPE + + " and action = $" + FlowControllerConstants.REQUEST_ACTION + + " and file_category = $" + FlowControllerConstants.CATEGORY + " )" ; + + + log.debug(fn + "Query String : " + queryString); + status = serviceLogic.query("SQL", false, null, queryString, null, null, localContext); + + if(status.toString().equals("FAILURE")) + throw new SvcLogicException("Error - while getting FlowReferenceData "); + + String queryString1 = "select artifact_content from " + FlowControllerConstants.DB_SDC_ARTIFACTS + + " where artifact_name = $artifactName and internal_version = $maxInternalVersion "; + + log.debug(fn + "Query String : " + queryString1); + status = serviceLogic.query("SQL", false, null, queryString1, null, null, localContext); + if(status.toString().equals("FAILURE")) + throw new SvcLogicException("Error - while getting FlowReferenceData "); + } + return localContext != null ? localContext.getAttribute("artifact-content") : null; + } + public QueryStatus loadSequenceIntoDB(SvcLogicContext localContext) throws SvcLogicException { + + QueryStatus status = null; + + if (localContext != null) { + String fn = "DBService.saveArtifacts"; + + localContext.setAttribute(FlowControllerConstants.ARTIFACT_CONTENT_ESCAPED, + EscapeUtils.escapeSql(localContext.getAttribute(FlowControllerConstants.ARTIFACT_CONTENT))); + log.debug("ESCAPED sequence for DB : " + localContext.getAttribute(FlowControllerConstants.ARTIFACT_CONTENT_ESCAPED)); + + for (Object key : localContext.getAttributeKeySet()) { + String parmName = (String) key; + String parmValue = localContext.getAttribute(parmName); + log.debug(" loadSequenceIntoDB " + parmName + "=" + parmValue); + + } + + String queryString = "INSERT INTO " + FlowControllerConstants.DB_REQUEST_ARTIFACTS + + " set request_id = $" + FlowControllerConstants.REQUEST_ID + + " , action = $" + FlowControllerConstants.REQUEST_ACTION + + " , action_level = $" + FlowControllerConstants.ACTION_LEVEL + + " , vnf_type = $" + FlowControllerConstants.VNF_TYPE + + " , category = $" + FlowControllerConstants.CATEGORY + + " , artifact_content = $" + FlowControllerConstants.ARTIFACT_CONTENT_ESCAPED + + " , updated_date = sysdate() "; + + log.debug(fn + "Query String : " + queryString); + status = serviceLogic.save("SQL", false, false, queryString, null, null, localContext); + if(status.toString().equals("FAILURE")) + throw new SvcLogicException("Error While processing storing Artifact: " +localContext.getAttribute(FlowControllerConstants.ARTIFACT_NAME)); + } + return status; + + } + public void populateModuleAndRPC(Transaction transaction, String vnf_type) throws SvcLogicException { + String fn = "FlowControlDBService.populateModuleAndRPC "; + QueryStatus status = null; + SvcLogicContext context = new SvcLogicContext(); + + String key = "select execution_type, execution_module, execution_rpc from " + FlowControllerConstants.DB_PROCESS_FLOW_REFERENCE + + " where action = '" + transaction.getAction() + "'" + + " and action_level = '" + transaction.getActionLevel() + "'" + + " and protocol in ( select protocol from " + FlowControllerConstants.DB_PROTOCOL_REFERENCE + + " where action = '" + transaction.getAction() + "'" ; + if(vnf_type !=null && !vnf_type.isEmpty()) + key = key + " and vnf_type ='" + vnf_type + "' )" ; + else + key = key + " ) " ; + log.debug(fn + "Query String : " + key); + status = serviceLogic.query("SQL", false, null, key, null, null, context); + if(status.toString().equals("FAILURE")) + throw new SvcLogicException("Error - while getting FlowReferenceData "); + + transaction.setExecutionModule(context.getAttribute(FlowControllerConstants.EXECUTTION_MODULE)); + transaction.setExecutionRPC(context.getAttribute(FlowControllerConstants.EXECUTION_RPC)); + transaction.setExecutionType(context.getAttribute(FlowControllerConstants.EXECUTION_TYPE)); + + } + + public String getDependencyInfo(SvcLogicContext localContext) throws SvcLogicException { + String fn = "DBService.getDependencyInfo "; + QueryStatus status = null; + if (serviceLogic != null && localContext != null) { + String queryString = "select max(internal_version) as maxInternalVersion, artifact_name as artifactName from " + FlowControllerConstants.DB_SDC_ARTIFACTS + + " where artifact_name in (select artifact_name from " + FlowControllerConstants.DB_SDC_REFERENCE + + " where vnf_type= $" + FlowControllerConstants.VNF_TYPE + + " and file_category = '" + FlowControllerConstants.DEPENDENCYMODEL +"' )" ; + + log.debug(fn + "Query String : " + queryString); + status = serviceLogic.query("SQL", false, null, queryString, null, null, localContext); + + if(status.toString().equals("FAILURE")) + throw new SvcLogicException("Error - while getting dependencydata "); + + String queryString1 = "select artifact_content from " + FlowControllerConstants.DB_SDC_ARTIFACTS + + " where artifact_name = $artifactName and internal_version = $maxInternalVersion "; + + log.debug(fn + "Query String : " + queryString1); + status = serviceLogic.query("SQL", false, null, queryString1, null, null, localContext); + if(status.toString().equals("FAILURE")) + throw new SvcLogicException("Error - while getting dependencyData "); + } + + return localContext != null ? localContext.getAttribute("artifact-content") : null; + + } + + public String getCapabilitiesData(SvcLogicContext localContext) throws SvcLogicException { + String fn = "DBService.getCapabilitiesData "; + QueryStatus status = null; + if (serviceLogic != null && localContext != null) { + String queryString = "select max(internal_version) as maxInternalVersion, artifact_name as artifactName from " + FlowControllerConstants.DB_SDC_ARTIFACTS + + " where artifact_name in (select artifact_name from " + FlowControllerConstants.DB_SDC_REFERENCE + + " where vnf_type= $" + FlowControllerConstants.VNF_TYPE + + " and file_category = '" + FlowControllerConstants.CAPABILITY +"' )" ; + + log.info(fn + "Query String : " + queryString); + status = serviceLogic.query("SQL", false, null, queryString, null, null, localContext); + + if(status.toString().equals("FAILURE")) + throw new SvcLogicException("Error - while getting capabilitiesData "); + + String queryString1 = "select artifact_content from " + FlowControllerConstants.DB_SDC_ARTIFACTS + + " where artifact_name = $artifactName and internal_version = $maxInternalVersion "; + + log.debug(fn + "Query String : " + queryString1); + status = serviceLogic.query("SQL", false, null, queryString1, null, null, localContext); + if(status.toString().equals("FAILURE")) + throw new SvcLogicException("Error - while getting capabilitiesData "); + } + return localContext != null ? localContext.getAttribute("artifact-content") : null; + } +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/executorImpl/GraphExecutor.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/executorImpl/GraphExecutor.java new file mode 100644 index 000000000..5548b1c3e --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/executorImpl/GraphExecutor.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.executorImpl; + +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Properties; + +import org.onap.appc.flow.controller.data.Parameters; +import org.onap.appc.flow.controller.data.Transaction; +import org.onap.appc.flow.controller.interfaces.FlowExecutorInterface; +import org.onap.appc.flow.controller.utils.FlowControllerConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +public class GraphExecutor implements FlowExecutorInterface { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(GraphExecutor.class); + + private SvcLogicService svcLogic = null; + + public GraphExecutor() { + BundleContext bctx = FrameworkUtil.getBundle(SvcLogicService.class) + .getBundleContext(); + + ServiceReference sref = bctx.getServiceReference(SvcLogicService.NAME); + if (sref != null) { + svcLogic = (SvcLogicService) bctx.getService(sref); + + + } else { + log.warn("Cannot find service reference for " + + SvcLogicService.NAME); + } + log.debug("Graph Executor Initialized successfully"); + } + + public boolean hasGraph(String module, String rpc, String version, + String mode) throws SvcLogicException { + return (svcLogic.hasGraph(module, rpc, version, mode)); + } + + public Properties executeGraph(String module, String rpc, String version, + String mode, Properties parms) throws SvcLogicException { + log.debug("Parameters passed to SLI"); + +// for (Object key : parms.keySet()) { +// String parmName = (String) key; +// String parmValue = parms.getProperty(parmName); +// +// log.debug(parmName + " = " + parmValue); +// } + + Properties respProps = svcLogic.execute(module, rpc, version, mode,parms); + if (log.isDebugEnabled()) { + log.debug("Parameters returned by SLI"); + for (Object key : respProps.keySet()) { + String parmName = (String) key; + String parmValue = respProps.getProperty(parmName); + + log.debug(parmName + " = " + parmValue); + } + } + if ("failure" + .equalsIgnoreCase(respProps.getProperty("SvcLogic.status"))) { + return (respProps); + } + return (respProps); +} + +@Override +public HashMap execute(Transaction transaction, SvcLogicContext ctx) throws Exception { + + String fn = "GraphExecutor.execute "; + log.debug(fn + "About to execute graph : " + transaction.getExecutionRPC()) ; + + Properties parms = new Properties(); + for (Object key : ctx.getAttributeKeySet()) { + String parmName = (String) key; + String parmValue = ctx.getAttribute(parmName); + parms.put(parmName, parmValue); + log.info(fn + "Setting Key= " + parmName + "and Value = " + parmValue); + + } + Properties returnParams = executeGraph(transaction.getExecutionModule(),transaction.getExecutionRPC(), null, "sync", parms); + + //log.debug("Return Params executing DG :" + returnParams.toString()); + + log.debug("Returned Params from DG Module: " + transaction.getExecutionModule() + "and DG NAME: " + transaction.getExecutionRPC() + + returnParams.toString()); + + Enumeration e = returnParams.propertyNames(); + + while (e.hasMoreElements()) { + String key = (String) e.nextElement(); + log.info("NEW KEY = " + key + " -- " + returnParams.getProperty(key)); + + ctx.setAttribute(key, returnParams.getProperty(key)); + } + + + //Get the correct code from the SVC Logic and set it in transaction +// transaction.setStatusCode(returnParams.getProperty("SvcLogic.code")); + + if (FlowControllerConstants.FAILURE + .equalsIgnoreCase(returnParams.getProperty("SvcLogic.status"))) { + transaction.setStatus(FlowControllerConstants.FAILURE); + ctx.setAttribute(ctx.getAttribute(FlowControllerConstants.RESPONSE_PREFIX) + FlowControllerConstants.OUTPUT_PARAM_STATUS, FlowControllerConstants.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(ctx.getAttribute(FlowControllerConstants.RESPONSE_PREFIX) + FlowControllerConstants.OUTPUT_STATUS_MESSAGE, returnParams.getProperty("error-message")); + transaction.setStatusCode("401"); + transaction.setState((ctx.getAttribute(transaction.getExecutionModule() + "." + transaction.getExecutionRPC() + "." + FlowControllerConstants.OUTPUT_STATUS_MESSAGE)) !=null ? + ctx.getAttribute(transaction.getExecutionModule() + "." + transaction.getExecutionRPC() + "." + FlowControllerConstants.OUTPUT_STATUS_MESSAGE): null); + //Get error code from above instead setting here ...its for testing purpose + + + } + else if(FlowControllerConstants.SUCCESS + .equalsIgnoreCase(returnParams.getProperty("SvcLogic.status"))) { + transaction.setStatus(FlowControllerConstants.SUCCESS); + transaction.setStatusCode("400"); + ctx.setAttribute(ctx.getAttribute(FlowControllerConstants.RESPONSE_PREFIX) + FlowControllerConstants.OUTPUT_PARAM_STATUS, FlowControllerConstants.OUTPUT_STATUS_SUCCESS); + transaction.setState((ctx.getAttribute(transaction.getExecutionModule() + "." + transaction.getExecutionRPC() + "." + FlowControllerConstants.OUTPUT_STATUS_MESSAGE)) !=null ? + ctx.getAttribute(transaction.getExecutionModule() + "." + transaction.getExecutionRPC() + "." + FlowControllerConstants.OUTPUT_STATUS_MESSAGE): null); + //Get error code from above instead setting here ...its for testing purpose + } + else { + transaction.setStatus(FlowControllerConstants.OTHERS); + ctx.setAttribute(ctx.getAttribute(FlowControllerConstants.RESPONSE_PREFIX) + FlowControllerConstants.OUTPUT_PARAM_STATUS, FlowControllerConstants.OUTPUT_STATUS_FAILURE); + transaction.setStatusCode("401"); + ctx.setAttribute(ctx.getAttribute(FlowControllerConstants.RESPONSE_PREFIX) + FlowControllerConstants.OUTPUT_STATUS_MESSAGE, returnParams.getProperty("error-message")); + } + + return null; + //Change null to required value if required in upper level +} +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/executorImpl/NodeExecutor.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/executorImpl/NodeExecutor.java new file mode 100644 index 000000000..50de43beb --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/executorImpl/NodeExecutor.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.executorImpl; + +import java.util.HashMap; +import java.util.Properties; + +import org.onap.appc.flow.controller.data.Transaction; +import org.onap.appc.flow.controller.interfaces.FlowExecutorInterface; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +public class NodeExecutor implements FlowExecutorInterface { + + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(NodeExecutor.class); + + @Override + public HashMap execute(Transaction transaction, SvcLogicContext ctx) { + return null; + } +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/executorImpl/RestExecutor.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/executorImpl/RestExecutor.java new file mode 100644 index 000000000..366e80273 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/executorImpl/RestExecutor.java @@ -0,0 +1,156 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.executorImpl; + +import java.io.FileInputStream; +import java.io.InputStream; +import java.net.URI; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Properties; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.MediaType; + +import org.apache.commons.io.IOUtils; +import org.onap.appc.flow.controller.data.Response; +import org.onap.appc.flow.controller.data.Transaction; +import org.onap.appc.flow.controller.interfaces.FlowExecutorInterface; +import org.onap.appc.flow.controller.utils.FlowControllerConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.config.DefaultClientConfig; +import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +public class RestExecutor implements FlowExecutorInterface { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(RestExecutor.class); + private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; + Properties props = new Properties(); + public RestExecutor() throws Exception { + String propDir = System.getenv(SDNC_CONFIG_DIR_VAR); + if (propDir == null) + throw new Exception(" Cannot find Property file -" + SDNC_CONFIG_DIR_VAR); + String propFile = propDir + FlowControllerConstants.APPC_FLOW_CONTROLLER; + InputStream propStream = new FileInputStream(propFile); + try{ + props.load(propStream); + } + catch (Exception e){ + throw new Exception("Could not load properties file " + propFile, e); + } + finally{ + try{ + propStream.close(); + } + catch (Exception e){ + log.warn("Could not close FileInputStream", e); + } + } + } + @Override + public HashMap execute(Transaction transaction, SvcLogicContext ctx) throws Exception{ + log.info("Configuring Rest Operation....." + transaction.toString()); + Response response = new Response(); + HashMap outputMessage = new HashMap(); + Client client = null; + WebResource webResource = null; + ClientResponse clientResponse = null; + String responseDataType=MediaType.APPLICATION_JSON; + String requestDataType=MediaType.APPLICATION_JSON; + + + try{ + DefaultClientConfig defaultClientConfig = new DefaultClientConfig(); + System.setProperty("jsse.enableSNIExtension", "false"); + SSLContext sslContext = null; + SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager(); + sslContext = SSLContext.getInstance("SSL"); + sslContext.init(null, new javax.net.ssl.TrustManager[] { secureRestClientTrustManager }, null); + defaultClientConfig.getProperties().put( + com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, + new com.sun.jersey.client.urlconnection.HTTPSProperties(getHostnameVerifier(), sslContext)); + client = Client.create(defaultClientConfig); + client.addFilter(new HTTPBasicAuthFilter(transaction.getuId(), transaction.getPswd())); + webResource = client.resource(new URI(transaction.getExecutionEndPoint())); + webResource.setProperty("Content-Type", "application/json;charset=UTF-8"); + + log.info("Starting Rest Operation....."); + if(HttpMethod.GET.equalsIgnoreCase(transaction.getExecutionRPC())){ + clientResponse = webResource.accept(responseDataType).get(ClientResponse.class); + }else if(HttpMethod.POST.equalsIgnoreCase(transaction.getExecutionRPC())){ + clientResponse = webResource.type(requestDataType).post(ClientResponse.class, transaction.getPayload()); + }else if(HttpMethod.PUT.equalsIgnoreCase(transaction.getExecutionRPC())){ + clientResponse = webResource.type(requestDataType).put(ClientResponse.class,transaction.getPayload()); + }else if(HttpMethod.DELETE.equalsIgnoreCase(transaction.getExecutionRPC())){ + clientResponse = webResource.delete(ClientResponse.class); + } + + if(clientResponse.getStatus() == 200){ + response.setResponseCode(String.valueOf(clientResponse.getStatus())); + ArrayList responses = new ArrayList(); + responses.add(response); + transaction.setResponses(responses); + outputMessage.put("restResponse", clientResponse.getEntity(String.class)); + } + else{ + throw new Exception("Can not determine the state of : " + transaction.getActionLevel() + " HTTP error code : " + + clientResponse.getStatus()); + + } + + log.info("Completed Rest Operation....."); + + }catch (Exception e) { + e.printStackTrace(); + log.debug("failed in RESTCONT Action ("+transaction.getExecutionRPC()+") for the resource " + transaction.getExecutionEndPoint() + ", falut message :"+e.getMessage()); + throw new Exception("Error While Sending Rest Request" + e.getMessage()); + } + finally { + // clean up. + webResource = null; + if(client != null){ + client.destroy(); + client = null; + } + } + + return outputMessage; + } + +private HostnameVerifier getHostnameVerifier() { + return new HostnameVerifier() { + @Override + public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) { + return true; + } + }; +} + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/executorImpl/SecureRestClientTrustManager.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/executorImpl/SecureRestClientTrustManager.java new file mode 100644 index 000000000..cbe5de28b --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/executorImpl/SecureRestClientTrustManager.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.executorImpl; + +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.X509TrustManager; + + +public class SecureRestClientTrustManager implements X509TrustManager { + + @Override + public void checkClientTrusted(X509Certificate[] arg0, String arg1) + throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] arg0, String arg1) + throws CertificateException { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + + public boolean isClientTrusted(X509Certificate[] arg0) { + return true; + } + + public boolean isServerTrusted(X509Certificate[] arg0) { + return true; + } + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/ActionIdentifier.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/ActionIdentifier.java new file mode 100644 index 000000000..2784dcc15 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/ActionIdentifier.java @@ -0,0 +1,158 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2017.07.31 at 10:30:39 AM EDT +// + + +package org.onap.appc.flow.controller.interfaceData; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import com.fasterxml.jackson.annotation.JsonProperty; + + +/** + *

Java class for anonymous complex type. + * + *

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

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="vnf-id" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="vserver-id" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="vnfc-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "vnfId", + "vserverId", + "vnfcName" +}) +@XmlRootElement(name = "action-identifier") +public class ActionIdentifier { + + @XmlElement(name = "vnf-id", required = true) + @JsonProperty("vnf-id") + protected String vnfId; + @XmlElement(name = "vserver-id", required = true) + @JsonProperty("vserver-id") + protected String vserverId; + @XmlElement(name = "vnfc-name", required = true) + @JsonProperty("vnfc-name") + protected String vnfcName; + + /** + * Gets the value of the vnfId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getVnfId() { + return vnfId; + } + + /** + * Sets the value of the vnfId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setVnfId(String value) { + this.vnfId = value; + } + + /** + * Gets the value of the vserverId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getVserverId() { + return vserverId; + } + + /** + * Sets the value of the vserverId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setVserverId(String value) { + this.vserverId = value; + } + + /** + * Gets the value of the vnfcName property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getVnfcName() { + return vnfcName; + } + + /** + * Sets the value of the vnfcName property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setVnfcName(String value) { + this.vnfcName = value; + } + + @Override + public String toString() { + return "ActionIdentifier [vnfId=" + vnfId + ", vserverId=" + vserverId + + ", vnfcName=" + vnfcName + "]"; + } + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Capabilities.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Capabilities.java new file mode 100644 index 000000000..91414d3b2 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Capabilities.java @@ -0,0 +1,190 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2017.07.31 at 10:30:39 AM EDT +// + + +package org.onap.appc.flow.controller.interfaceData; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlList; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import com.fasterxml.jackson.annotation.JsonProperty; + + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "vnf", + "vfModule", + "vm", + "vnfc" +}) +@XmlRootElement(name = "capabilities") +public class Capabilities { + + @XmlList + @XmlElement(required = true) + protected List vnf; + @XmlList + @XmlElement(name = "vf-module", required = true) + @JsonProperty("vf-module") + protected List vfModule; + @XmlList + @XmlElement(required = true) + protected List vm; + @XmlList + @XmlElement(required = true) + protected List vnfc; + + /** + * Gets the value of the vnf property. + * + *

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

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

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

+ * Objects of the following type(s) are allowed in the list + * {@link String } + * + * + */ + public List getVnf() { + if (vnf == null) { + vnf = new ArrayList(); + } + return this.vnf; + } + + /** + * Gets the value of the vfModule property. + * + *

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

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

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

+ * Objects of the following type(s) are allowed in the list + * {@link String } + * + * + */ + public List getVfModule() { + if (vfModule == null) { + vfModule = new ArrayList(); + } + return this.vfModule; + } + + /** + * Gets the value of the vm property. + * + *

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

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

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

+ * Objects of the following type(s) are allowed in the list + * {@link String } + * + * + */ + public List getVm() { + if (vm == null) { + vm = new ArrayList(); + } + return this.vm; + } + + /** + * Gets the value of the vnfc property. + * + *

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

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

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

+ * Objects of the following type(s) are allowed in the list + * {@link String } + * + * + */ + public List getVnfc() { + if (vnfc == null) { + vnfc = new ArrayList(); + } + return this.vnfc; + } + + @Override + public String toString() { + return "Capabilities [vnf=" + vnf + ", vfModule=" + vfModule + ", vm=" + + vm + ", vnfc=" + vnfc + "]"; + } + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/DependencyInfo.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/DependencyInfo.java new file mode 100644 index 000000000..1dfe961b7 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/DependencyInfo.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2017.07.31 at 10:30:39 AM EDT +// + + +package org.onap.appc.flow.controller.interfaceData; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "vnfcs" +}) +@XmlRootElement(name = "dependency-info") +@JsonIgnoreProperties(ignoreUnknown = true) +public class DependencyInfo { + + protected List vnfcs; + + /** + * Gets the value of the vnfcs property. + * + *

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

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

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

+ * Objects of the following type(s) are allowed in the list + * {@link Vnfcs } + * + * + */ + public List getVnfcs() { + if (vnfcs == null) { + vnfcs = new ArrayList(); + } + return this.vnfcs; + } + + @Override + public String toString() { + return "DependencyInfo [vnfcs=" + vnfcs + "]"; + } + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Input.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Input.java new file mode 100644 index 000000000..ed95268d1 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Input.java @@ -0,0 +1,199 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2017.07.31 at 10:30:39 AM EDT +// + + +package org.onap.appc.flow.controller.interfaceData; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonRootName; + + +@XmlAccessorType(XmlAccessType.FIELD) +@JsonRootName(value="input") +@XmlType(name = "input", propOrder = { + "requestInfo", + "inventoryInfo", + "dependencyInfo", + "tunableParameters", + "capabilities" +}) +@JsonPropertyOrder({"requestInfo", + "inventoryInfo", + "dependencyInfo", + "tunableParameters", + "capabilities" }) +public class Input { + + @XmlElement(name = "request-info") + @JsonProperty("request-info") + protected RequestInfo requestInfo; + @XmlElement(name = "inventory-info") + @JsonProperty("inventory-info") + protected InventoryInfo inventoryInfo; + @XmlElement(name = "dependency-info") + @JsonProperty("dependency-info") + protected DependencyInfo dependencyInfo; + @XmlElement(name = "tunable-parameters") + @JsonProperty("tunable-parameters") + protected TunableParameters tunableParameters; + protected Capabilities capabilities; + + /** + * Gets the value of the requestInfo property. + * + * @return + * possible object is + * {@link RequestInfo } + * + */ + public RequestInfo getRequestInfo() { + return requestInfo; + } + + /** + * Sets the value of the requestInfo property. + * + * @param value + * allowed object is + * {@link RequestInfo } + * + */ + public void setRequestInfo(RequestInfo value) { + this.requestInfo = value; + } + + /** + * Gets the value of the inventoryInfo property. + * + * @return + * possible object is + * {@link InventoryInfo } + * + */ + public InventoryInfo getInventoryInfo() { + return inventoryInfo; + } + + /** + * Sets the value of the inventoryInfo property. + * + * @param value + * allowed object is + * {@link InventoryInfo } + * + */ + public void setInventoryInfo(InventoryInfo value) { + this.inventoryInfo = value; + } + + /** + * Gets the value of the dependencyInfo property. + * + * @return + * possible object is + * {@link DependencyInfo } + * + */ + public DependencyInfo getDependencyInfo() { + return dependencyInfo; + } + + /** + * Sets the value of the dependencyInfo property. + * + * @param value + * allowed object is + * {@link DependencyInfo } + * + */ + public void setDependencyInfo(DependencyInfo value) { + this.dependencyInfo = value; + } + + /** + * Gets the value of the tunableParameters property. + * + * @return + * possible object is + * {@link TunableParameters } + * + */ + public TunableParameters getTunableParameters() { + return tunableParameters; + } + + /** + * Sets the value of the tunableParameters property. + * + * @param value + * allowed object is + * {@link TunableParameters } + * + */ + public void setTunableParameters(TunableParameters value) { + this.tunableParameters = value; + } + + /** + * Gets the value of the capabilities property. + * + * @return + * possible object is + * {@link Capabilities } + * + */ + public Capabilities getCapabilities() { + return capabilities; + } + + /** + * Sets the value of the capabilities property. + * + * @param value + * allowed object is + * {@link Capabilities } + * + */ + public void setCapabilities(Capabilities value) { + this.capabilities = value; + } + + @Override + public String toString() { + return "Input [requestInfo=" + requestInfo + ", inventoryInfo=" + + inventoryInfo + ", dependencyInfo=" + dependencyInfo + + ", tunableParameters=" + tunableParameters + + ", capabilities=" + capabilities + "]"; + } + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/InventoryInfo.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/InventoryInfo.java new file mode 100644 index 000000000..24da512b1 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/InventoryInfo.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2017.07.31 at 10:30:39 AM EDT +// + + +package org.onap.appc.flow.controller.interfaceData; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import com.fasterxml.jackson.annotation.JsonProperty; + + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "vnfInfo" +}) +@XmlRootElement(name = "inventory-info") +public class InventoryInfo { + + @XmlElement(name = "vnf-info", required = true) + @JsonProperty("vnf-info") + protected VnfInfo vnfInfo; + + /** + * Gets the value of the vnfInfo property. + * + * @return + * possible object is + * {@link VnfInfo } + * + */ + public VnfInfo getVnfInfo() { + return vnfInfo; + } + + /** + * Sets the value of the vnfInfo property. + * + * @param value + * allowed object is + * {@link VnfInfo } + * + */ + public void setVnfInfo(VnfInfo value) { + this.vnfInfo = value; + } + + @Override + public String toString() { + return "InventoryInfo [vnfInfo=" + vnfInfo + "]"; + } + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/ObjectFactory.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/ObjectFactory.java new file mode 100644 index 000000000..a52634b97 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/ObjectFactory.java @@ -0,0 +1,147 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2017.07.31 at 10:30:39 AM EDT +// + + +package org.onap.appc.flow.controller.interfaceData; + +import javax.xml.bind.annotation.XmlRegistry; + + +/** + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the org.onap.appc.flow.controller.interfaceData package. + *

An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are + * provided in this class. + * + */ +@XmlRegistry +public class ObjectFactory { + + + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.appc.flow.controller.interfaceData + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link Capabilities } + * + */ + public Capabilities createCapabilities() { + return new Capabilities(); + } + + /** + * Create an instance of {@link RequestInfo } + * + */ + public RequestInfo createRequestInfo() { + return new RequestInfo(); + } + + /** + * Create an instance of {@link ActionIdentifier } + * + */ + public ActionIdentifier createActionIdentifier() { + return new ActionIdentifier(); + } + + /** + * Create an instance of {@link DependencyInfo } + * + */ + public DependencyInfo createDependencyInfo() { + return new DependencyInfo(); + } + + /** + * Create an instance of {@link Vnfcs } + * + */ + public Vnfcs createVnfcs() { + return new Vnfcs(); + } + + /** + * Create an instance of {@link Vm } + * + */ + public Vm createVm() { + return new Vm(); + } + + /** + * Create an instance of {@link Vnfcslist } + * + */ + public Vnfcslist createVnfcslist() { + return new Vnfcslist(); + } + + /** + * Create an instance of {@link TunableParameters } + * + */ + public TunableParameters createTunableParameters() { + return new TunableParameters(); + } + + /** + * Create an instance of {@link VnfInfo } + * + */ + public VnfInfo createVnfInfo() { + return new VnfInfo(); + } + + /** + * Create an instance of {@link InventoryInfo } + * + */ + public InventoryInfo createInventoryInfo() { + return new InventoryInfo(); + } + + /** + * Create an instance of {@link Input } + * + */ + public Input createInput() { + return new Input(); + } + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/RequestInfo.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/RequestInfo.java new file mode 100644 index 000000000..2cca748e6 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/RequestInfo.java @@ -0,0 +1,164 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2017.07.31 at 10:30:39 AM EDT +// + + +package org.onap.appc.flow.controller.interfaceData; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import com.fasterxml.jackson.annotation.JsonProperty; + + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "action", + "actionLevel", + "actionIdentifier", + "payload" +}) +@XmlRootElement(name = "request-info") +public class RequestInfo { + + @XmlElement(required = true) + protected String action; + @XmlElement(name = "action-level", required = true) + @JsonProperty("action-level") + protected String actionLevel; + @XmlElement(name = "action-identifier", required = true) + @JsonProperty("action-identifier") + protected ActionIdentifier actionIdentifier; + @XmlElement(required = true) + protected String payload; + + /** + * Gets the value of the action property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getAction() { + return action; + } + + /** + * Sets the value of the action property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setAction(String value) { + this.action = value; + } + + /** + * Gets the value of the actionLevel property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getActionLevel() { + return actionLevel; + } + + /** + * Sets the value of the actionLevel property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setActionLevel(String value) { + this.actionLevel = value; + } + + /** + * Gets the value of the actionIdentifier property. + * + * @return + * possible object is + * {@link ActionIdentifier } + * + */ + public ActionIdentifier getActionIdentifier() { + return actionIdentifier; + } + + /** + * Sets the value of the actionIdentifier property. + * + * @param value + * allowed object is + * {@link ActionIdentifier } + * + */ + public void setActionIdentifier(ActionIdentifier value) { + this.actionIdentifier = value; + } + + /** + * Gets the value of the payload property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPayload() { + return payload; + } + + /** + * Sets the value of the payload property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPayload(String value) { + this.payload = value; + } + + @Override + public String toString() { + return "RequestInfo [action=" + action + ", actionLevel=" + actionLevel + + ", actionIdentifier=" + actionIdentifier + ", payload=" + + payload + "]"; + } + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/TunableParameters.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/TunableParameters.java new file mode 100644 index 000000000..ceb3e2ade --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/TunableParameters.java @@ -0,0 +1,153 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2017.07.31 at 10:30:39 AM EDT +// + + +package org.onap.appc.flow.controller.interfaceData; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for anonymous complex type. + * + *

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

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="strategy" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="wait-time" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="retry-count" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "strategy", + "waitTime", + "retryCount" +}) +@XmlRootElement(name = "tunable-parameters") +public class TunableParameters { + + @XmlElement(required = true) + protected String strategy; + @XmlElement(name = "wait-time", required = true) + protected String waitTime; + @XmlElement(name = "retry-count", required = true) + protected String retryCount; + + /** + * Gets the value of the strategy property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getStrategy() { + return strategy; + } + + /** + * Sets the value of the strategy property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setStrategy(String value) { + this.strategy = value; + } + + /** + * Gets the value of the waitTime property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getWaitTime() { + return waitTime; + } + + /** + * Sets the value of the waitTime property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setWaitTime(String value) { + this.waitTime = value; + } + + /** + * Gets the value of the retryCount property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRetryCount() { + return retryCount; + } + + /** + * Sets the value of the retryCount property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRetryCount(String value) { + this.retryCount = value; + } + + @Override + public String toString() { + return "TunableParameters [strategy=" + strategy + ", waitTime=" + + waitTime + ", retryCount=" + retryCount + "]"; + } + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Vm.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Vm.java new file mode 100644 index 000000000..49a98ea0d --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Vm.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2017.07.31 at 10:30:39 AM EDT +// + + +package org.onap.appc.flow.controller.interfaceData; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import com.fasterxml.jackson.annotation.JsonProperty; + + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "vserverId", + "vnfc" +}) +@XmlRootElement(name = "vm") +public class Vm { + + @XmlElement(name = "vserver-id", required = true) + @JsonProperty("vserver-id") + protected String vserverId; + @XmlElement(required = true) + @JsonProperty("vnfc") + protected Vnfcslist vnfc; + + /** + * Gets the value of the vserverId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getVserverId() { + return vserverId; + } + + /** + * Sets the value of the vserverId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setVserverId(String value) { + this.vserverId = value; + } + + /** + * Gets the value of the vnfc property. + * + * @return + * possible object is + * {@link Vnfcslist } + * + */ + public Vnfcslist getVnfc() { + return vnfc; + } + + /** + * Sets the value of the vnfc property. + * + * @param value + * allowed object is + * {@link Vnfcslist } + * + */ + public void setVnfc(Vnfcslist value) { + this.vnfc = value; + } + + @Override + public String toString() { + return "Vm [vserverId=" + vserverId + ", vnfc=" + vnfc + "]"; + } + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/VnfInfo.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/VnfInfo.java new file mode 100644 index 000000000..d4a6d65b7 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/VnfInfo.java @@ -0,0 +1,172 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2017.07.31 at 10:30:39 AM EDT +// + + +package org.onap.appc.flow.controller.interfaceData; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import com.fasterxml.jackson.annotation.JsonProperty; + + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "vnfId", + "vnfName", + "vnfType", + "vm" +}) +@XmlRootElement(name = "vnf-info") +public class VnfInfo { + + @XmlElement(name = "vnf-id", required = true) + @JsonProperty("vnf-id") + protected String vnfId; + @XmlElement(name = "vnf-name", required = true) + @JsonProperty("vnf-name") + protected String vnfName; + @XmlElement(name = "vnf-type", required = true) + @JsonProperty("vnf-type") + protected String vnfType; + @JsonProperty("vm") + protected List vm; + + /** + * Gets the value of the vnfId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getVnfId() { + return vnfId; + } + + /** + * Sets the value of the vnfId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setVnfId(String value) { + this.vnfId = value; + } + + /** + * Gets the value of the vnfName property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getVnfName() { + return vnfName; + } + + /** + * Sets the value of the vnfName property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setVnfName(String value) { + this.vnfName = value; + } + + /** + * Gets the value of the vnfType property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getVnfType() { + return vnfType; + } + + /** + * Sets the value of the vnfType property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setVnfType(String value) { + this.vnfType = value; + } + + /** + * Gets the value of the vm property. + * + *

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

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

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

+ * Objects of the following type(s) are allowed in the list + * {@link Vm } + * + * + */ + public List getVm() { + if (vm == null) { + vm = new ArrayList(); + } + return this.vm; + } + + @Override + public String toString() { + return "VnfInfo [vnfId=" + vnfId + ", vnfName=" + vnfName + + ", vnfType=" + vnfType + ", vm=" + vm + "]"; + } + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Vnfcs.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Vnfcs.java new file mode 100644 index 000000000..7adf05d3c --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Vnfcs.java @@ -0,0 +1,176 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2017.07.31 at 10:30:39 AM EDT +// + + +package org.onap.appc.flow.controller.interfaceData; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlList; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonRootName; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "vnfcType", + "mandatory", + "resilience", + "parents" +}) +@XmlRootElement(name = "vnfcs") +@JsonRootName(value="vnfcs") +public class Vnfcs { + + @XmlElement(name = "vnfc-type", required = true) + @JsonProperty("vnfc-type") + protected String vnfcType; + @XmlElement(required = true) + @JsonProperty("mandatory") + protected String mandatory; + @XmlElement(required = true) + @JsonProperty("resilience") + protected String resilience; + @XmlList + @XmlElement(required = true) + @JsonProperty("parents") + protected List parents; + + /** + * Gets the value of the vnfcType property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getVnfcType() { + return vnfcType; + } + + /** + * Sets the value of the vnfcType property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setVnfcType(String value) { + this.vnfcType = value; + } + + /** + * Gets the value of the mandatory property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getMandatory() { + return mandatory; + } + + /** + * Sets the value of the mandatory property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMandatory(String value) { + this.mandatory = value; + } + + /** + * Gets the value of the resilience property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getResilience() { + return resilience; + } + + /** + * Sets the value of the resilience property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setResilience(String value) { + this.resilience = value; + } + + /** + * Gets the value of the parents property. + * + *

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

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

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

+ * Objects of the following type(s) are allowed in the list + * {@link String } + * + * + */ + public List getParents() { + if (parents == null) { + parents = new ArrayList(); + } + return this.parents; + } + + @Override + public String toString() { + return "Vnfcs [vnfcType=" + vnfcType + ", mandatory=" + mandatory + + ", resilience=" + resilience + ", parents=" + parents + "]"; + } + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Vnfcslist.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Vnfcslist.java new file mode 100644 index 000000000..849f7cad9 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Vnfcslist.java @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2017.07.31 at 10:30:39 AM EDT +// + + +package org.onap.appc.flow.controller.interfaceData; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + +import com.fasterxml.jackson.annotation.JsonProperty; + + +/** + *

Java class for vnfcslist complex type. + * + *

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

+ * <complexType name="vnfcslist">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="vnfc-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="vnfc-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "vnfcslist", propOrder = { + "vnfcType", + "vnfcName" +}) +public class Vnfcslist { + + @XmlElement(name = "vnfc-type", required = true) + @JsonProperty("vnfc-type") + protected String vnfcType; + @XmlElement(name = "vnfc-name", required = true) + @JsonProperty("vnfc-name") + protected String vnfcName; + + /** + * Gets the value of the vnfcType property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getVnfcType() { + return vnfcType; + } + + /** + * Sets the value of the vnfcType property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setVnfcType(String value) { + this.vnfcType = value; + } + + /** + * Gets the value of the vnfcName property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getVnfcName() { + return vnfcName; + } + + /** + * Sets the value of the vnfcName property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setVnfcName(String value) { + this.vnfcName = value; + } + + @Override + public String toString() { + return "Vnfcslist [vnfcType=" + vnfcType + ", vnfcName=" + vnfcName + + "]"; + } + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Vnflist.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Vnflist.java new file mode 100644 index 000000000..1d63f6e53 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/Vnflist.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2017.07.03 at 03:13:44 PM EDT +// + + +package org.onap.appc.flow.controller.interfaceData; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for vnflist. + * + *

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

+ *

+ * <simpleType name="vnflist">
+ *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
+ *     <enumeration value="Restart"/>
+ *     <enumeration value="Rebuild"/>
+ *     <enumeration value="Migrate"/>
+ *     <enumeration value="Evacuate"/>
+ *     <enumeration value="Snapshot"/>
+ *     <enumeration value="Rollback"/>
+ *     <enumeration value="Sync"/>
+ *     <enumeration value="Audit"/>
+ *     <enumeration value="Start"/>
+ *     <enumeration value="Stop"/>
+ *     <enumeration value="Terminate"/>
+ *     <enumeration value="SoftwareUpload"/>
+ *     <enumeration value="HealthCheck"/>
+ *     <enumeration value="LiveUpgrade"/>
+ *     <enumeration value="ModifyConfig"/>
+ *     <enumeration value="Lock"/>
+ *     <enumeration value="Unlock"/>
+ *     <enumeration value="Test"/>
+ *     <enumeration value="CheckLock"/>
+ *     <enumeration value="Configure"/>
+ *     <enumeration value="ConfigModify"/>
+ *     <enumeration value="ConfigScaleOut"/>
+ *     <enumeration value="ConfigRestore"/>
+ *     <enumeration value="ConfigBackup"/>
+ *     <enumeration value="ConfigBackupDelete"/>
+ *     <enumeration value="ConfigExport"/>
+ *   </restriction>
+ * </simpleType>
+ * 
+ * + */ +@XmlType(name = "vnflist") +@XmlEnum +public enum Vnflist { + + @XmlEnumValue("Restart") + RESTART("Restart"), + @XmlEnumValue("Rebuild") + REBUILD("Rebuild"), + @XmlEnumValue("Migrate") + MIGRATE("Migrate"), + @XmlEnumValue("Evacuate") + EVACUATE("Evacuate"), + @XmlEnumValue("Snapshot") + SNAPSHOT("Snapshot"), + @XmlEnumValue("Rollback") + ROLLBACK("Rollback"), + @XmlEnumValue("Sync") + SYNC("Sync"), + @XmlEnumValue("Audit") + AUDIT("Audit"), + @XmlEnumValue("Start") + START("Start"), + @XmlEnumValue("Stop") + STOP("Stop"), + @XmlEnumValue("Terminate") + TERMINATE("Terminate"), + @XmlEnumValue("SoftwareUpload") + SOFTWARE_UPLOAD("SoftwareUpload"), + @XmlEnumValue("HealthCheck") + HEALTH_CHECK("HealthCheck"), + @XmlEnumValue("LiveUpgrade") + LIVE_UPGRADE("LiveUpgrade"), + @XmlEnumValue("ModifyConfig") + MODIFY_CONFIG("ModifyConfig"), + @XmlEnumValue("Lock") + LOCK("Lock"), + @XmlEnumValue("Unlock") + UNLOCK("Unlock"), + @XmlEnumValue("Test") + TEST("Test"), + @XmlEnumValue("CheckLock") + CHECK_LOCK("CheckLock"), + @XmlEnumValue("Configure") + CONFIGURE("Configure"), + @XmlEnumValue("ConfigModify") + CONFIG_MODIFY("ConfigModify"), + @XmlEnumValue("ConfigScaleOut") + CONFIG_SCALE_OUT("ConfigScaleOut"), + @XmlEnumValue("ConfigRestore") + CONFIG_RESTORE("ConfigRestore"), + @XmlEnumValue("ConfigBackup") + CONFIG_BACKUP("ConfigBackup"), + @XmlEnumValue("ConfigBackupDelete") + CONFIG_BACKUP_DELETE("ConfigBackupDelete"), + @XmlEnumValue("ConfigExport") + CONFIG_EXPORT("ConfigExport"); + private final String value; + + Vnflist(String v) { + value = v; + } + + public String value() { + return value; + } + + public static Vnflist fromValue(String v) { + for (Vnflist c: Vnflist.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/package-info.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/package-info.java new file mode 100644 index 000000000..926dfafd8 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaceData/package-info.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2017.07.31 at 10:30:39 AM EDT +// + +@javax.xml.bind.annotation.XmlSchema(namespace = "http:org.onap.appc/sequence/v1", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) +package org.onap.appc.flow.controller.interfaceData; diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaces/FlowExecutorInterface.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaces/FlowExecutorInterface.java new file mode 100644 index 000000000..dbf27c829 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/interfaces/FlowExecutorInterface.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.interfaces; + +import java.util.HashMap; + +import org.onap.appc.flow.controller.data.Transaction; +import org.onap.appc.flow.controller.utils.FlowControllerConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public interface FlowExecutorInterface { + + public HashMap execute(Transaction transaction, SvcLogicContext ctx) throws Exception; + + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/node/FlowControlNode.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/node/FlowControlNode.java new file mode 100644 index 000000000..010729f29 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/node/FlowControlNode.java @@ -0,0 +1,562 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.node; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.flow.controller.ResponseHandlerImpl.DefaultResponseHandler; +import org.onap.appc.flow.controller.data.PrecheckOption; +import org.onap.appc.flow.controller.data.ResponseAction; +import org.onap.appc.flow.controller.data.Transaction; +import org.onap.appc.flow.controller.data.Transactions; +import org.onap.appc.flow.controller.dbervices.FlowControlDBService; +import org.onap.appc.flow.controller.executorImpl.GraphExecutor; +import org.onap.appc.flow.controller.executorImpl.NodeExecutor; +import org.onap.appc.flow.controller.executorImpl.RestExecutor; +import org.onap.appc.flow.controller.interfaceData.ActionIdentifier; +import org.onap.appc.flow.controller.interfaceData.Capabilities; +import org.onap.appc.flow.controller.interfaceData.DependencyInfo; +import org.onap.appc.flow.controller.interfaceData.Input; +import org.onap.appc.flow.controller.interfaceData.InventoryInfo; +import org.onap.appc.flow.controller.interfaceData.RequestInfo; +import org.onap.appc.flow.controller.interfaceData.Vm; +import org.onap.appc.flow.controller.interfaceData.VnfInfo; +import org.onap.appc.flow.controller.interfaceData.Vnfcs; +import org.onap.appc.flow.controller.interfaceData.Vnfcslist; +import org.onap.appc.flow.controller.interfaces.FlowExecutorInterface; +import org.onap.appc.flow.controller.utils.FlowControllerConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + +public class FlowControlNode implements SvcLogicJavaPlugin{ + + + private static final EELFLogger log = EELFManager.getInstance().getLogger(FlowControlNode.class); + private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; + + public void processFlow(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + log.debug("Received processParamKeys call with params : " + inParams); + String responsePrefix = inParams.get(FlowControllerConstants.INPUT_PARAM_RESPONSE_PRIFIX); + try + { + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + FlowControlDBService dbservice = FlowControlDBService.initialise(); + SvcLogicContext localContext = new SvcLogicContext(); + localContext.setAttribute(FlowControllerConstants.REQUEST_ID, ctx.getAttribute(FlowControllerConstants.REQUEST_ID)); + localContext.setAttribute(FlowControllerConstants.VNF_TYPE, ctx.getAttribute(FlowControllerConstants.VNF_TYPE)); + localContext.setAttribute(FlowControllerConstants.REQUEST_ACTION, ctx.getAttribute(FlowControllerConstants.REQUEST_ACTION)); + localContext.setAttribute(FlowControllerConstants.ACTION_LEVEL, ctx.getAttribute(FlowControllerConstants.ACTION_LEVEL)); + localContext.setAttribute(FlowControllerConstants.RESPONSE_PREFIX, responsePrefix); + ctx.setAttribute(FlowControllerConstants.RESPONSE_PREFIX, responsePrefix); + dbservice.getFlowReferenceData(ctx, inParams, localContext); + + for (Object key : localContext.getAttributeKeySet()) { + String parmName = (String) key; + String parmValue = ctx.getAttribute(parmName); + log.debug("processFlow " + parmName + "=" + parmValue); + + } + processFlowSequence(inParams, ctx, localContext); + if(!ctx.getAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_STATUS).equals(FlowControllerConstants.OUTPUT_STATUS_SUCCESS)) + throw new SvcLogicException(ctx.getAttribute(responsePrefix + FlowControllerConstants.OUTPUT_STATUS_MESSAGE)); + + } catch (Exception e) { + ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_STATUS, FlowControllerConstants.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + e.printStackTrace(); + throw new SvcLogicException(e.getMessage()); + } + } + + private void processFlowSequence( Map inParams, SvcLogicContext ctx, SvcLogicContext localContext) throws Exception + { + String fn = "FlowExecutorNode.processflowSequence"; + log.debug(fn + "Received model for flow : " + localContext.toString()); + FlowControlDBService dbservice = FlowControlDBService.initialise(); + String flowSequnce =null; + for (Object key : localContext.getAttributeKeySet()) { + String parmName = (String) key; + String parmValue = ctx.getAttribute(parmName); + log.debug(parmName + "=" + parmValue); + + } + if(localContext != null && localContext.getAttribute(FlowControllerConstants.SEQUENCE_TYPE) !=null){ + + if(localContext.getAttribute(FlowControllerConstants.GENERATION_NODE) != null){ + GraphExecutor transactionExecutor = new GraphExecutor(); + Boolean generatorExists = transactionExecutor.hasGraph("APPC_COMMOM", localContext.getAttribute(FlowControllerConstants.GENERATION_NODE), null, "sync"); + if(generatorExists){ + flowSequnce = transactionExecutor.executeGraph("APPC_COMMOM", localContext.getAttribute(FlowControllerConstants.GENERATION_NODE), + null, "sync", null).getProperty(FlowControllerConstants.FLOW_SEQUENCE); + } + else + throw new Exception("Can not find Custom defined Flow Generator for " + localContext.getAttribute(FlowControllerConstants.GENERATION_NODE)); + } + else if(((String) localContext.getAttribute(FlowControllerConstants.SEQUENCE_TYPE)).equalsIgnoreCase(FlowControllerConstants.DESINGTIME)){ + localContext.setAttribute(FlowControllerConstants.VNFC_TYPE, ctx.getAttribute(FlowControllerConstants.VNFC_TYPE)); + flowSequnce = dbservice.getDesignTimeFlowModel(localContext); + if(flowSequnce == null) + throw new Exception("Flow Sequence is not found User Desinged VNF " + ctx.getAttribute(FlowControllerConstants.VNF_TYPE)); + } + else if(((String) localContext.getAttribute(FlowControllerConstants.SEQUENCE_TYPE)).equalsIgnoreCase(FlowControllerConstants.RUNTIME)){ + + Transaction transaction = new Transaction(); + String input = collectInputParams(ctx,transaction); + log.info("collectInputParamsData" + input ); + + RestExecutor restExe = new RestExecutor(); + HashMapflowSeq= restExe.execute(transaction, localContext); + flowSequnce=flowSeq.get("restResponse"); + + if(flowSequnce == null) + throw new Exception("Failed to get the Flow Sequece runtime for VNF type" + ctx.getAttribute(FlowControllerConstants.VNF_TYPE)); + + } + else if(((String) localContext.getAttribute(FlowControllerConstants.SEQUENCE_TYPE)).equalsIgnoreCase(FlowControllerConstants.EXTERNAL)){ + //String input = collectInputParams(localContext); + // flowSequnce = ""; //get it from the External interface calling the Rest End point - TBD + if(flowSequnce == null) + throw new Exception("Flow Sequence not found for " + ctx.getAttribute(FlowControllerConstants.VNF_TYPE)); + } + else + { + //No other type of model supported...in Future can get flowModel from other generators which will be included here + throw new Exception("No information found for sequence Owner Design-Time Vs Run-Time" ); + } + } + else{ + FlowGenerator flowGenerator = new FlowGenerator(); + Transactions trans = flowGenerator.createSingleStepModel(inParams,ctx); + ObjectMapper mapper = new ObjectMapper(); + flowSequnce = mapper.writeValueAsString(trans); + log.debug("Single step Flow Sequence : " + flowSequnce); + + } + log.debug("Received Flow Sequence : " + flowSequnce); + + HashMap transactionMap = createTransactionMap(flowSequnce, localContext); + exeuteAllTransaction(transactionMap, ctx); + log.info("Executed all the transacstion successfully"); + + } + + private void exeuteAllTransaction(HashMap transactionMap, SvcLogicContext ctx) throws Exception { + + String fn = "FlowExecutorNode.exeuteAllTransaction "; + int retry = 0; + FlowExecutorInterface flowExecutor = null; + for (int key = 1; key <= transactionMap.size() ; key++ ) + { + log.debug(fn + "Starting transactions ID " + key + " :)=" + retry); + Transaction transaction = transactionMap.get(key); + if(!preProcessor(transactionMap, transaction)){ + log.info("Skipping Transaction ID " + transaction.getTransactionId()); + continue; + } + if(transaction.getExecutionType() != null){ + switch (transaction.getExecutionType()){ + case FlowControllerConstants.GRAPH : + flowExecutor = new GraphExecutor(); + break; + case FlowControllerConstants.NODE : + flowExecutor = new NodeExecutor(); + break; + case FlowControllerConstants.REST : + flowExecutor = new RestExecutor(); + break; + default : + throw new Exception("No Executor found for transaction ID" + transaction.getTransactionId()); + } + flowExecutor.execute(transaction, ctx); + ResponseAction responseAction= handleResponse(transaction); + + if(responseAction.getWait() != null && Integer.parseInt(responseAction.getWait()) > 0){ + log.debug(fn + "Going to Sleep .... " + responseAction.getWait()); + Thread.sleep(Integer.parseInt(responseAction.getWait())*1000); + } + + if(responseAction.isIntermediateMessage()){ + log.debug(fn + "Sending Intermediate Message back .... "); + sendIntermediateMessage(); + } + if(responseAction.getRetry() != null && Integer.parseInt(responseAction.getRetry()) > retry ){ + log.debug(fn + "Ooppss!!! We will retry again ....... "); + key--; + retry++; + log.debug(fn + "key =" + key + "retry =" + retry); + + } + if(responseAction.isIgnore()){ + log.debug(fn + "Ignoring this Error and moving ahead ....... "); + continue; + } + if(responseAction.isStop()){ + log.debug(fn + "Need to Stop ....... "); + break; + } + if(responseAction.getJump() != null && Integer.parseInt(responseAction.getJump()) > 0 ){ + key = Integer.parseInt(responseAction.getJump()); + key --; + } + log.debug(fn + "key =" + key + "retry =" + retry); + + } + else{ + throw new Exception("Don't know how to execute transaction ID " + transaction.getTransactionId()); + } + } + + } + private void sendIntermediateMessage() { + // TODO Auto-generated method stub + + } + + private ResponseAction handleResponse(Transaction transaction) { + log.info("Handling Response for transaction Id " + transaction.getTransactionId()); + DefaultResponseHandler defaultHandler = new DefaultResponseHandler(); + return defaultHandler.handlerResponse(transaction); + } + + private boolean preProcessor(HashMap transactionMap, Transaction transaction) throws IOException { + + log.debug("Starting Preprocessing Logic "); + boolean runthisStep = false; + try{ + if(transaction.getPrecheck() != null && transaction.getPrecheck().getPrecheckOptions() != null + && !transaction.getPrecheck().getPrecheckOptions().isEmpty()){ + List precheckOptions = transaction.getPrecheck().getPrecheckOptions(); + for(PrecheckOption precheck : precheckOptions){ + Transaction trans = transactionMap.get(precheck.getpTransactionID()); + ObjectMapper mapper = new ObjectMapper(); + log.info("Mapper= " + mapper.writeValueAsString(trans)); + HashMap trmap = mapper.readValue(mapper.writeValueAsString(trans), HashMap.class); + if(trmap.get(precheck.getParamName()) != null && + ((String) trmap.get(precheck.getParamName())).equalsIgnoreCase(precheck.getParamValue())) + runthisStep = true; + else + runthisStep = false; + + if(transaction.getPrecheck().getPrecheckOperator() != null && + transaction.getPrecheck().getPrecheckOperator().equalsIgnoreCase("any") && runthisStep) + break; + } + } + + else{ + log.debug("No Pre check defined for transaction ID " + transaction.getTransactionId()); + runthisStep = true; + + } + } + catch(Exception e) + { + e.printStackTrace(); + throw e; + } + log.debug("Returing process current Transaction = " + runthisStep); + + return runthisStep ; + } + + private HashMap createTransactionMap(String flowSequnce, SvcLogicContext localContext) throws SvcLogicException, JsonParseException, JsonMappingException, IOException { + ObjectMapper mapper = new ObjectMapper(); + Transactions transactions = mapper.readValue(flowSequnce,Transactions.class); + HashMap transMap = new HashMap(); + for(Transaction transaction : transactions.getTransactions()){ + compileFlowDependencies(transaction, localContext); + //loadTransactionIntoStatus(transactions, ctx); //parse the Transactions Object and create records in process_flow_status table + transMap.put(transaction.getTransactionId(), transaction); + } + return transMap; + } + + private void compileFlowDependencies(Transaction transaction, SvcLogicContext localContext) throws SvcLogicException, JsonParseException, JsonMappingException, IOException { + + String fn = "FlowExecutorNode.compileFlowDependencies"; + FlowControlDBService dbservice = FlowControlDBService.initialise(); + dbservice.populateModuleAndRPC(transaction, localContext.getAttribute(FlowControllerConstants.VNF_TYPE)); + ObjectMapper mapper = new ObjectMapper(); + log.debug("Indivisual Transaction Details :" + transaction.toString()); + if((localContext.getAttribute(FlowControllerConstants.SEQUENCE_TYPE) == null) || + ( localContext.getAttribute(FlowControllerConstants.SEQUENCE_TYPE) != null && + ! localContext.getAttribute(FlowControllerConstants.SEQUENCE_TYPE).equalsIgnoreCase(FlowControllerConstants.DESINGTIME))){ + localContext.setAttribute("artifact-content", mapper.writeValueAsString(transaction)); + dbservice.loadSequenceIntoDB(localContext); + } + //get a field in transction class as transactionhandle interface and register the Handler here for each trnactions + } + + private String collectInputParams(SvcLogicContext ctx, Transaction transaction) throws Exception { + + String fn = "FlowExecuteNode.collectInputParams"; + Properties prop = loadProperties(); + log.info("Loaded Properties " + prop.toString()); + + String vnfId = ctx.getAttribute(FlowControllerConstants.VNF_ID); + log.debug(fn + "vnfId :" + vnfId); + + if (StringUtils.isBlank(vnfId)) { + throw new Exception("VnfId is missing"); + } + + ActionIdentifier actionIdentifier = new ActionIdentifier(); + actionIdentifier.setVnfId(vnfId); + actionIdentifier.setVserverId(ctx.getAttribute(FlowControllerConstants.VSERVER_ID)); + actionIdentifier.setVnfcName(ctx.getAttribute(FlowControllerConstants.VNFC_NAME)); + + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setAction(ctx.getAttribute(FlowControllerConstants.ACTION)); + requestInfo.setActionLevel(ctx.getAttribute(FlowControllerConstants.ACTION_LEVEL)); + requestInfo.setPayload(ctx.getAttribute(FlowControllerConstants.PAYLOAD)); + requestInfo.setActionIdentifier(actionIdentifier); + + InventoryInfo inventoryInfo = getInventoryInfo(ctx,vnfId); + DependencyInfo dependencyInfo = getDependencyInfo(ctx); + Capabilities capabilites = getCapabilitesData(ctx); + + Input input = new Input(); + input.setRequestInfo(requestInfo); + input.setInventoryInfo(inventoryInfo); + input.setDependencyInfo(dependencyInfo); + input.setCapabilities(capabilites); + //input.setTunableParameters(null); + + + log.info(fn + "Input parameters:" + input.toString()); + + String inputData = null; + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_NULL); + mapper.configure(SerializationFeature.WRAP_ROOT_VALUE,true); + inputData = mapper.writeValueAsString(input); + log.info("InputDataJson:"+inputData); + + } catch (Exception e) { + e.printStackTrace(); + } + + String resourceUri = prop.getProperty(FlowControllerConstants.SEQ_GENERATOR_URL); + log.info(fn + "resourceUri= " + resourceUri); + + transaction.setPayload(inputData); + transaction.setExecutionRPC("POST"); + transaction.setuId(prop.getProperty(FlowControllerConstants.SEQ_GENERATOR_UID)); + transaction.setPswd(prop.getProperty(FlowControllerConstants.SEQ_GENERATOR_PWD)); + transaction.setExecutionEndPoint(resourceUri); + + return inputData; + + } + + private DependencyInfo getDependencyInfo(SvcLogicContext ctx) throws Exception { + + String fn = "FlowExecutorNode.getDependencyInfo"; + DependencyInfo dependencyInfo = new DependencyInfo(); + FlowControlDBService dbservice = FlowControlDBService.initialise(); + String dependencyData = dbservice.getDependencyInfo(ctx); + log.info(fn + "dependencyDataInput:" + dependencyData); + + if (dependencyData != null) { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false); + mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); + JsonNode dependencyInfoData = mapper.readTree(dependencyData).get("dependencyInfo"); + JsonNode vnfcData = mapper.readTree(dependencyInfoData.toString()).get("vnfcs"); + List vnfclist = Arrays.asList(mapper.readValue(vnfcData.toString(), Vnfcs[].class)); + dependencyInfo.getVnfcs().addAll(vnfclist); + + log.info("Dependency Output:"+ dependencyInfo.toString()); + } + + return dependencyInfo; + + } + + private Capabilities getCapabilitesData(SvcLogicContext ctx)throws Exception { + + String fn = "FlowExecutorNode.getCapabilitesData"; + Capabilities capabilities = new Capabilities(); + FlowControlDBService dbservice = FlowControlDBService.initialise(); + String capabilitiesData = dbservice.getCapabilitiesData(ctx); + log.info(fn + "capabilitiesDataInput:" + capabilitiesData); + + if (capabilitiesData != null) { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false); + mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); + JsonNode capabilitiesNode = mapper.readValue(capabilitiesData,JsonNode.class); + log.info("capabilitiesNode:" + capabilitiesNode.toString()); + + JsonNode vnfs = capabilitiesNode.findValue(FlowControllerConstants.VNF); + List vnfsList = new ArrayList(); + if (vnfs != null) { + for (int i = 0; i < vnfs.size(); i++) { + + String vnf = vnfs.get(i).asText(); + vnfsList.add(vnf); + } + } + + JsonNode vfModules = capabilitiesNode.findValue(FlowControllerConstants.VF_MODULE); + List vfModulesList = new ArrayList(); + if (vfModules != null) { + for (int i = 0; i < vfModules.size(); i++) { + + String vfModule = vfModules.get(i).asText(); + vfModulesList.add(vfModule); + } + } + + JsonNode vnfcs = capabilitiesNode.findValue(FlowControllerConstants.VNFC); + List vnfcsList = new ArrayList(); + if (vnfcs != null) { + for (int i = 0; i < vnfcs.size(); i++) { + + String vnfc1 = vnfcs.get(i).asText(); + vnfcsList.add(vnfc1); + } + } + + JsonNode vms = capabilitiesNode.findValue(FlowControllerConstants.VM); + + List vmList = new ArrayList(); + if (vms != null) { + for (int i = 0; i < vms.size(); i++) { + + String vm1 = vms.get(i).asText(); + vmList.add(vm1); + } + } + + capabilities.getVnfc().addAll(vnfcsList); + capabilities.getVnf().addAll(vnfsList); + capabilities.getVfModule().addAll(vfModulesList); + capabilities.getVm().addAll(vmList); + + log.info("Capabilities Output:"+ capabilities.toString()); + + } + + return capabilities; + + } + + private InventoryInfo getInventoryInfo(SvcLogicContext ctx, String vnfId) throws Exception{ + + String fn = "FlowExecutorNode.getInventoryInfo"; + String vmcount = ctx.getAttribute("tmp.vnfInfo.vm-count"); + int vmCount = Integer.parseInt(vmcount); + log.info(fn +"vmcount:"+ vmCount); + + VnfInfo vnfInfo = new VnfInfo(); + vnfInfo.setVnfId(vnfId); + vnfInfo.setVnfName(ctx.getAttribute("tmp.vnfInfo.vnf.vnf-name")); + vnfInfo.setVnfType(ctx.getAttribute("tmp.vnfInfo.vnf.vnf-type")); + + Vm vm = new Vm(); + Vnfcslist vnfc = new Vnfcslist(); + + if (vmCount > 0) { + + for (int i = 0; i < vmCount; i++) { + + vm.setVserverId(ctx.getAttribute("tmp.vnfInfo.vm[" + i + "].vserverId")); + String vnfccount = ctx.getAttribute("tmp.vnfInfo.vm[" + i + "].vnfc-count"); + int vnfcCount = Integer.parseInt(vnfccount); + + if (vnfcCount > 0) { + vnfc.setVnfcName(ctx.getAttribute("tmp.vnfInfo.vm[" + i + "].vnfc-name")); + vnfc.setVnfcType(ctx.getAttribute("tmp.vnfInfo.vm[" + i + "].vnfc-type")); + vm.setVnfc(vnfc); + } + vnfInfo.getVm().add(vm); + } + } + + InventoryInfo inventoryInfo = new InventoryInfo(); + inventoryInfo.setVnfInfo(vnfInfo); + + return inventoryInfo; + + } + + private String getFlowSequence() throws IOException { + + String sequenceModel = IOUtils.toString(FlowControlNode.class.getClassLoader().getResourceAsStream("sequence.json"), Charset.defaultCharset()); + + return null; + } + + +private static Properties loadProperties() throws Exception { + Properties props = new Properties(); + String propDir = System.getenv(SDNC_CONFIG_DIR_VAR); + if (propDir == null) + throw new Exception("Cannot find Property file -" + SDNC_CONFIG_DIR_VAR); + String propFile = propDir + FlowControllerConstants.APPC_FLOW_CONTROLLER; + InputStream propStream = new FileInputStream(propFile); + try + { + props.load(propStream); + } + catch (Exception e) + { + throw new Exception("Could not load properties file " + propFile, e); + } + finally + { + try + { + propStream.close(); + } + catch (Exception e) + { + log.warn("Could not close FileInputStream", e); + } + } + return props; +} + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/node/FlowGenerator.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/node/FlowGenerator.java new file mode 100644 index 000000000..fe894c955 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/node/FlowGenerator.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.node; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.onap.appc.flow.controller.data.Response; +import org.onap.appc.flow.controller.data.ResponseAction; +import org.onap.appc.flow.controller.data.Transaction; +import org.onap.appc.flow.controller.data.Transactions; +import org.onap.appc.flow.controller.utils.FlowControllerConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class FlowGenerator { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(FlowGenerator.class); + + public Transactions createSingleStepModel(Map inParams, SvcLogicContext ctx) { + + String fn = "FlowGenerator.createSingleStepModel"; + log.debug("Starting generating single Step flow" ); + + log.debug("Data in context" + ctx.getAttributeKeySet() ); + Transactions transactions = new Transactions(); + List transactionList = new ArrayList(); + Transaction singleTransaction = new Transaction(); + + singleTransaction.setTransactionId(1); + singleTransaction.setAction(ctx.getAttribute(FlowControllerConstants.REQUEST_ACTION)); + singleTransaction.setActionLevel(FlowControllerConstants.VNF); //Need to discuss how to get action level if not in request + singleTransaction.setPayload(ctx.getAttribute(FlowControllerConstants.PAYLOAD)); + singleTransaction.setActionLevel(ctx.getAttribute(FlowControllerConstants.ACTION_LEVEL)); + + + + + List responseList = new ArrayList(); + Response response = new Response(); + + ResponseAction ra = new ResponseAction(); + ra.setStop(true); + response.setResponseAction(ra); + + responseList.add(response); + singleTransaction.setResponses(responseList); + transactionList.add(singleTransaction); + + transactions.setTransactions(transactionList); + + log.debug("Sequence String" + transactions.toString()); + + return transactions; + } + + + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/node/JsonParsingNode.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/node/JsonParsingNode.java new file mode 100644 index 000000000..dd56aee60 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/node/JsonParsingNode.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.node; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.flow.controller.data.Transaction; +import org.onap.appc.flow.controller.executorImpl.RestExecutor; +import org.onap.appc.flow.controller.utils.FlowControllerConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JsonParsingNode implements SvcLogicJavaPlugin{ + + + private static final EELFLogger log = EELFManager.getInstance().getLogger(JsonParsingNode.class); + private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; + + public void parse(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + String fn = "RestServiceNode.sendRequest"; + log.info("Received processParamKeys call with params : " + inParams); + String responsePrefix = inParams.get(FlowControllerConstants.INPUT_PARAM_RESPONSE_PRIFIX); + try + { + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + //Remove below for Block + if(isValidJSON(inParams.get("data")) !=null){ + JsonNode jnode = isValidJSON(inParams.get("data")); + ObjectMapper mapper = new ObjectMapper(); + Map map = new HashMap(); + map = mapper.readValue(jnode.toString(), new TypeReference>(){}); + for (Entry entry : map.entrySet()) + { + ctx.setAttribute(responsePrefix + entry.getKey(),(String) entry.getValue()); + } + + } + ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_STATUS, FlowControllerConstants.OUTPUT_STATUS_SUCCESS); + + } catch (Exception e) { + ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_STATUS, FlowControllerConstants.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + e.printStackTrace(); + log.error("Error Message : " + e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + } + + public JsonNode isValidJSON(String json) throws IOException { + JsonNode output = null; + log.info("Received response from Interface " + json); + if(json ==null || json.isEmpty()) + return null; + try{ + ObjectMapper objectMapper = new ObjectMapper(); + output = objectMapper.readTree(json); + } catch(JsonProcessingException e){ + log.warn("Response received from interface is not a valid JSON block" + json); + return null; + } + + return output; + } +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/node/RestServiceNode.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/node/RestServiceNode.java new file mode 100644 index 000000000..1975de3d9 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/node/RestServiceNode.java @@ -0,0 +1,207 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.node; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.flow.controller.data.Transaction; +import org.onap.appc.flow.controller.executorImpl.RestExecutor; +import org.onap.appc.flow.controller.utils.FlowControllerConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class RestServiceNode implements SvcLogicJavaPlugin{ + + + private static final EELFLogger log = EELFManager.getInstance().getLogger(RestServiceNode.class); + private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; + + public void sendRequest(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + String fn = "RestServiceNode.sendRequest"; + log.info("Received processParamKeys call with params : " + inParams); + String responsePrefix = inParams.get(FlowControllerConstants.INPUT_PARAM_RESPONSE_PRIFIX); + try + { + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + //Remove below for Block + for (Object key : ctx.getAttributeKeySet()) { + String parmName = (String) key; + String parmValue = ctx.getAttribute(parmName); + log.info(fn + "Getting Key = " + parmName + "and Value = " + parmValue); + } + + send(ctx, inParams); + ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_STATUS, FlowControllerConstants.OUTPUT_STATUS_SUCCESS); + + } catch (Exception e) { + ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_STATUS, FlowControllerConstants.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + e.printStackTrace(); + log.error("Error Message : " + e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + } + + public void send(SvcLogicContext ctx, Map inParams) throws Exception{ + try{ + Properties prop = loadProperties(); + log.info("Loaded Properties " + prop.toString()); + String responsePrefix = inParams.get(FlowControllerConstants.INPUT_PARAM_RESPONSE_PRIFIX); + RestExecutor restRequestExecutor = new RestExecutor(); + String resourceUri = ""; + if(ctx.getAttribute(FlowControllerConstants.INPUT_URL) != null && !(ctx.getAttribute(FlowControllerConstants.INPUT_URL).isEmpty())) + resourceUri = ctx.getAttribute(FlowControllerConstants.INPUT_URL); + else{ + resourceUri = resourceUri.concat(FlowControllerConstants.HTTP); + log.info("resourceUri= " + resourceUri ); + resourceUri = resourceUri.concat(ctx.getAttribute(FlowControllerConstants.INPUT_HOST_IP_ADDRESS)); + resourceUri = resourceUri.concat(":"); + resourceUri = resourceUri.concat(ctx.getAttribute(FlowControllerConstants.INPUT_PORT_NUMBER)); + + if(ctx.getAttribute(FlowControllerConstants.INPUT_CONTEXT) != null && !ctx.getAttribute(FlowControllerConstants.INPUT_CONTEXT).isEmpty()){ + resourceUri = resourceUri.concat("/").concat(ctx.getAttribute(FlowControllerConstants.INPUT_CONTEXT)); + log.info("resourceUri= " + resourceUri ); + } + else if(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".context")) != null ){ + log.info("resourceUri = " + resourceUri ); + resourceUri = resourceUri.concat("/").concat(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".context"))); + } + else + throw new Exception("Could Not found the context for operation " + ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION)); + + + if(ctx.getAttribute(FlowControllerConstants.INPUT_SUB_CONTEXT) != null && !ctx.getAttribute(FlowControllerConstants.INPUT_SUB_CONTEXT).isEmpty()){ + resourceUri = resourceUri.concat("/").concat(ctx.getAttribute(FlowControllerConstants.INPUT_SUB_CONTEXT)); + log.info("resourceUri" + resourceUri ); + } + else if(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".sub-context")) != null ){ + resourceUri = resourceUri.concat("/").concat(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".sub-context"))); + log.info("resourceUri" + resourceUri ); + } + } + + log.info("Rest Constructed URL : " + resourceUri); + Transaction transaction = new Transaction(); + + transaction.setExecutionEndPoint(resourceUri); + transaction.setExecutionRPC(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION_TYPE)); + transaction.setAction(FlowControllerConstants.INPUT_REQUEST_ACTION); + if(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION_TYPE) == null || ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION_TYPE).isEmpty()) + throw new Exception("Dont know REST operation for Action " + transaction.getExecutionRPC()); + if(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION) == null || ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).isEmpty()) + throw new Exception("Dont know request-action " + transaction.getAction()); + + //This code need to get changed to get the UserID and pass from a common place. + if(transaction.getuId() == null ) + transaction.setuId(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".default-rest-user"))); + if(transaction.getPswd() == null) + transaction.setPswd(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".default-rest-pass"))); + + HashMap output = restRequestExecutor.execute(transaction, ctx); + + if(output.get("restResponse") !=null && isValidJSON(output.get("restResponse")) != null) + { + ctx.setAttribute(responsePrefix + "." + FlowControllerConstants.OUTPUT_STATUS_MESSAGE , output.get("restResponse")); +// JsonNode restResponse = isValidJSON(output.get("restResponse")); +// for (String key : inParams.keySet()) { +// if(key !=null && key.startsWith("output-")){ +// log.info("Found Key = " + key); +// log.info("Found Key in Params " + inParams.get(key) + "."); +// JsonNode setValue = restResponse.findValue(inParams.get(key)); +// log.info("Found value = " + setValue); +// if(setValue !=null && setValue.textValue() !=null && !setValue.textValue().isEmpty()) +// ctx.setAttribute(responsePrefix + "." + key, setValue.textValue()); +// else +// ctx.setAttribute(responsePrefix + "." + key, null); +// } +// } + } + log.info("Response from Rest :" ); + } + catch(Exception e) + { + e.printStackTrace(); + log.error("Error Message " + e.getMessage()); + throw e; + } + } + + private Properties loadProperties() throws Exception { + Properties props = new Properties(); + String propDir = System.getenv(SDNC_CONFIG_DIR_VAR); + if (propDir == null) + throw new Exception("Cannot find Property file -" + SDNC_CONFIG_DIR_VAR); + String propFile = propDir + FlowControllerConstants.APPC_FLOW_CONTROLLER; + InputStream propStream = new FileInputStream(propFile); + try + { + props.load(propStream); + } + catch (Exception e) + { + throw new Exception("Could not load properties file " + propFile, e); + } + finally + { + try + { + propStream.close(); + } + catch (Exception e) + { + log.warn("Could not close FileInputStream", e); + } + } + // TODO Auto-generated method stub + return props; + } + + public JsonNode isValidJSON(String json) throws IOException { + JsonNode output = null; + log.info("Received response from Interface " + json); + if(json ==null || json.isEmpty()) + return null; + try{ + ObjectMapper objectMapper = new ObjectMapper(); + output = objectMapper.readTree(json); + } catch(JsonProcessingException e){ + log.warn("Response received from interface is not a valid JSON block" + json); + return null; + } + log.info("state is " + output.findValue("state")); + + return output; + } +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/utils/EscapeUtils.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/utils/EscapeUtils.java new file mode 100644 index 000000000..40bf7593f --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/utils/EscapeUtils.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.utils; + +import org.apache.commons.lang3.StringUtils; + +public class EscapeUtils { + + public EscapeUtils() { + } + + public static String escapeSql(String str) { + if (str == null) { + return null; + } + String searchList[] = new String[]{"'","\\", "\"" }; + String replacementList[] = new String[]{ "''","\\\\" ,"\\\""}; + return StringUtils.replaceEach(str,searchList, replacementList); + } + +} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/utils/FlowControllerConstants.java b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/utils/FlowControllerConstants.java new file mode 100644 index 000000000..1881e3e45 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/main/java/org/onap/appc/flow/controller/utils/FlowControllerConstants.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.controller.utils; + +public class FlowControllerConstants { + + public static String STRING_ENCODING = "utf-8"; + public static String Y = "Y"; + public static String N = "N"; + public static String DATA_TYPE_TEXT = "TEXT"; + public static String DATA_TYPE_JSON = "JSON"; + public static String DATA_TYPE_XML = "XML"; + public static String DATA_TYPE_SQL = "SQL"; + + public static String INPUT_PARAM_RESPONSE_PRIFIX = "responsePrefix"; + + public static String OUTPUT_PARAM_STATUS = "status"; + public static String OUTPUT_PARAM_ERROR_MESSAGE = "error-message"; + public static String OUTPUT_STATUS_SUCCESS = "success"; + public static String OUTPUT_STATUS_FAILURE = "failure"; + + public static final String DESINGTIME = "DesignTime"; + public static final String RUNTIME = "RunTime"; + public static final String APPC_FLOW_CONTROLLER = "/appc-flow-controller.properties"; + public static final String VNF_TYPE = "vnf-type"; + public static final String ACTION = "action"; + public static final String VNFC_TYPE = "vnfc-type"; + public static final String VM_INSTANCE = "vm-instance"; + public static final String VM = "vm"; + public static final String VNFC = "vnfc"; + public static final String REFERENCE = "reference"; + public static final String VNFC_INSTANCE = "vnfc-instance"; + public static final String DEVICE_PROTOCOL = "device-protocol"; + public static final String DG_RPC = "dg-rpc"; + public static final String MODULE = "module"; + public static final String USER_NAME = "user-name"; + public static final String PORT_NUMBER = "port-number"; + public static final String DOWNLOAD_DG_REFERENCE = "download-dg-reference"; + public static final String REQUEST_ACTION = "request-action"; + public static final String VNF = "vnf"; + public static final String EXTERNAL = "External"; + public static final String ACTION_LEVEL = "action-level"; + public static final String ARTIFACT_NAME = "artifact-name"; + + public static enum endPointType {DG,REST,NODE}; + public static enum flowStatus {PENDING,IN_PROCESS,COMPLETED}; + + public static final String GENERATION_NODE = "GENERATION-NODE"; + public static final String SEQUENCE_TYPE = "SEQUENCE-TYPE"; + public static final String CATEGORY = "CATEGORY"; + public static final String EXECUTION_NODE = "EXECUTION-NODE"; + + + public static final String REQUEST_ID = "reqeust-id"; + public static final String ARTIFACT_CONTENT = "artifact-content"; + public static final String ARTIFACT_CONTENT_ESCAPED = "artifact-content-escaped"; + public static final String FLOW_SEQUENCE = "flow-sequence"; + public static final String EXECUTTION_MODULE = "execution-module"; + public static final String EXECUTION_RPC = "execution-rpc"; + public static final String EXECUTION_TYPE = "execution-type"; + public static final String GRAPH = "graph"; + public static final String NODE = "node"; + public static final String REST = "rest"; + + + public static final String DB_SDC_ARTIFACTS = "ASDC_ARTIFACTS"; + public static final String DB_SDC_REFERENCE = "ASDC_REFERENCE"; + public static final String DB_REQUEST_ARTIFACTS = "REQUEST_ARTIFACTS"; + public static final String DB_MULTISTEP_FLOW_REFERENCE = "MULTISTEP_FLOW_REFERENCE"; + public static final String DB_PROTOCOL_REFERENCE = "PROTOCOL_REFERENCE"; + public static final String DB_PROCESS_FLOW_REFERENCE = "PROCESS_FLOW_REFERENCE"; + public static final String MOCK_HEALTHCHECK = "mock-healthcheck"; + public static final String ACTION_IDENTIFIER = "action-identifier"; + public static final String PAYLOAD = "payload"; + public static final String FAILURE = "failure"; + public static final String SUCCESS = "success"; + public static final String OTHERS = "Others"; + public static final String RESPONSE_PREFIX = "response-prefix"; + public static final String OUTPUT_STATUS_MESSAGE = "status-message"; + public static final String HEALTHY = "healthy"; + public static final String INPUT_URL = "input.url"; + public static final String INPUT_HOST_IP_ADDRESS = "host-ip-address"; + public static final String INPUT_PORT_NUMBER = "port-number"; + public static final String INPUT_CONTEXT = "context"; + public static final String INPUT_SUB_CONTEXT = "sub-context"; + public static final String INPUT_REQUEST_ACTION_TYPE = "request-action-type"; + public static final String INPUT_REQUEST_ACTION = "request-action"; + public static final String HTTP = "http://"; + + public static final String VNF_ID = "vnf-id"; + public static final String VSERVER_ID = "vserver-id"; + public static final String SEQ_GENERATOR_URL = "seq_generator_url"; + public static final String SEQ_GENERATOR_UID = "seq_generator.uid"; + public static final String SEQ_GENERATOR_PWD = "seq_generator.pwd"; + public static final String CAPABILITY ="capability"; + public static final String DEPENDENCYMODEL ="tosca_dependency_model"; + public static final String VF_MODULE ="vf-module"; + public static final String VNFC_NAME = "vnfc-name"; + } diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/FlowControllerActivator.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/FlowControllerActivator.java deleted file mode 100644 index 4e8370024..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/FlowControllerActivator.java +++ /dev/null @@ -1,80 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller; - -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; - -import org.onap.appc.flow.controller.node.FlowControlNode; -import org.onap.appc.flow.controller.node.JsonParsingNode; -import org.onap.appc.flow.controller.node.RestServiceNode; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class FlowControllerActivator implements BundleActivator{ - - private List registrations = new LinkedList(); - - - private static final EELFLogger log = EELFManager.getInstance().getLogger(FlowControllerActivator.class); - - @Override - public void start(BundleContext ctx) throws Exception - { - - try { - - FlowControlNode flowExecutorNode = new FlowControlNode(); - log.debug("Registering service "+ flowExecutorNode.getClass().getName()); - registrations.add(ctx.registerService(flowExecutorNode.getClass().getName(), flowExecutorNode, null)); - log.debug("Registering service sccessful for "+ flowExecutorNode.getClass().getName()); - - RestServiceNode restServiceNode = new RestServiceNode(); - log.debug("Registering service "+ restServiceNode.getClass().getName()); - registrations.add(ctx.registerService(restServiceNode.getClass().getName(), restServiceNode, null)); - log.debug("Registering service sccessful for "+ restServiceNode.getClass().getName()); - - JsonParsingNode jsonParsingNode = new JsonParsingNode(); - log.debug("Registering service "+ jsonParsingNode.getClass().getName()); - registrations.add(ctx.registerService(jsonParsingNode.getClass().getName(), jsonParsingNode, null)); - log.debug("Registering service sccessful for "+ jsonParsingNode.getClass().getName()); - - } catch (Exception e) { - e.printStackTrace(); - } - - } - @Override - public void stop(BundleContext arg0) throws Exception - { - for (ServiceRegistration registration: registrations) - { - registration.unregister(); - registration = null; - } - - } -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/ResponseHandlerImpl/DefaultResponseHandler.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/ResponseHandlerImpl/DefaultResponseHandler.java deleted file mode 100644 index 2a0edb086..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/ResponseHandlerImpl/DefaultResponseHandler.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.ResponseHandlerImpl; - -import java.util.ArrayList; -import java.util.List; - -import org.onap.appc.flow.controller.data.Response; -import org.onap.appc.flow.controller.data.ResponseAction; -import org.onap.appc.flow.controller.data.Transaction; -import org.onap.appc.flow.controller.utils.FlowControllerConstants; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -public class DefaultResponseHandler { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(DefaultResponseHandler.class); - - public ResponseAction handlerResponse(Transaction transaction){ - - log.info("Transaction Input params " + transaction.toString()); - ResponseAction responseAction = new ResponseAction(); - if(transaction.getResponses() != null && !transaction.getResponses().isEmpty()){ - for(Response response : transaction.getResponses()){ - if(response.getResponseCode() != null && response.getResponseCode().equals(transaction.getStatusCode())){ - responseAction = response.getResponseAction(); - break; - } - - } - - } - return responseAction ; - } -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/ActionIdentifier.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/ActionIdentifier.java deleted file mode 100644 index abce46862..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/ActionIdentifier.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.data; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class ActionIdentifier { - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((vnfId == null) ? 0 : vnfId.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ActionIdentifier other = (ActionIdentifier) obj; - if (vnfId == null) { - if (other.vnfId != null) - return false; - } else if (!vnfId.equals(other.vnfId)) - return false; - return true; - } - - @JsonProperty("vnf-id") - private String vnfId ; - - public String getVnfId() { - return vnfId; - } - - public void setVnfId(String vnfId) { - this.vnfId = vnfId; - } - - @Override - public String toString() { - return "ActionIdentifier [vnfId=" + vnfId + "]"; - } - - - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/Parameters.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/Parameters.java deleted file mode 100644 index 8320b15fe..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/Parameters.java +++ /dev/null @@ -1,82 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.data; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class Parameters { - - - @JsonProperty("name") - private String paramName ; - - @JsonProperty("value") - private String paramValue ; - - - public String getParamValue() { - return paramValue; - } - public void setParamValue(String paramValue) { - this.paramValue = paramValue; - } - public String getParamName() { - return paramName; - } - public void setParamName(String paramName) { - this.paramName = paramName; - } - @Override - public String toString() { - return "Parameters [paramName=" + paramName + ", paramValue=" + paramValue + "]"; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((paramName == null) ? 0 : paramName.hashCode()); - result = prime * result + ((paramValue == null) ? 0 : paramValue.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Parameters other = (Parameters) obj; - if (paramName == null) { - if (other.paramName != null) - return false; - } else if (!paramName.equals(other.paramName)) - return false; - if (paramValue == null) { - if (other.paramValue != null) - return false; - } else if (!paramValue.equals(other.paramValue)) - return false; - return true; - } - - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/PreCheck.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/PreCheck.java deleted file mode 100644 index db76895ab..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/PreCheck.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.data; - -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class PreCheck { - - - @JsonProperty("precheck-operator") - private String precheckOperator; - - public String getPrecheckOperator() { - return precheckOperator; - } - - public void setPrecheckOperator(String precheckOperator) { - this.precheckOperator = precheckOperator; - } - - @JsonProperty("precheck-options") - private List precheckOptions; - - public List getPrecheckOptions() { - return precheckOptions; - } - - public void setPrecheckOptions(List precheckOptions) { - this.precheckOptions = precheckOptions; - } - - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((precheckOperator == null) ? 0 : precheckOperator.hashCode()); - result = prime * result + ((precheckOptions == null) ? 0 : precheckOptions.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - PreCheck other = (PreCheck) obj; - if (precheckOperator == null) { - if (other.precheckOperator != null) - return false; - } else if (!precheckOperator.equals(other.precheckOperator)) - return false; - if (precheckOptions == null) { - if (other.precheckOptions != null) - return false; - } else if (!precheckOptions.equals(other.precheckOptions)) - return false; - return true; - } - - @Override - public String toString() { - return "PreCheck [precheckOperator=" + precheckOperator + ", precheckOptions=" + precheckOptions + "]"; - } - - - - - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/PrecheckOption.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/PrecheckOption.java deleted file mode 100644 index b3f146fdb..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/PrecheckOption.java +++ /dev/null @@ -1,120 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.data; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class PrecheckOption { - - - @JsonProperty("pre-transaction-id") - private int pTransactionID ; - - @JsonProperty("param-name") - private String paramName ; - - - @JsonProperty("param-value") - private String paramValue ; - - @JsonProperty("rule") - private String rule ; - - public int getpTransactionID() { - return pTransactionID; - } - - public void setpTransactionID(int pTransactionID) { - this.pTransactionID = pTransactionID; - } - - public String getParamName() { - return paramName; - } - - public void setParamName(String paramName) { - this.paramName = paramName; - } - - public String getParamValue() { - return paramValue; - } - - public void setParamValue(String paramValue) { - this.paramValue = paramValue; - } - - - - @Override - public String toString() { - return "PrecheckOption [pTransactionID=" + pTransactionID + ", paramName=" + paramName + ", paramValue=" - + paramValue + ", rule=" + rule + "]"; - } - - - public String getRule() { - return rule; - } - - public void setRule(String rule) { - this.rule = rule; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + this.pTransactionID; - result = prime * result + this.paramName.hashCode(); - result = prime * result + this.paramValue.hashCode(); - result = prime * result + this.rule.hashCode(); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - PrecheckOption other = (PrecheckOption) obj; - if (pTransactionID != other.pTransactionID) - return false; - if (paramName == null) { - if (other.paramName != null) - return false; - } else if (!paramName.equals(other.paramName)) - return false; - if (paramValue == null) { - if (other.paramValue != null) - return false; - } else if (!paramValue.equals(other.paramValue)) - return false; - if (rule != other.rule) - return false; - return true; - } - - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/Response.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/Response.java deleted file mode 100644 index f5c6fe871..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/Response.java +++ /dev/null @@ -1,79 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.data; - -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class Response { - - @JsonProperty("response-code") - private String responseCode; - - @JsonProperty("response-message") - private String responseMessage; - - @JsonProperty("response-action") - private ResponseAction responseAction; - - private String responseActionHanlder; - - public String getResponseCode() { - return responseCode; - } - - public void setResponseCode(String responseCode) { - this.responseCode = responseCode; - } - - public String getResponseMessage() { - return responseMessage; - } - - public void setResponseMessage(String responseMessage) { - this.responseMessage = responseMessage; - } - - - public String getResponseActionHanlder() { - return responseActionHanlder; - } - - public void setResponseActionHanlder(String responseActionHanlder) { - this.responseActionHanlder = responseActionHanlder; - } - - public ResponseAction getResponseAction() { - return responseAction; - } - - public void setResponseAction(ResponseAction responseAction) { - this.responseAction = responseAction; - } - - @Override - public String toString() { - return "Response [responseCode=" + responseCode + ", responseMessage=" + responseMessage + ", responseAction=" - + responseAction + ", responseActionHanlder=" + responseActionHanlder + "]"; - } - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/ResponseAction.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/ResponseAction.java deleted file mode 100644 index 3768941df..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/ResponseAction.java +++ /dev/null @@ -1,103 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.data; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class ResponseAction { - - @JsonProperty("wait") - private String wait; - - @JsonProperty("retry") - private String retry; - - @JsonProperty("jump") - private String jump; - - @JsonProperty("ignore") - private boolean ignore; - - @JsonProperty("stop") - private boolean stop; - - @JsonProperty("intermediate-message") - private boolean intermediateMessage; - - public String getWait() { - return wait; - } - - public void setWait(String wait) { - this.wait = wait; - } - - public String getRetry() { - return retry; - } - - public void setRetry(String retry) { - this.retry = retry; - } - - public String getJump() { - return jump; - } - - public void setJump(String jump) { - this.jump = jump; - } - - public boolean isIgnore() { - return ignore; - } - - public void setIgnore(boolean ignore) { - this.ignore = ignore; - } - - public boolean isStop() { - return stop; - } - - public void setStop(boolean stop) { - this.stop = stop; - } - - - - @Override - public String toString() { - return "ResponseAction [wait=" + wait + ", retry=" + retry + ", jump=" + jump + ", ignore=" + ignore + ", stop=" - + stop + ", intermediateMessage=" + intermediateMessage + "]"; - } - - public boolean isIntermediateMessage() { - return intermediateMessage; - } - - public void setIntermediateMessage(boolean intermediateMessage) { - this.intermediateMessage = intermediateMessage; - } - - - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/Transaction.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/Transaction.java deleted file mode 100644 index 082e41b0d..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/Transaction.java +++ /dev/null @@ -1,365 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.data; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class Transaction { - - @JsonProperty("transaction-id") - private int transactionId ; - - @JsonProperty("action") - private String action ; - - @JsonProperty("action-level") - private String actionLevel ; - - @JsonProperty("action-identifier") - private ActionIdentifier actionIdentifier ; - - @JsonProperty("parameters") - private List parameters ; - - private String executionType; - - private String uId; - - private String statusCode; - - private String pswd; - - private String executionEndPoint; - - private String executionModule; - - private String executionRPC; - - @JsonProperty("state") - private String state; - - @JsonProperty("precheck") - private PreCheck precheck; - - @JsonProperty("payload") - private String payload ; - - @JsonProperty("responses") - private List responses ; - - - private String status = "PENDING"; - - public String getuId() { - return uId; - } - - public void setuId(String uId) { - this.uId = uId; - } - - public String getPswd() { - return pswd; - } - - public void setPswd(String pswd) { - this.pswd = pswd; - } - - public String getExecutionEndPoint() { - return executionEndPoint; - } - - public void setExecutionEndPoint(String executionEndPoint) { - this.executionEndPoint = executionEndPoint; - } - - - public String getExecutionType() { - return executionType; - } - - public void setExecutionType(String executionType) { - this.executionType = executionType; - } - - public String getExecutionModule() { - return executionModule; - } - - - public void setExecutionModule(String executionModule) { - this.executionModule = executionModule; - } - - - public String getExecutionRPC() { - return executionRPC; - } - - - public void setExecutionRPC(String executionRPC) { - this.executionRPC = executionRPC; - } - - - public List getParameters() { - return parameters; - } - - - public void setParameters(List parameters) { - this.parameters = parameters; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public PreCheck getPrecheck() { - return precheck; - } - - public void setPrecheck(PreCheck precheck) { - this.precheck = precheck; - } - - public String getStatus() { - return status; - } - - - public void setStatus(String status) { - this.status = status; - } - - public List getResponses() { - return responses; - } - - - public void setResponses(List responses) { - this.responses = responses; - } - - public int getTransactionId() { - return transactionId; - } - - - public void setTransactionId(int transactionId) { - this.transactionId = transactionId; - } - - - public String getAction() { - return action; - } - - - public void setAction(String action) { - this.action = action; - } - - - public String getActionLevel() { - return actionLevel; - } - - - public void setActionLevel(String actionLevel) { - this.actionLevel = actionLevel; - } - - - - public String getPayload() { - return payload; - } - - - public void setPayload(String payload) { - this.payload = payload; - } - - - public ActionIdentifier getActionIdentifier() { - return actionIdentifier; - } - - - public void setActionIdentifier(ActionIdentifier actionIdentifier) { - this.actionIdentifier = actionIdentifier; - } - - public String getStatusCode() { - return statusCode; - } - - public void setStatusCode(String statusCode) { - this.statusCode = statusCode; - } - - @Override - public String toString() { - return "Transaction [transactionId=" + transactionId + ", action=" + action + ", actionLevel=" + actionLevel - + ", actionIdentifier=" + actionIdentifier + ", parameters=" + parameters + ", executionType=" - + executionType + ", uId=" + uId + ", statusCode=" + statusCode + ", pswd=" + pswd - + ", executionEndPoint=" + executionEndPoint + ", executionModule=" + executionModule - + ", executionRPC=" + executionRPC + ", state=" + state + ", precheck=" + precheck + ", payload=" - + payload + ", responses=" + responses + ", status=" + status + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((action == null) ? 0 : action.hashCode()); - result = prime * result + ((actionIdentifier == null) ? 0 : actionIdentifier.hashCode()); - result = prime * result + ((actionLevel == null) ? 0 : actionLevel.hashCode()); - result = prime * result + ((executionEndPoint == null) ? 0 : executionEndPoint.hashCode()); - result = prime * result + ((executionModule == null) ? 0 : executionModule.hashCode()); - result = prime * result + ((executionRPC == null) ? 0 : executionRPC.hashCode()); - result = prime * result + ((executionType == null) ? 0 : executionType.hashCode()); - result = prime * result + ((parameters == null) ? 0 : parameters.hashCode()); - result = prime * result + ((payload == null) ? 0 : payload.hashCode()); - result = prime * result + ((precheck == null) ? 0 : precheck.hashCode()); - result = prime * result + ((pswd == null) ? 0 : pswd.hashCode()); - result = prime * result + ((responses == null) ? 0 : responses.hashCode()); - result = prime * result + ((state == null) ? 0 : state.hashCode()); - result = prime * result + ((status == null) ? 0 : status.hashCode()); - result = prime * result + ((statusCode == null) ? 0 : statusCode.hashCode()); - result = prime * result + transactionId; - result = prime * result + ((uId == null) ? 0 : uId.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Transaction other = (Transaction) obj; - if (action == null) { - if (other.action != null) - return false; - } else if (!action.equals(other.action)) - return false; - if (actionIdentifier == null) { - if (other.actionIdentifier != null) - return false; - } else if (!actionIdentifier.equals(other.actionIdentifier)) - return false; - if (actionLevel == null) { - if (other.actionLevel != null) - return false; - } else if (!actionLevel.equals(other.actionLevel)) - return false; - if (executionEndPoint == null) { - if (other.executionEndPoint != null) - return false; - } else if (!executionEndPoint.equals(other.executionEndPoint)) - return false; - if (executionModule == null) { - if (other.executionModule != null) - return false; - } else if (!executionModule.equals(other.executionModule)) - return false; - if (executionRPC == null) { - if (other.executionRPC != null) - return false; - } else if (!executionRPC.equals(other.executionRPC)) - return false; - if (executionType == null) { - if (other.executionType != null) - return false; - } else if (!executionType.equals(other.executionType)) - return false; - if (parameters == null) { - if (other.parameters != null) - return false; - } else if (!parameters.equals(other.parameters)) - return false; - if (payload == null) { - if (other.payload != null) - return false; - } else if (!payload.equals(other.payload)) - return false; - if (precheck == null) { - if (other.precheck != null) - return false; - } else if (!precheck.equals(other.precheck)) - return false; - if (pswd == null) { - if (other.pswd != null) - return false; - } else if (!pswd.equals(other.pswd)) - return false; - if (responses == null) { - if (other.responses != null) - return false; - } else if (!responses.equals(other.responses)) - return false; - if (state == null) { - if (other.state != null) - return false; - } else if (!state.equals(other.state)) - return false; - if (status == null) { - if (other.status != null) - return false; - } else if (!status.equals(other.status)) - return false; - if (statusCode == null) { - if (other.statusCode != null) - return false; - } else if (!statusCode.equals(other.statusCode)) - return false; - if (transactionId != other.transactionId) - return false; - if (uId == null) { - if (other.uId != null) - return false; - } else if (!uId.equals(other.uId)) - return false; - return true; - } - - -} - - - diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/Transactions.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/Transactions.java deleted file mode 100644 index d8dc8472c..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/data/Transactions.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.data; - -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class Transactions { - - - @JsonProperty("transactions") - private List transactions ; - - public List getTransactions() { - return transactions; - } - - public void setTransactions(List transactions) { - this.transactions = transactions; - } - - @Override - public String toString() { - return "Transactions [transactions=" + transactions + "]"; - } - - -} - - - diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/dbervices/FlowControlDBService.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/dbervices/FlowControlDBService.java deleted file mode 100644 index 618494167..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/dbervices/FlowControlDBService.java +++ /dev/null @@ -1,222 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.dbervices; - -import java.util.HashMap; -import java.util.Map; - -import org.onap.appc.flow.controller.data.Transaction; -import org.onap.appc.flow.controller.utils.EscapeUtils; -import org.onap.appc.flow.controller.utils.FlowControllerConstants; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; -import org.onap.ccsdk.sli.adaptors.resource.sql.SqlResource; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class FlowControlDBService { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(FlowControlDBService.class); - private SvcLogicResource serviceLogic; - private static FlowControlDBService dgGeneralDBService = null; - public static FlowControlDBService initialise() { - if (dgGeneralDBService == null) { - dgGeneralDBService = new FlowControlDBService(); - } - return dgGeneralDBService; - } - private FlowControlDBService() { - if (serviceLogic == null) { - serviceLogic = new SqlResource(); - } - } - - public void getFlowReferenceData(SvcLogicContext ctx, Map inParams, SvcLogicContext localContext) throws SvcLogicException { - - String fn = "DBService.getflowModelInfo"; - // log.debug("Testing " + ctx.getAttribute(FlowExecutorConstants.VNF_TYPE) + " and " + ctx.getAttribute(FlowExecutorConstants.ACTION_LEVEL)); - String whereClause = " where ACTION = $" +FlowControllerConstants.REQUEST_ACTION ; - - if(ctx.getAttribute(FlowControllerConstants.VNF_TYPE) !=null) - whereClause = whereClause.concat(" and VNF_TYPE = $" + FlowControllerConstants.VNF_TYPE); - - if(ctx.getAttribute(FlowControllerConstants.ACTION_LEVEL) !=null) - whereClause = whereClause.concat(" and ACTION_LEVEL = $" + FlowControllerConstants.ACTION_LEVEL); - - QueryStatus status = null; - if (serviceLogic != null && localContext != null) { - String key = "select SEQUENCE_TYPE, CATEGORY, GENERATION_NODE, EXECUTION_NODE from " + FlowControllerConstants.DB_MULTISTEP_FLOW_REFERENCE + - whereClause ; - log.debug(fn + "Query String : " + key); - status = serviceLogic.query("SQL", false, null, key, null, null, localContext); - if(status.toString().equals("FAILURE")) - throw new SvcLogicException("Error - while getting FlowReferenceData "); - } - } - public String getEndPointByAction(String action) { - // TODO Auto-generated method stub - return null; - } - public String getDesignTimeFlowModel(SvcLogicContext localContext) throws SvcLogicException { - String fn = "DBService.getDesignTimeFlowModel "; - QueryStatus status = null; - if (serviceLogic != null && localContext != null) { - String queryString = "select max(internal_version) as maxInternalVersion, artifact_name as artifactName from " + FlowControllerConstants.DB_SDC_ARTIFACTS - + " where artifact_name in (select artifact_name from " + FlowControllerConstants.DB_SDC_REFERENCE + - " where vnf_type= $" + FlowControllerConstants.VNF_TYPE + - " and vnfc_type = $" + FlowControllerConstants.VNFC_TYPE + - " and action = $" + FlowControllerConstants.REQUEST_ACTION + - " and file_category = $" + FlowControllerConstants.CATEGORY + " )" ; - - - log.debug(fn + "Query String : " + queryString); - status = serviceLogic.query("SQL", false, null, queryString, null, null, localContext); - - if(status.toString().equals("FAILURE")) - throw new SvcLogicException("Error - while getting FlowReferenceData "); - - String queryString1 = "select artifact_content from " + FlowControllerConstants.DB_SDC_ARTIFACTS + - " where artifact_name = $artifactName and internal_version = $maxInternalVersion "; - - log.debug(fn + "Query String : " + queryString1); - status = serviceLogic.query("SQL", false, null, queryString1, null, null, localContext); - if(status.toString().equals("FAILURE")) - throw new SvcLogicException("Error - while getting FlowReferenceData "); - } - return localContext != null ? localContext.getAttribute("artifact-content") : null; - } - public QueryStatus loadSequenceIntoDB(SvcLogicContext localContext) throws SvcLogicException { - - QueryStatus status = null; - - if (localContext != null) { - String fn = "DBService.saveArtifacts"; - - localContext.setAttribute(FlowControllerConstants.ARTIFACT_CONTENT_ESCAPED, - EscapeUtils.escapeSql(localContext.getAttribute(FlowControllerConstants.ARTIFACT_CONTENT))); - log.debug("ESCAPED sequence for DB : " + localContext.getAttribute(FlowControllerConstants.ARTIFACT_CONTENT_ESCAPED)); - - for (Object key : localContext.getAttributeKeySet()) { - String parmName = (String) key; - String parmValue = localContext.getAttribute(parmName); - log.debug(" loadSequenceIntoDB " + parmName + "=" + parmValue); - - } - - String queryString = "INSERT INTO " + FlowControllerConstants.DB_REQUEST_ARTIFACTS + - " set request_id = $" + FlowControllerConstants.REQUEST_ID + - " , action = $" + FlowControllerConstants.REQUEST_ACTION + - " , action_level = $" + FlowControllerConstants.ACTION_LEVEL + - " , vnf_type = $" + FlowControllerConstants.VNF_TYPE + - " , category = $" + FlowControllerConstants.CATEGORY + - " , artifact_content = $" + FlowControllerConstants.ARTIFACT_CONTENT_ESCAPED + - " , updated_date = sysdate() "; - - log.debug(fn + "Query String : " + queryString); - status = serviceLogic.save("SQL", false, false, queryString, null, null, localContext); - if(status.toString().equals("FAILURE")) - throw new SvcLogicException("Error While processing storing Artifact: " +localContext.getAttribute(FlowControllerConstants.ARTIFACT_NAME)); - } - return status; - - } - public void populateModuleAndRPC(Transaction transaction, String vnf_type) throws SvcLogicException { - String fn = "FlowControlDBService.populateModuleAndRPC "; - QueryStatus status = null; - SvcLogicContext context = new SvcLogicContext(); - - String key = "select execution_type, execution_module, execution_rpc from " + FlowControllerConstants.DB_PROCESS_FLOW_REFERENCE + - " where action = '" + transaction.getAction() + "'" + - " and action_level = '" + transaction.getActionLevel() + "'" + - " and protocol in ( select protocol from " + FlowControllerConstants.DB_PROTOCOL_REFERENCE + - " where action = '" + transaction.getAction() + "'" ; - if(vnf_type !=null && !vnf_type.isEmpty()) - key = key + " and vnf_type ='" + vnf_type + "' )" ; - else - key = key + " ) " ; - log.debug(fn + "Query String : " + key); - status = serviceLogic.query("SQL", false, null, key, null, null, context); - if(status.toString().equals("FAILURE")) - throw new SvcLogicException("Error - while getting FlowReferenceData "); - - transaction.setExecutionModule(context.getAttribute(FlowControllerConstants.EXECUTTION_MODULE)); - transaction.setExecutionRPC(context.getAttribute(FlowControllerConstants.EXECUTION_RPC)); - transaction.setExecutionType(context.getAttribute(FlowControllerConstants.EXECUTION_TYPE)); - - } - - public String getDependencyInfo(SvcLogicContext localContext) throws SvcLogicException { - String fn = "DBService.getDependencyInfo "; - QueryStatus status = null; - if (serviceLogic != null && localContext != null) { - String queryString = "select max(internal_version) as maxInternalVersion, artifact_name as artifactName from " + FlowControllerConstants.DB_SDC_ARTIFACTS - + " where artifact_name in (select artifact_name from " + FlowControllerConstants.DB_SDC_REFERENCE + - " where vnf_type= $" + FlowControllerConstants.VNF_TYPE + - " and file_category = '" + FlowControllerConstants.DEPENDENCYMODEL +"' )" ; - - log.debug(fn + "Query String : " + queryString); - status = serviceLogic.query("SQL", false, null, queryString, null, null, localContext); - - if(status.toString().equals("FAILURE")) - throw new SvcLogicException("Error - while getting dependencydata "); - - String queryString1 = "select artifact_content from " + FlowControllerConstants.DB_SDC_ARTIFACTS + - " where artifact_name = $artifactName and internal_version = $maxInternalVersion "; - - log.debug(fn + "Query String : " + queryString1); - status = serviceLogic.query("SQL", false, null, queryString1, null, null, localContext); - if(status.toString().equals("FAILURE")) - throw new SvcLogicException("Error - while getting dependencyData "); - } - - return localContext != null ? localContext.getAttribute("artifact-content") : null; - - } - - public String getCapabilitiesData(SvcLogicContext localContext) throws SvcLogicException { - String fn = "DBService.getCapabilitiesData "; - QueryStatus status = null; - if (serviceLogic != null && localContext != null) { - String queryString = "select max(internal_version) as maxInternalVersion, artifact_name as artifactName from " + FlowControllerConstants.DB_SDC_ARTIFACTS - + " where artifact_name in (select artifact_name from " + FlowControllerConstants.DB_SDC_REFERENCE + - " where vnf_type= $" + FlowControllerConstants.VNF_TYPE + - " and file_category = '" + FlowControllerConstants.CAPABILITY +"' )" ; - - log.info(fn + "Query String : " + queryString); - status = serviceLogic.query("SQL", false, null, queryString, null, null, localContext); - - if(status.toString().equals("FAILURE")) - throw new SvcLogicException("Error - while getting capabilitiesData "); - - String queryString1 = "select artifact_content from " + FlowControllerConstants.DB_SDC_ARTIFACTS + - " where artifact_name = $artifactName and internal_version = $maxInternalVersion "; - - log.debug(fn + "Query String : " + queryString1); - status = serviceLogic.query("SQL", false, null, queryString1, null, null, localContext); - if(status.toString().equals("FAILURE")) - throw new SvcLogicException("Error - while getting capabilitiesData "); - } - return localContext != null ? localContext.getAttribute("artifact-content") : null; - } -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/executorImpl/GraphExecutor.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/executorImpl/GraphExecutor.java deleted file mode 100644 index 5548b1c3e..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/executorImpl/GraphExecutor.java +++ /dev/null @@ -1,163 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.executorImpl; - -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Properties; - -import org.onap.appc.flow.controller.data.Parameters; -import org.onap.appc.flow.controller.data.Transaction; -import org.onap.appc.flow.controller.interfaces.FlowExecutorInterface; -import org.onap.appc.flow.controller.utils.FlowControllerConstants; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; -import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -public class GraphExecutor implements FlowExecutorInterface { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(GraphExecutor.class); - - private SvcLogicService svcLogic = null; - - public GraphExecutor() { - BundleContext bctx = FrameworkUtil.getBundle(SvcLogicService.class) - .getBundleContext(); - - ServiceReference sref = bctx.getServiceReference(SvcLogicService.NAME); - if (sref != null) { - svcLogic = (SvcLogicService) bctx.getService(sref); - - - } else { - log.warn("Cannot find service reference for " - + SvcLogicService.NAME); - } - log.debug("Graph Executor Initialized successfully"); - } - - public boolean hasGraph(String module, String rpc, String version, - String mode) throws SvcLogicException { - return (svcLogic.hasGraph(module, rpc, version, mode)); - } - - public Properties executeGraph(String module, String rpc, String version, - String mode, Properties parms) throws SvcLogicException { - log.debug("Parameters passed to SLI"); - -// for (Object key : parms.keySet()) { -// String parmName = (String) key; -// String parmValue = parms.getProperty(parmName); -// -// log.debug(parmName + " = " + parmValue); -// } - - Properties respProps = svcLogic.execute(module, rpc, version, mode,parms); - if (log.isDebugEnabled()) { - log.debug("Parameters returned by SLI"); - for (Object key : respProps.keySet()) { - String parmName = (String) key; - String parmValue = respProps.getProperty(parmName); - - log.debug(parmName + " = " + parmValue); - } - } - if ("failure" - .equalsIgnoreCase(respProps.getProperty("SvcLogic.status"))) { - return (respProps); - } - return (respProps); -} - -@Override -public HashMap execute(Transaction transaction, SvcLogicContext ctx) throws Exception { - - String fn = "GraphExecutor.execute "; - log.debug(fn + "About to execute graph : " + transaction.getExecutionRPC()) ; - - Properties parms = new Properties(); - for (Object key : ctx.getAttributeKeySet()) { - String parmName = (String) key; - String parmValue = ctx.getAttribute(parmName); - parms.put(parmName, parmValue); - log.info(fn + "Setting Key= " + parmName + "and Value = " + parmValue); - - } - Properties returnParams = executeGraph(transaction.getExecutionModule(),transaction.getExecutionRPC(), null, "sync", parms); - - //log.debug("Return Params executing DG :" + returnParams.toString()); - - log.debug("Returned Params from DG Module: " + transaction.getExecutionModule() + "and DG NAME: " + transaction.getExecutionRPC() - + returnParams.toString()); - - Enumeration e = returnParams.propertyNames(); - - while (e.hasMoreElements()) { - String key = (String) e.nextElement(); - log.info("NEW KEY = " + key + " -- " + returnParams.getProperty(key)); - - ctx.setAttribute(key, returnParams.getProperty(key)); - } - - - //Get the correct code from the SVC Logic and set it in transaction -// transaction.setStatusCode(returnParams.getProperty("SvcLogic.code")); - - if (FlowControllerConstants.FAILURE - .equalsIgnoreCase(returnParams.getProperty("SvcLogic.status"))) { - transaction.setStatus(FlowControllerConstants.FAILURE); - ctx.setAttribute(ctx.getAttribute(FlowControllerConstants.RESPONSE_PREFIX) + FlowControllerConstants.OUTPUT_PARAM_STATUS, FlowControllerConstants.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(ctx.getAttribute(FlowControllerConstants.RESPONSE_PREFIX) + FlowControllerConstants.OUTPUT_STATUS_MESSAGE, returnParams.getProperty("error-message")); - transaction.setStatusCode("401"); - transaction.setState((ctx.getAttribute(transaction.getExecutionModule() + "." + transaction.getExecutionRPC() + "." + FlowControllerConstants.OUTPUT_STATUS_MESSAGE)) !=null ? - ctx.getAttribute(transaction.getExecutionModule() + "." + transaction.getExecutionRPC() + "." + FlowControllerConstants.OUTPUT_STATUS_MESSAGE): null); - //Get error code from above instead setting here ...its for testing purpose - - - } - else if(FlowControllerConstants.SUCCESS - .equalsIgnoreCase(returnParams.getProperty("SvcLogic.status"))) { - transaction.setStatus(FlowControllerConstants.SUCCESS); - transaction.setStatusCode("400"); - ctx.setAttribute(ctx.getAttribute(FlowControllerConstants.RESPONSE_PREFIX) + FlowControllerConstants.OUTPUT_PARAM_STATUS, FlowControllerConstants.OUTPUT_STATUS_SUCCESS); - transaction.setState((ctx.getAttribute(transaction.getExecutionModule() + "." + transaction.getExecutionRPC() + "." + FlowControllerConstants.OUTPUT_STATUS_MESSAGE)) !=null ? - ctx.getAttribute(transaction.getExecutionModule() + "." + transaction.getExecutionRPC() + "." + FlowControllerConstants.OUTPUT_STATUS_MESSAGE): null); - //Get error code from above instead setting here ...its for testing purpose - } - else { - transaction.setStatus(FlowControllerConstants.OTHERS); - ctx.setAttribute(ctx.getAttribute(FlowControllerConstants.RESPONSE_PREFIX) + FlowControllerConstants.OUTPUT_PARAM_STATUS, FlowControllerConstants.OUTPUT_STATUS_FAILURE); - transaction.setStatusCode("401"); - ctx.setAttribute(ctx.getAttribute(FlowControllerConstants.RESPONSE_PREFIX) + FlowControllerConstants.OUTPUT_STATUS_MESSAGE, returnParams.getProperty("error-message")); - } - - return null; - //Change null to required value if required in upper level -} -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/executorImpl/NodeExecutor.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/executorImpl/NodeExecutor.java deleted file mode 100644 index 50de43beb..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/executorImpl/NodeExecutor.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.executorImpl; - -import java.util.HashMap; -import java.util.Properties; - -import org.onap.appc.flow.controller.data.Transaction; -import org.onap.appc.flow.controller.interfaces.FlowExecutorInterface; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -public class NodeExecutor implements FlowExecutorInterface { - - private static final EELFLogger LOG = EELFManager.getInstance().getLogger(NodeExecutor.class); - - @Override - public HashMap execute(Transaction transaction, SvcLogicContext ctx) { - return null; - } -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/executorImpl/RestExecutor.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/executorImpl/RestExecutor.java deleted file mode 100644 index 366e80273..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/executorImpl/RestExecutor.java +++ /dev/null @@ -1,156 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.executorImpl; - -import java.io.FileInputStream; -import java.io.InputStream; -import java.net.URI; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Properties; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; -import javax.ws.rs.HttpMethod; -import javax.ws.rs.core.MediaType; - -import org.apache.commons.io.IOUtils; -import org.onap.appc.flow.controller.data.Response; -import org.onap.appc.flow.controller.data.Transaction; -import org.onap.appc.flow.controller.interfaces.FlowExecutorInterface; -import org.onap.appc.flow.controller.utils.FlowControllerConstants; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -public class RestExecutor implements FlowExecutorInterface { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(RestExecutor.class); - private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; - Properties props = new Properties(); - public RestExecutor() throws Exception { - String propDir = System.getenv(SDNC_CONFIG_DIR_VAR); - if (propDir == null) - throw new Exception(" Cannot find Property file -" + SDNC_CONFIG_DIR_VAR); - String propFile = propDir + FlowControllerConstants.APPC_FLOW_CONTROLLER; - InputStream propStream = new FileInputStream(propFile); - try{ - props.load(propStream); - } - catch (Exception e){ - throw new Exception("Could not load properties file " + propFile, e); - } - finally{ - try{ - propStream.close(); - } - catch (Exception e){ - log.warn("Could not close FileInputStream", e); - } - } - } - @Override - public HashMap execute(Transaction transaction, SvcLogicContext ctx) throws Exception{ - log.info("Configuring Rest Operation....." + transaction.toString()); - Response response = new Response(); - HashMap outputMessage = new HashMap(); - Client client = null; - WebResource webResource = null; - ClientResponse clientResponse = null; - String responseDataType=MediaType.APPLICATION_JSON; - String requestDataType=MediaType.APPLICATION_JSON; - - - try{ - DefaultClientConfig defaultClientConfig = new DefaultClientConfig(); - System.setProperty("jsse.enableSNIExtension", "false"); - SSLContext sslContext = null; - SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager(); - sslContext = SSLContext.getInstance("SSL"); - sslContext.init(null, new javax.net.ssl.TrustManager[] { secureRestClientTrustManager }, null); - defaultClientConfig.getProperties().put( - com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, - new com.sun.jersey.client.urlconnection.HTTPSProperties(getHostnameVerifier(), sslContext)); - client = Client.create(defaultClientConfig); - client.addFilter(new HTTPBasicAuthFilter(transaction.getuId(), transaction.getPswd())); - webResource = client.resource(new URI(transaction.getExecutionEndPoint())); - webResource.setProperty("Content-Type", "application/json;charset=UTF-8"); - - log.info("Starting Rest Operation....."); - if(HttpMethod.GET.equalsIgnoreCase(transaction.getExecutionRPC())){ - clientResponse = webResource.accept(responseDataType).get(ClientResponse.class); - }else if(HttpMethod.POST.equalsIgnoreCase(transaction.getExecutionRPC())){ - clientResponse = webResource.type(requestDataType).post(ClientResponse.class, transaction.getPayload()); - }else if(HttpMethod.PUT.equalsIgnoreCase(transaction.getExecutionRPC())){ - clientResponse = webResource.type(requestDataType).put(ClientResponse.class,transaction.getPayload()); - }else if(HttpMethod.DELETE.equalsIgnoreCase(transaction.getExecutionRPC())){ - clientResponse = webResource.delete(ClientResponse.class); - } - - if(clientResponse.getStatus() == 200){ - response.setResponseCode(String.valueOf(clientResponse.getStatus())); - ArrayList responses = new ArrayList(); - responses.add(response); - transaction.setResponses(responses); - outputMessage.put("restResponse", clientResponse.getEntity(String.class)); - } - else{ - throw new Exception("Can not determine the state of : " + transaction.getActionLevel() + " HTTP error code : " - + clientResponse.getStatus()); - - } - - log.info("Completed Rest Operation....."); - - }catch (Exception e) { - e.printStackTrace(); - log.debug("failed in RESTCONT Action ("+transaction.getExecutionRPC()+") for the resource " + transaction.getExecutionEndPoint() + ", falut message :"+e.getMessage()); - throw new Exception("Error While Sending Rest Request" + e.getMessage()); - } - finally { - // clean up. - webResource = null; - if(client != null){ - client.destroy(); - client = null; - } - } - - return outputMessage; - } - -private HostnameVerifier getHostnameVerifier() { - return new HostnameVerifier() { - @Override - public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) { - return true; - } - }; -} - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/executorImpl/SecureRestClientTrustManager.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/executorImpl/SecureRestClientTrustManager.java deleted file mode 100644 index cbe5de28b..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/executorImpl/SecureRestClientTrustManager.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.executorImpl; - -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.X509TrustManager; - - -public class SecureRestClientTrustManager implements X509TrustManager { - - @Override - public void checkClientTrusted(X509Certificate[] arg0, String arg1) - throws CertificateException { - } - - @Override - public void checkServerTrusted(X509Certificate[] arg0, String arg1) - throws CertificateException { - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } - - public boolean isClientTrusted(X509Certificate[] arg0) { - return true; - } - - public boolean isServerTrusted(X509Certificate[] arg0) { - return true; - } - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/ActionIdentifier.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/ActionIdentifier.java deleted file mode 100644 index 2784dcc15..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/ActionIdentifier.java +++ /dev/null @@ -1,158 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2017.07.31 at 10:30:39 AM EDT -// - - -package org.onap.appc.flow.controller.interfaceData; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -import com.fasterxml.jackson.annotation.JsonProperty; - - -/** - *

Java class for anonymous complex type. - * - *

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

- * <complexType>
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="vnf-id" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="vserver-id" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="vnfc-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "vnfId", - "vserverId", - "vnfcName" -}) -@XmlRootElement(name = "action-identifier") -public class ActionIdentifier { - - @XmlElement(name = "vnf-id", required = true) - @JsonProperty("vnf-id") - protected String vnfId; - @XmlElement(name = "vserver-id", required = true) - @JsonProperty("vserver-id") - protected String vserverId; - @XmlElement(name = "vnfc-name", required = true) - @JsonProperty("vnfc-name") - protected String vnfcName; - - /** - * Gets the value of the vnfId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getVnfId() { - return vnfId; - } - - /** - * Sets the value of the vnfId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVnfId(String value) { - this.vnfId = value; - } - - /** - * Gets the value of the vserverId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getVserverId() { - return vserverId; - } - - /** - * Sets the value of the vserverId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVserverId(String value) { - this.vserverId = value; - } - - /** - * Gets the value of the vnfcName property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getVnfcName() { - return vnfcName; - } - - /** - * Sets the value of the vnfcName property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVnfcName(String value) { - this.vnfcName = value; - } - - @Override - public String toString() { - return "ActionIdentifier [vnfId=" + vnfId + ", vserverId=" + vserverId - + ", vnfcName=" + vnfcName + "]"; - } - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Capabilities.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Capabilities.java deleted file mode 100644 index 91414d3b2..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Capabilities.java +++ /dev/null @@ -1,190 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2017.07.31 at 10:30:39 AM EDT -// - - -package org.onap.appc.flow.controller.interfaceData; - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlList; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -import com.fasterxml.jackson.annotation.JsonProperty; - - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "vnf", - "vfModule", - "vm", - "vnfc" -}) -@XmlRootElement(name = "capabilities") -public class Capabilities { - - @XmlList - @XmlElement(required = true) - protected List vnf; - @XmlList - @XmlElement(name = "vf-module", required = true) - @JsonProperty("vf-module") - protected List vfModule; - @XmlList - @XmlElement(required = true) - protected List vm; - @XmlList - @XmlElement(required = true) - protected List vnfc; - - /** - * Gets the value of the vnf property. - * - *

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

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

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

- * Objects of the following type(s) are allowed in the list - * {@link String } - * - * - */ - public List getVnf() { - if (vnf == null) { - vnf = new ArrayList(); - } - return this.vnf; - } - - /** - * Gets the value of the vfModule property. - * - *

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

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

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

- * Objects of the following type(s) are allowed in the list - * {@link String } - * - * - */ - public List getVfModule() { - if (vfModule == null) { - vfModule = new ArrayList(); - } - return this.vfModule; - } - - /** - * Gets the value of the vm property. - * - *

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

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

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

- * Objects of the following type(s) are allowed in the list - * {@link String } - * - * - */ - public List getVm() { - if (vm == null) { - vm = new ArrayList(); - } - return this.vm; - } - - /** - * Gets the value of the vnfc property. - * - *

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

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

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

- * Objects of the following type(s) are allowed in the list - * {@link String } - * - * - */ - public List getVnfc() { - if (vnfc == null) { - vnfc = new ArrayList(); - } - return this.vnfc; - } - - @Override - public String toString() { - return "Capabilities [vnf=" + vnf + ", vfModule=" + vfModule + ", vm=" - + vm + ", vnfc=" + vnfc + "]"; - } - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/DependencyInfo.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/DependencyInfo.java deleted file mode 100644 index 1dfe961b7..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/DependencyInfo.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2017.07.31 at 10:30:39 AM EDT -// - - -package org.onap.appc.flow.controller.interfaceData; - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "vnfcs" -}) -@XmlRootElement(name = "dependency-info") -@JsonIgnoreProperties(ignoreUnknown = true) -public class DependencyInfo { - - protected List vnfcs; - - /** - * Gets the value of the vnfcs property. - * - *

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

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

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

- * Objects of the following type(s) are allowed in the list - * {@link Vnfcs } - * - * - */ - public List getVnfcs() { - if (vnfcs == null) { - vnfcs = new ArrayList(); - } - return this.vnfcs; - } - - @Override - public String toString() { - return "DependencyInfo [vnfcs=" + vnfcs + "]"; - } - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Input.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Input.java deleted file mode 100644 index ed95268d1..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Input.java +++ /dev/null @@ -1,199 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2017.07.31 at 10:30:39 AM EDT -// - - -package org.onap.appc.flow.controller.interfaceData; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import com.fasterxml.jackson.annotation.JsonRootName; - - -@XmlAccessorType(XmlAccessType.FIELD) -@JsonRootName(value="input") -@XmlType(name = "input", propOrder = { - "requestInfo", - "inventoryInfo", - "dependencyInfo", - "tunableParameters", - "capabilities" -}) -@JsonPropertyOrder({"requestInfo", - "inventoryInfo", - "dependencyInfo", - "tunableParameters", - "capabilities" }) -public class Input { - - @XmlElement(name = "request-info") - @JsonProperty("request-info") - protected RequestInfo requestInfo; - @XmlElement(name = "inventory-info") - @JsonProperty("inventory-info") - protected InventoryInfo inventoryInfo; - @XmlElement(name = "dependency-info") - @JsonProperty("dependency-info") - protected DependencyInfo dependencyInfo; - @XmlElement(name = "tunable-parameters") - @JsonProperty("tunable-parameters") - protected TunableParameters tunableParameters; - protected Capabilities capabilities; - - /** - * Gets the value of the requestInfo property. - * - * @return - * possible object is - * {@link RequestInfo } - * - */ - public RequestInfo getRequestInfo() { - return requestInfo; - } - - /** - * Sets the value of the requestInfo property. - * - * @param value - * allowed object is - * {@link RequestInfo } - * - */ - public void setRequestInfo(RequestInfo value) { - this.requestInfo = value; - } - - /** - * Gets the value of the inventoryInfo property. - * - * @return - * possible object is - * {@link InventoryInfo } - * - */ - public InventoryInfo getInventoryInfo() { - return inventoryInfo; - } - - /** - * Sets the value of the inventoryInfo property. - * - * @param value - * allowed object is - * {@link InventoryInfo } - * - */ - public void setInventoryInfo(InventoryInfo value) { - this.inventoryInfo = value; - } - - /** - * Gets the value of the dependencyInfo property. - * - * @return - * possible object is - * {@link DependencyInfo } - * - */ - public DependencyInfo getDependencyInfo() { - return dependencyInfo; - } - - /** - * Sets the value of the dependencyInfo property. - * - * @param value - * allowed object is - * {@link DependencyInfo } - * - */ - public void setDependencyInfo(DependencyInfo value) { - this.dependencyInfo = value; - } - - /** - * Gets the value of the tunableParameters property. - * - * @return - * possible object is - * {@link TunableParameters } - * - */ - public TunableParameters getTunableParameters() { - return tunableParameters; - } - - /** - * Sets the value of the tunableParameters property. - * - * @param value - * allowed object is - * {@link TunableParameters } - * - */ - public void setTunableParameters(TunableParameters value) { - this.tunableParameters = value; - } - - /** - * Gets the value of the capabilities property. - * - * @return - * possible object is - * {@link Capabilities } - * - */ - public Capabilities getCapabilities() { - return capabilities; - } - - /** - * Sets the value of the capabilities property. - * - * @param value - * allowed object is - * {@link Capabilities } - * - */ - public void setCapabilities(Capabilities value) { - this.capabilities = value; - } - - @Override - public String toString() { - return "Input [requestInfo=" + requestInfo + ", inventoryInfo=" - + inventoryInfo + ", dependencyInfo=" + dependencyInfo - + ", tunableParameters=" + tunableParameters - + ", capabilities=" + capabilities + "]"; - } - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/InventoryInfo.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/InventoryInfo.java deleted file mode 100644 index 24da512b1..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/InventoryInfo.java +++ /dev/null @@ -1,80 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2017.07.31 at 10:30:39 AM EDT -// - - -package org.onap.appc.flow.controller.interfaceData; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -import com.fasterxml.jackson.annotation.JsonProperty; - - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "vnfInfo" -}) -@XmlRootElement(name = "inventory-info") -public class InventoryInfo { - - @XmlElement(name = "vnf-info", required = true) - @JsonProperty("vnf-info") - protected VnfInfo vnfInfo; - - /** - * Gets the value of the vnfInfo property. - * - * @return - * possible object is - * {@link VnfInfo } - * - */ - public VnfInfo getVnfInfo() { - return vnfInfo; - } - - /** - * Sets the value of the vnfInfo property. - * - * @param value - * allowed object is - * {@link VnfInfo } - * - */ - public void setVnfInfo(VnfInfo value) { - this.vnfInfo = value; - } - - @Override - public String toString() { - return "InventoryInfo [vnfInfo=" + vnfInfo + "]"; - } - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/ObjectFactory.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/ObjectFactory.java deleted file mode 100644 index a52634b97..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/ObjectFactory.java +++ /dev/null @@ -1,147 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2017.07.31 at 10:30:39 AM EDT -// - - -package org.onap.appc.flow.controller.interfaceData; - -import javax.xml.bind.annotation.XmlRegistry; - - -/** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the org.onap.appc.flow.controller.interfaceData package. - *

An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. - * - */ -@XmlRegistry -public class ObjectFactory { - - - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.appc.flow.controller.interfaceData - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link Capabilities } - * - */ - public Capabilities createCapabilities() { - return new Capabilities(); - } - - /** - * Create an instance of {@link RequestInfo } - * - */ - public RequestInfo createRequestInfo() { - return new RequestInfo(); - } - - /** - * Create an instance of {@link ActionIdentifier } - * - */ - public ActionIdentifier createActionIdentifier() { - return new ActionIdentifier(); - } - - /** - * Create an instance of {@link DependencyInfo } - * - */ - public DependencyInfo createDependencyInfo() { - return new DependencyInfo(); - } - - /** - * Create an instance of {@link Vnfcs } - * - */ - public Vnfcs createVnfcs() { - return new Vnfcs(); - } - - /** - * Create an instance of {@link Vm } - * - */ - public Vm createVm() { - return new Vm(); - } - - /** - * Create an instance of {@link Vnfcslist } - * - */ - public Vnfcslist createVnfcslist() { - return new Vnfcslist(); - } - - /** - * Create an instance of {@link TunableParameters } - * - */ - public TunableParameters createTunableParameters() { - return new TunableParameters(); - } - - /** - * Create an instance of {@link VnfInfo } - * - */ - public VnfInfo createVnfInfo() { - return new VnfInfo(); - } - - /** - * Create an instance of {@link InventoryInfo } - * - */ - public InventoryInfo createInventoryInfo() { - return new InventoryInfo(); - } - - /** - * Create an instance of {@link Input } - * - */ - public Input createInput() { - return new Input(); - } - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/RequestInfo.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/RequestInfo.java deleted file mode 100644 index 2cca748e6..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/RequestInfo.java +++ /dev/null @@ -1,164 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2017.07.31 at 10:30:39 AM EDT -// - - -package org.onap.appc.flow.controller.interfaceData; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -import com.fasterxml.jackson.annotation.JsonProperty; - - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "action", - "actionLevel", - "actionIdentifier", - "payload" -}) -@XmlRootElement(name = "request-info") -public class RequestInfo { - - @XmlElement(required = true) - protected String action; - @XmlElement(name = "action-level", required = true) - @JsonProperty("action-level") - protected String actionLevel; - @XmlElement(name = "action-identifier", required = true) - @JsonProperty("action-identifier") - protected ActionIdentifier actionIdentifier; - @XmlElement(required = true) - protected String payload; - - /** - * Gets the value of the action property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getAction() { - return action; - } - - /** - * Sets the value of the action property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setAction(String value) { - this.action = value; - } - - /** - * Gets the value of the actionLevel property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getActionLevel() { - return actionLevel; - } - - /** - * Sets the value of the actionLevel property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setActionLevel(String value) { - this.actionLevel = value; - } - - /** - * Gets the value of the actionIdentifier property. - * - * @return - * possible object is - * {@link ActionIdentifier } - * - */ - public ActionIdentifier getActionIdentifier() { - return actionIdentifier; - } - - /** - * Sets the value of the actionIdentifier property. - * - * @param value - * allowed object is - * {@link ActionIdentifier } - * - */ - public void setActionIdentifier(ActionIdentifier value) { - this.actionIdentifier = value; - } - - /** - * Gets the value of the payload property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getPayload() { - return payload; - } - - /** - * Sets the value of the payload property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setPayload(String value) { - this.payload = value; - } - - @Override - public String toString() { - return "RequestInfo [action=" + action + ", actionLevel=" + actionLevel - + ", actionIdentifier=" + actionIdentifier + ", payload=" - + payload + "]"; - } - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/TunableParameters.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/TunableParameters.java deleted file mode 100644 index ceb3e2ade..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/TunableParameters.java +++ /dev/null @@ -1,153 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2017.07.31 at 10:30:39 AM EDT -// - - -package org.onap.appc.flow.controller.interfaceData; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for anonymous complex type. - * - *

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

- * <complexType>
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="strategy" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="wait-time" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="retry-count" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "strategy", - "waitTime", - "retryCount" -}) -@XmlRootElement(name = "tunable-parameters") -public class TunableParameters { - - @XmlElement(required = true) - protected String strategy; - @XmlElement(name = "wait-time", required = true) - protected String waitTime; - @XmlElement(name = "retry-count", required = true) - protected String retryCount; - - /** - * Gets the value of the strategy property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getStrategy() { - return strategy; - } - - /** - * Sets the value of the strategy property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setStrategy(String value) { - this.strategy = value; - } - - /** - * Gets the value of the waitTime property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getWaitTime() { - return waitTime; - } - - /** - * Sets the value of the waitTime property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setWaitTime(String value) { - this.waitTime = value; - } - - /** - * Gets the value of the retryCount property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getRetryCount() { - return retryCount; - } - - /** - * Sets the value of the retryCount property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setRetryCount(String value) { - this.retryCount = value; - } - - @Override - public String toString() { - return "TunableParameters [strategy=" + strategy + ", waitTime=" - + waitTime + ", retryCount=" + retryCount + "]"; - } - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Vm.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Vm.java deleted file mode 100644 index 49a98ea0d..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Vm.java +++ /dev/null @@ -1,108 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2017.07.31 at 10:30:39 AM EDT -// - - -package org.onap.appc.flow.controller.interfaceData; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -import com.fasterxml.jackson.annotation.JsonProperty; - - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "vserverId", - "vnfc" -}) -@XmlRootElement(name = "vm") -public class Vm { - - @XmlElement(name = "vserver-id", required = true) - @JsonProperty("vserver-id") - protected String vserverId; - @XmlElement(required = true) - @JsonProperty("vnfc") - protected Vnfcslist vnfc; - - /** - * Gets the value of the vserverId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getVserverId() { - return vserverId; - } - - /** - * Sets the value of the vserverId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVserverId(String value) { - this.vserverId = value; - } - - /** - * Gets the value of the vnfc property. - * - * @return - * possible object is - * {@link Vnfcslist } - * - */ - public Vnfcslist getVnfc() { - return vnfc; - } - - /** - * Sets the value of the vnfc property. - * - * @param value - * allowed object is - * {@link Vnfcslist } - * - */ - public void setVnfc(Vnfcslist value) { - this.vnfc = value; - } - - @Override - public String toString() { - return "Vm [vserverId=" + vserverId + ", vnfc=" + vnfc + "]"; - } - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/VnfInfo.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/VnfInfo.java deleted file mode 100644 index d4a6d65b7..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/VnfInfo.java +++ /dev/null @@ -1,172 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2017.07.31 at 10:30:39 AM EDT -// - - -package org.onap.appc.flow.controller.interfaceData; - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -import com.fasterxml.jackson.annotation.JsonProperty; - - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "vnfId", - "vnfName", - "vnfType", - "vm" -}) -@XmlRootElement(name = "vnf-info") -public class VnfInfo { - - @XmlElement(name = "vnf-id", required = true) - @JsonProperty("vnf-id") - protected String vnfId; - @XmlElement(name = "vnf-name", required = true) - @JsonProperty("vnf-name") - protected String vnfName; - @XmlElement(name = "vnf-type", required = true) - @JsonProperty("vnf-type") - protected String vnfType; - @JsonProperty("vm") - protected List vm; - - /** - * Gets the value of the vnfId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getVnfId() { - return vnfId; - } - - /** - * Sets the value of the vnfId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVnfId(String value) { - this.vnfId = value; - } - - /** - * Gets the value of the vnfName property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getVnfName() { - return vnfName; - } - - /** - * Sets the value of the vnfName property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVnfName(String value) { - this.vnfName = value; - } - - /** - * Gets the value of the vnfType property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getVnfType() { - return vnfType; - } - - /** - * Sets the value of the vnfType property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVnfType(String value) { - this.vnfType = value; - } - - /** - * Gets the value of the vm property. - * - *

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

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

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

- * Objects of the following type(s) are allowed in the list - * {@link Vm } - * - * - */ - public List getVm() { - if (vm == null) { - vm = new ArrayList(); - } - return this.vm; - } - - @Override - public String toString() { - return "VnfInfo [vnfId=" + vnfId + ", vnfName=" + vnfName - + ", vnfType=" + vnfType + ", vm=" + vm + "]"; - } - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Vnfcs.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Vnfcs.java deleted file mode 100644 index 7adf05d3c..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Vnfcs.java +++ /dev/null @@ -1,176 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2017.07.31 at 10:30:39 AM EDT -// - - -package org.onap.appc.flow.controller.interfaceData; - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlList; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonRootName; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "vnfcType", - "mandatory", - "resilience", - "parents" -}) -@XmlRootElement(name = "vnfcs") -@JsonRootName(value="vnfcs") -public class Vnfcs { - - @XmlElement(name = "vnfc-type", required = true) - @JsonProperty("vnfc-type") - protected String vnfcType; - @XmlElement(required = true) - @JsonProperty("mandatory") - protected String mandatory; - @XmlElement(required = true) - @JsonProperty("resilience") - protected String resilience; - @XmlList - @XmlElement(required = true) - @JsonProperty("parents") - protected List parents; - - /** - * Gets the value of the vnfcType property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getVnfcType() { - return vnfcType; - } - - /** - * Sets the value of the vnfcType property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVnfcType(String value) { - this.vnfcType = value; - } - - /** - * Gets the value of the mandatory property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMandatory() { - return mandatory; - } - - /** - * Sets the value of the mandatory property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMandatory(String value) { - this.mandatory = value; - } - - /** - * Gets the value of the resilience property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getResilience() { - return resilience; - } - - /** - * Sets the value of the resilience property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setResilience(String value) { - this.resilience = value; - } - - /** - * Gets the value of the parents property. - * - *

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

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

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

- * Objects of the following type(s) are allowed in the list - * {@link String } - * - * - */ - public List getParents() { - if (parents == null) { - parents = new ArrayList(); - } - return this.parents; - } - - @Override - public String toString() { - return "Vnfcs [vnfcType=" + vnfcType + ", mandatory=" + mandatory - + ", resilience=" + resilience + ", parents=" + parents + "]"; - } - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Vnfcslist.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Vnfcslist.java deleted file mode 100644 index 849f7cad9..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Vnfcslist.java +++ /dev/null @@ -1,127 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2017.07.31 at 10:30:39 AM EDT -// - - -package org.onap.appc.flow.controller.interfaceData; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - -import com.fasterxml.jackson.annotation.JsonProperty; - - -/** - *

Java class for vnfcslist complex type. - * - *

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

- * <complexType name="vnfcslist">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="vnfc-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="vnfc-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "vnfcslist", propOrder = { - "vnfcType", - "vnfcName" -}) -public class Vnfcslist { - - @XmlElement(name = "vnfc-type", required = true) - @JsonProperty("vnfc-type") - protected String vnfcType; - @XmlElement(name = "vnfc-name", required = true) - @JsonProperty("vnfc-name") - protected String vnfcName; - - /** - * Gets the value of the vnfcType property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getVnfcType() { - return vnfcType; - } - - /** - * Sets the value of the vnfcType property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVnfcType(String value) { - this.vnfcType = value; - } - - /** - * Gets the value of the vnfcName property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getVnfcName() { - return vnfcName; - } - - /** - * Sets the value of the vnfcName property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVnfcName(String value) { - this.vnfcName = value; - } - - @Override - public String toString() { - return "Vnfcslist [vnfcType=" + vnfcType + ", vnfcName=" + vnfcName - + "]"; - } - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Vnflist.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Vnflist.java deleted file mode 100644 index 1d63f6e53..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/Vnflist.java +++ /dev/null @@ -1,150 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2017.07.03 at 03:13:44 PM EDT -// - - -package org.onap.appc.flow.controller.interfaceData; - -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for vnflist. - * - *

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

- *

- * <simpleType name="vnflist">
- *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
- *     <enumeration value="Restart"/>
- *     <enumeration value="Rebuild"/>
- *     <enumeration value="Migrate"/>
- *     <enumeration value="Evacuate"/>
- *     <enumeration value="Snapshot"/>
- *     <enumeration value="Rollback"/>
- *     <enumeration value="Sync"/>
- *     <enumeration value="Audit"/>
- *     <enumeration value="Start"/>
- *     <enumeration value="Stop"/>
- *     <enumeration value="Terminate"/>
- *     <enumeration value="SoftwareUpload"/>
- *     <enumeration value="HealthCheck"/>
- *     <enumeration value="LiveUpgrade"/>
- *     <enumeration value="ModifyConfig"/>
- *     <enumeration value="Lock"/>
- *     <enumeration value="Unlock"/>
- *     <enumeration value="Test"/>
- *     <enumeration value="CheckLock"/>
- *     <enumeration value="Configure"/>
- *     <enumeration value="ConfigModify"/>
- *     <enumeration value="ConfigScaleOut"/>
- *     <enumeration value="ConfigRestore"/>
- *     <enumeration value="ConfigBackup"/>
- *     <enumeration value="ConfigBackupDelete"/>
- *     <enumeration value="ConfigExport"/>
- *   </restriction>
- * </simpleType>
- * 
- * - */ -@XmlType(name = "vnflist") -@XmlEnum -public enum Vnflist { - - @XmlEnumValue("Restart") - RESTART("Restart"), - @XmlEnumValue("Rebuild") - REBUILD("Rebuild"), - @XmlEnumValue("Migrate") - MIGRATE("Migrate"), - @XmlEnumValue("Evacuate") - EVACUATE("Evacuate"), - @XmlEnumValue("Snapshot") - SNAPSHOT("Snapshot"), - @XmlEnumValue("Rollback") - ROLLBACK("Rollback"), - @XmlEnumValue("Sync") - SYNC("Sync"), - @XmlEnumValue("Audit") - AUDIT("Audit"), - @XmlEnumValue("Start") - START("Start"), - @XmlEnumValue("Stop") - STOP("Stop"), - @XmlEnumValue("Terminate") - TERMINATE("Terminate"), - @XmlEnumValue("SoftwareUpload") - SOFTWARE_UPLOAD("SoftwareUpload"), - @XmlEnumValue("HealthCheck") - HEALTH_CHECK("HealthCheck"), - @XmlEnumValue("LiveUpgrade") - LIVE_UPGRADE("LiveUpgrade"), - @XmlEnumValue("ModifyConfig") - MODIFY_CONFIG("ModifyConfig"), - @XmlEnumValue("Lock") - LOCK("Lock"), - @XmlEnumValue("Unlock") - UNLOCK("Unlock"), - @XmlEnumValue("Test") - TEST("Test"), - @XmlEnumValue("CheckLock") - CHECK_LOCK("CheckLock"), - @XmlEnumValue("Configure") - CONFIGURE("Configure"), - @XmlEnumValue("ConfigModify") - CONFIG_MODIFY("ConfigModify"), - @XmlEnumValue("ConfigScaleOut") - CONFIG_SCALE_OUT("ConfigScaleOut"), - @XmlEnumValue("ConfigRestore") - CONFIG_RESTORE("ConfigRestore"), - @XmlEnumValue("ConfigBackup") - CONFIG_BACKUP("ConfigBackup"), - @XmlEnumValue("ConfigBackupDelete") - CONFIG_BACKUP_DELETE("ConfigBackupDelete"), - @XmlEnumValue("ConfigExport") - CONFIG_EXPORT("ConfigExport"); - private final String value; - - Vnflist(String v) { - value = v; - } - - public String value() { - return value; - } - - public static Vnflist fromValue(String v) { - for (Vnflist c: Vnflist.values()) { - if (c.value.equals(v)) { - return c; - } - } - throw new IllegalArgumentException(v); - } - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/package-info.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/package-info.java deleted file mode 100644 index 926dfafd8..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaceData/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2017.07.31 at 10:30:39 AM EDT -// - -@javax.xml.bind.annotation.XmlSchema(namespace = "http:org.onap.appc/sequence/v1", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) -package org.onap.appc.flow.controller.interfaceData; diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaces/FlowExecutorInterface.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaces/FlowExecutorInterface.java deleted file mode 100644 index dbf27c829..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/interfaces/FlowExecutorInterface.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.interfaces; - -import java.util.HashMap; - -import org.onap.appc.flow.controller.data.Transaction; -import org.onap.appc.flow.controller.utils.FlowControllerConstants; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public interface FlowExecutorInterface { - - public HashMap execute(Transaction transaction, SvcLogicContext ctx) throws Exception; - - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/node/FlowControlNode.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/node/FlowControlNode.java deleted file mode 100644 index 010729f29..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/node/FlowControlNode.java +++ /dev/null @@ -1,562 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.node; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.flow.controller.ResponseHandlerImpl.DefaultResponseHandler; -import org.onap.appc.flow.controller.data.PrecheckOption; -import org.onap.appc.flow.controller.data.ResponseAction; -import org.onap.appc.flow.controller.data.Transaction; -import org.onap.appc.flow.controller.data.Transactions; -import org.onap.appc.flow.controller.dbervices.FlowControlDBService; -import org.onap.appc.flow.controller.executorImpl.GraphExecutor; -import org.onap.appc.flow.controller.executorImpl.NodeExecutor; -import org.onap.appc.flow.controller.executorImpl.RestExecutor; -import org.onap.appc.flow.controller.interfaceData.ActionIdentifier; -import org.onap.appc.flow.controller.interfaceData.Capabilities; -import org.onap.appc.flow.controller.interfaceData.DependencyInfo; -import org.onap.appc.flow.controller.interfaceData.Input; -import org.onap.appc.flow.controller.interfaceData.InventoryInfo; -import org.onap.appc.flow.controller.interfaceData.RequestInfo; -import org.onap.appc.flow.controller.interfaceData.Vm; -import org.onap.appc.flow.controller.interfaceData.VnfInfo; -import org.onap.appc.flow.controller.interfaceData.Vnfcs; -import org.onap.appc.flow.controller.interfaceData.Vnfcslist; -import org.onap.appc.flow.controller.interfaces.FlowExecutorInterface; -import org.onap.appc.flow.controller.utils.FlowControllerConstants; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - -public class FlowControlNode implements SvcLogicJavaPlugin{ - - - private static final EELFLogger log = EELFManager.getInstance().getLogger(FlowControlNode.class); - private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; - - public void processFlow(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - log.debug("Received processParamKeys call with params : " + inParams); - String responsePrefix = inParams.get(FlowControllerConstants.INPUT_PARAM_RESPONSE_PRIFIX); - try - { - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - FlowControlDBService dbservice = FlowControlDBService.initialise(); - SvcLogicContext localContext = new SvcLogicContext(); - localContext.setAttribute(FlowControllerConstants.REQUEST_ID, ctx.getAttribute(FlowControllerConstants.REQUEST_ID)); - localContext.setAttribute(FlowControllerConstants.VNF_TYPE, ctx.getAttribute(FlowControllerConstants.VNF_TYPE)); - localContext.setAttribute(FlowControllerConstants.REQUEST_ACTION, ctx.getAttribute(FlowControllerConstants.REQUEST_ACTION)); - localContext.setAttribute(FlowControllerConstants.ACTION_LEVEL, ctx.getAttribute(FlowControllerConstants.ACTION_LEVEL)); - localContext.setAttribute(FlowControllerConstants.RESPONSE_PREFIX, responsePrefix); - ctx.setAttribute(FlowControllerConstants.RESPONSE_PREFIX, responsePrefix); - dbservice.getFlowReferenceData(ctx, inParams, localContext); - - for (Object key : localContext.getAttributeKeySet()) { - String parmName = (String) key; - String parmValue = ctx.getAttribute(parmName); - log.debug("processFlow " + parmName + "=" + parmValue); - - } - processFlowSequence(inParams, ctx, localContext); - if(!ctx.getAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_STATUS).equals(FlowControllerConstants.OUTPUT_STATUS_SUCCESS)) - throw new SvcLogicException(ctx.getAttribute(responsePrefix + FlowControllerConstants.OUTPUT_STATUS_MESSAGE)); - - } catch (Exception e) { - ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_STATUS, FlowControllerConstants.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - e.printStackTrace(); - throw new SvcLogicException(e.getMessage()); - } - } - - private void processFlowSequence( Map inParams, SvcLogicContext ctx, SvcLogicContext localContext) throws Exception - { - String fn = "FlowExecutorNode.processflowSequence"; - log.debug(fn + "Received model for flow : " + localContext.toString()); - FlowControlDBService dbservice = FlowControlDBService.initialise(); - String flowSequnce =null; - for (Object key : localContext.getAttributeKeySet()) { - String parmName = (String) key; - String parmValue = ctx.getAttribute(parmName); - log.debug(parmName + "=" + parmValue); - - } - if(localContext != null && localContext.getAttribute(FlowControllerConstants.SEQUENCE_TYPE) !=null){ - - if(localContext.getAttribute(FlowControllerConstants.GENERATION_NODE) != null){ - GraphExecutor transactionExecutor = new GraphExecutor(); - Boolean generatorExists = transactionExecutor.hasGraph("APPC_COMMOM", localContext.getAttribute(FlowControllerConstants.GENERATION_NODE), null, "sync"); - if(generatorExists){ - flowSequnce = transactionExecutor.executeGraph("APPC_COMMOM", localContext.getAttribute(FlowControllerConstants.GENERATION_NODE), - null, "sync", null).getProperty(FlowControllerConstants.FLOW_SEQUENCE); - } - else - throw new Exception("Can not find Custom defined Flow Generator for " + localContext.getAttribute(FlowControllerConstants.GENERATION_NODE)); - } - else if(((String) localContext.getAttribute(FlowControllerConstants.SEQUENCE_TYPE)).equalsIgnoreCase(FlowControllerConstants.DESINGTIME)){ - localContext.setAttribute(FlowControllerConstants.VNFC_TYPE, ctx.getAttribute(FlowControllerConstants.VNFC_TYPE)); - flowSequnce = dbservice.getDesignTimeFlowModel(localContext); - if(flowSequnce == null) - throw new Exception("Flow Sequence is not found User Desinged VNF " + ctx.getAttribute(FlowControllerConstants.VNF_TYPE)); - } - else if(((String) localContext.getAttribute(FlowControllerConstants.SEQUENCE_TYPE)).equalsIgnoreCase(FlowControllerConstants.RUNTIME)){ - - Transaction transaction = new Transaction(); - String input = collectInputParams(ctx,transaction); - log.info("collectInputParamsData" + input ); - - RestExecutor restExe = new RestExecutor(); - HashMapflowSeq= restExe.execute(transaction, localContext); - flowSequnce=flowSeq.get("restResponse"); - - if(flowSequnce == null) - throw new Exception("Failed to get the Flow Sequece runtime for VNF type" + ctx.getAttribute(FlowControllerConstants.VNF_TYPE)); - - } - else if(((String) localContext.getAttribute(FlowControllerConstants.SEQUENCE_TYPE)).equalsIgnoreCase(FlowControllerConstants.EXTERNAL)){ - //String input = collectInputParams(localContext); - // flowSequnce = ""; //get it from the External interface calling the Rest End point - TBD - if(flowSequnce == null) - throw new Exception("Flow Sequence not found for " + ctx.getAttribute(FlowControllerConstants.VNF_TYPE)); - } - else - { - //No other type of model supported...in Future can get flowModel from other generators which will be included here - throw new Exception("No information found for sequence Owner Design-Time Vs Run-Time" ); - } - } - else{ - FlowGenerator flowGenerator = new FlowGenerator(); - Transactions trans = flowGenerator.createSingleStepModel(inParams,ctx); - ObjectMapper mapper = new ObjectMapper(); - flowSequnce = mapper.writeValueAsString(trans); - log.debug("Single step Flow Sequence : " + flowSequnce); - - } - log.debug("Received Flow Sequence : " + flowSequnce); - - HashMap transactionMap = createTransactionMap(flowSequnce, localContext); - exeuteAllTransaction(transactionMap, ctx); - log.info("Executed all the transacstion successfully"); - - } - - private void exeuteAllTransaction(HashMap transactionMap, SvcLogicContext ctx) throws Exception { - - String fn = "FlowExecutorNode.exeuteAllTransaction "; - int retry = 0; - FlowExecutorInterface flowExecutor = null; - for (int key = 1; key <= transactionMap.size() ; key++ ) - { - log.debug(fn + "Starting transactions ID " + key + " :)=" + retry); - Transaction transaction = transactionMap.get(key); - if(!preProcessor(transactionMap, transaction)){ - log.info("Skipping Transaction ID " + transaction.getTransactionId()); - continue; - } - if(transaction.getExecutionType() != null){ - switch (transaction.getExecutionType()){ - case FlowControllerConstants.GRAPH : - flowExecutor = new GraphExecutor(); - break; - case FlowControllerConstants.NODE : - flowExecutor = new NodeExecutor(); - break; - case FlowControllerConstants.REST : - flowExecutor = new RestExecutor(); - break; - default : - throw new Exception("No Executor found for transaction ID" + transaction.getTransactionId()); - } - flowExecutor.execute(transaction, ctx); - ResponseAction responseAction= handleResponse(transaction); - - if(responseAction.getWait() != null && Integer.parseInt(responseAction.getWait()) > 0){ - log.debug(fn + "Going to Sleep .... " + responseAction.getWait()); - Thread.sleep(Integer.parseInt(responseAction.getWait())*1000); - } - - if(responseAction.isIntermediateMessage()){ - log.debug(fn + "Sending Intermediate Message back .... "); - sendIntermediateMessage(); - } - if(responseAction.getRetry() != null && Integer.parseInt(responseAction.getRetry()) > retry ){ - log.debug(fn + "Ooppss!!! We will retry again ....... "); - key--; - retry++; - log.debug(fn + "key =" + key + "retry =" + retry); - - } - if(responseAction.isIgnore()){ - log.debug(fn + "Ignoring this Error and moving ahead ....... "); - continue; - } - if(responseAction.isStop()){ - log.debug(fn + "Need to Stop ....... "); - break; - } - if(responseAction.getJump() != null && Integer.parseInt(responseAction.getJump()) > 0 ){ - key = Integer.parseInt(responseAction.getJump()); - key --; - } - log.debug(fn + "key =" + key + "retry =" + retry); - - } - else{ - throw new Exception("Don't know how to execute transaction ID " + transaction.getTransactionId()); - } - } - - } - private void sendIntermediateMessage() { - // TODO Auto-generated method stub - - } - - private ResponseAction handleResponse(Transaction transaction) { - log.info("Handling Response for transaction Id " + transaction.getTransactionId()); - DefaultResponseHandler defaultHandler = new DefaultResponseHandler(); - return defaultHandler.handlerResponse(transaction); - } - - private boolean preProcessor(HashMap transactionMap, Transaction transaction) throws IOException { - - log.debug("Starting Preprocessing Logic "); - boolean runthisStep = false; - try{ - if(transaction.getPrecheck() != null && transaction.getPrecheck().getPrecheckOptions() != null - && !transaction.getPrecheck().getPrecheckOptions().isEmpty()){ - List precheckOptions = transaction.getPrecheck().getPrecheckOptions(); - for(PrecheckOption precheck : precheckOptions){ - Transaction trans = transactionMap.get(precheck.getpTransactionID()); - ObjectMapper mapper = new ObjectMapper(); - log.info("Mapper= " + mapper.writeValueAsString(trans)); - HashMap trmap = mapper.readValue(mapper.writeValueAsString(trans), HashMap.class); - if(trmap.get(precheck.getParamName()) != null && - ((String) trmap.get(precheck.getParamName())).equalsIgnoreCase(precheck.getParamValue())) - runthisStep = true; - else - runthisStep = false; - - if(transaction.getPrecheck().getPrecheckOperator() != null && - transaction.getPrecheck().getPrecheckOperator().equalsIgnoreCase("any") && runthisStep) - break; - } - } - - else{ - log.debug("No Pre check defined for transaction ID " + transaction.getTransactionId()); - runthisStep = true; - - } - } - catch(Exception e) - { - e.printStackTrace(); - throw e; - } - log.debug("Returing process current Transaction = " + runthisStep); - - return runthisStep ; - } - - private HashMap createTransactionMap(String flowSequnce, SvcLogicContext localContext) throws SvcLogicException, JsonParseException, JsonMappingException, IOException { - ObjectMapper mapper = new ObjectMapper(); - Transactions transactions = mapper.readValue(flowSequnce,Transactions.class); - HashMap transMap = new HashMap(); - for(Transaction transaction : transactions.getTransactions()){ - compileFlowDependencies(transaction, localContext); - //loadTransactionIntoStatus(transactions, ctx); //parse the Transactions Object and create records in process_flow_status table - transMap.put(transaction.getTransactionId(), transaction); - } - return transMap; - } - - private void compileFlowDependencies(Transaction transaction, SvcLogicContext localContext) throws SvcLogicException, JsonParseException, JsonMappingException, IOException { - - String fn = "FlowExecutorNode.compileFlowDependencies"; - FlowControlDBService dbservice = FlowControlDBService.initialise(); - dbservice.populateModuleAndRPC(transaction, localContext.getAttribute(FlowControllerConstants.VNF_TYPE)); - ObjectMapper mapper = new ObjectMapper(); - log.debug("Indivisual Transaction Details :" + transaction.toString()); - if((localContext.getAttribute(FlowControllerConstants.SEQUENCE_TYPE) == null) || - ( localContext.getAttribute(FlowControllerConstants.SEQUENCE_TYPE) != null && - ! localContext.getAttribute(FlowControllerConstants.SEQUENCE_TYPE).equalsIgnoreCase(FlowControllerConstants.DESINGTIME))){ - localContext.setAttribute("artifact-content", mapper.writeValueAsString(transaction)); - dbservice.loadSequenceIntoDB(localContext); - } - //get a field in transction class as transactionhandle interface and register the Handler here for each trnactions - } - - private String collectInputParams(SvcLogicContext ctx, Transaction transaction) throws Exception { - - String fn = "FlowExecuteNode.collectInputParams"; - Properties prop = loadProperties(); - log.info("Loaded Properties " + prop.toString()); - - String vnfId = ctx.getAttribute(FlowControllerConstants.VNF_ID); - log.debug(fn + "vnfId :" + vnfId); - - if (StringUtils.isBlank(vnfId)) { - throw new Exception("VnfId is missing"); - } - - ActionIdentifier actionIdentifier = new ActionIdentifier(); - actionIdentifier.setVnfId(vnfId); - actionIdentifier.setVserverId(ctx.getAttribute(FlowControllerConstants.VSERVER_ID)); - actionIdentifier.setVnfcName(ctx.getAttribute(FlowControllerConstants.VNFC_NAME)); - - RequestInfo requestInfo = new RequestInfo(); - requestInfo.setAction(ctx.getAttribute(FlowControllerConstants.ACTION)); - requestInfo.setActionLevel(ctx.getAttribute(FlowControllerConstants.ACTION_LEVEL)); - requestInfo.setPayload(ctx.getAttribute(FlowControllerConstants.PAYLOAD)); - requestInfo.setActionIdentifier(actionIdentifier); - - InventoryInfo inventoryInfo = getInventoryInfo(ctx,vnfId); - DependencyInfo dependencyInfo = getDependencyInfo(ctx); - Capabilities capabilites = getCapabilitesData(ctx); - - Input input = new Input(); - input.setRequestInfo(requestInfo); - input.setInventoryInfo(inventoryInfo); - input.setDependencyInfo(dependencyInfo); - input.setCapabilities(capabilites); - //input.setTunableParameters(null); - - - log.info(fn + "Input parameters:" + input.toString()); - - String inputData = null; - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_NULL); - mapper.configure(SerializationFeature.WRAP_ROOT_VALUE,true); - inputData = mapper.writeValueAsString(input); - log.info("InputDataJson:"+inputData); - - } catch (Exception e) { - e.printStackTrace(); - } - - String resourceUri = prop.getProperty(FlowControllerConstants.SEQ_GENERATOR_URL); - log.info(fn + "resourceUri= " + resourceUri); - - transaction.setPayload(inputData); - transaction.setExecutionRPC("POST"); - transaction.setuId(prop.getProperty(FlowControllerConstants.SEQ_GENERATOR_UID)); - transaction.setPswd(prop.getProperty(FlowControllerConstants.SEQ_GENERATOR_PWD)); - transaction.setExecutionEndPoint(resourceUri); - - return inputData; - - } - - private DependencyInfo getDependencyInfo(SvcLogicContext ctx) throws Exception { - - String fn = "FlowExecutorNode.getDependencyInfo"; - DependencyInfo dependencyInfo = new DependencyInfo(); - FlowControlDBService dbservice = FlowControlDBService.initialise(); - String dependencyData = dbservice.getDependencyInfo(ctx); - log.info(fn + "dependencyDataInput:" + dependencyData); - - if (dependencyData != null) { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false); - mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); - JsonNode dependencyInfoData = mapper.readTree(dependencyData).get("dependencyInfo"); - JsonNode vnfcData = mapper.readTree(dependencyInfoData.toString()).get("vnfcs"); - List vnfclist = Arrays.asList(mapper.readValue(vnfcData.toString(), Vnfcs[].class)); - dependencyInfo.getVnfcs().addAll(vnfclist); - - log.info("Dependency Output:"+ dependencyInfo.toString()); - } - - return dependencyInfo; - - } - - private Capabilities getCapabilitesData(SvcLogicContext ctx)throws Exception { - - String fn = "FlowExecutorNode.getCapabilitesData"; - Capabilities capabilities = new Capabilities(); - FlowControlDBService dbservice = FlowControlDBService.initialise(); - String capabilitiesData = dbservice.getCapabilitiesData(ctx); - log.info(fn + "capabilitiesDataInput:" + capabilitiesData); - - if (capabilitiesData != null) { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false); - mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); - JsonNode capabilitiesNode = mapper.readValue(capabilitiesData,JsonNode.class); - log.info("capabilitiesNode:" + capabilitiesNode.toString()); - - JsonNode vnfs = capabilitiesNode.findValue(FlowControllerConstants.VNF); - List vnfsList = new ArrayList(); - if (vnfs != null) { - for (int i = 0; i < vnfs.size(); i++) { - - String vnf = vnfs.get(i).asText(); - vnfsList.add(vnf); - } - } - - JsonNode vfModules = capabilitiesNode.findValue(FlowControllerConstants.VF_MODULE); - List vfModulesList = new ArrayList(); - if (vfModules != null) { - for (int i = 0; i < vfModules.size(); i++) { - - String vfModule = vfModules.get(i).asText(); - vfModulesList.add(vfModule); - } - } - - JsonNode vnfcs = capabilitiesNode.findValue(FlowControllerConstants.VNFC); - List vnfcsList = new ArrayList(); - if (vnfcs != null) { - for (int i = 0; i < vnfcs.size(); i++) { - - String vnfc1 = vnfcs.get(i).asText(); - vnfcsList.add(vnfc1); - } - } - - JsonNode vms = capabilitiesNode.findValue(FlowControllerConstants.VM); - - List vmList = new ArrayList(); - if (vms != null) { - for (int i = 0; i < vms.size(); i++) { - - String vm1 = vms.get(i).asText(); - vmList.add(vm1); - } - } - - capabilities.getVnfc().addAll(vnfcsList); - capabilities.getVnf().addAll(vnfsList); - capabilities.getVfModule().addAll(vfModulesList); - capabilities.getVm().addAll(vmList); - - log.info("Capabilities Output:"+ capabilities.toString()); - - } - - return capabilities; - - } - - private InventoryInfo getInventoryInfo(SvcLogicContext ctx, String vnfId) throws Exception{ - - String fn = "FlowExecutorNode.getInventoryInfo"; - String vmcount = ctx.getAttribute("tmp.vnfInfo.vm-count"); - int vmCount = Integer.parseInt(vmcount); - log.info(fn +"vmcount:"+ vmCount); - - VnfInfo vnfInfo = new VnfInfo(); - vnfInfo.setVnfId(vnfId); - vnfInfo.setVnfName(ctx.getAttribute("tmp.vnfInfo.vnf.vnf-name")); - vnfInfo.setVnfType(ctx.getAttribute("tmp.vnfInfo.vnf.vnf-type")); - - Vm vm = new Vm(); - Vnfcslist vnfc = new Vnfcslist(); - - if (vmCount > 0) { - - for (int i = 0; i < vmCount; i++) { - - vm.setVserverId(ctx.getAttribute("tmp.vnfInfo.vm[" + i + "].vserverId")); - String vnfccount = ctx.getAttribute("tmp.vnfInfo.vm[" + i + "].vnfc-count"); - int vnfcCount = Integer.parseInt(vnfccount); - - if (vnfcCount > 0) { - vnfc.setVnfcName(ctx.getAttribute("tmp.vnfInfo.vm[" + i + "].vnfc-name")); - vnfc.setVnfcType(ctx.getAttribute("tmp.vnfInfo.vm[" + i + "].vnfc-type")); - vm.setVnfc(vnfc); - } - vnfInfo.getVm().add(vm); - } - } - - InventoryInfo inventoryInfo = new InventoryInfo(); - inventoryInfo.setVnfInfo(vnfInfo); - - return inventoryInfo; - - } - - private String getFlowSequence() throws IOException { - - String sequenceModel = IOUtils.toString(FlowControlNode.class.getClassLoader().getResourceAsStream("sequence.json"), Charset.defaultCharset()); - - return null; - } - - -private static Properties loadProperties() throws Exception { - Properties props = new Properties(); - String propDir = System.getenv(SDNC_CONFIG_DIR_VAR); - if (propDir == null) - throw new Exception("Cannot find Property file -" + SDNC_CONFIG_DIR_VAR); - String propFile = propDir + FlowControllerConstants.APPC_FLOW_CONTROLLER; - InputStream propStream = new FileInputStream(propFile); - try - { - props.load(propStream); - } - catch (Exception e) - { - throw new Exception("Could not load properties file " + propFile, e); - } - finally - { - try - { - propStream.close(); - } - catch (Exception e) - { - log.warn("Could not close FileInputStream", e); - } - } - return props; -} - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/node/FlowGenerator.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/node/FlowGenerator.java deleted file mode 100644 index fe894c955..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/node/FlowGenerator.java +++ /dev/null @@ -1,80 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.node; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.onap.appc.flow.controller.data.Response; -import org.onap.appc.flow.controller.data.ResponseAction; -import org.onap.appc.flow.controller.data.Transaction; -import org.onap.appc.flow.controller.data.Transactions; -import org.onap.appc.flow.controller.utils.FlowControllerConstants; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class FlowGenerator { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(FlowGenerator.class); - - public Transactions createSingleStepModel(Map inParams, SvcLogicContext ctx) { - - String fn = "FlowGenerator.createSingleStepModel"; - log.debug("Starting generating single Step flow" ); - - log.debug("Data in context" + ctx.getAttributeKeySet() ); - Transactions transactions = new Transactions(); - List transactionList = new ArrayList(); - Transaction singleTransaction = new Transaction(); - - singleTransaction.setTransactionId(1); - singleTransaction.setAction(ctx.getAttribute(FlowControllerConstants.REQUEST_ACTION)); - singleTransaction.setActionLevel(FlowControllerConstants.VNF); //Need to discuss how to get action level if not in request - singleTransaction.setPayload(ctx.getAttribute(FlowControllerConstants.PAYLOAD)); - singleTransaction.setActionLevel(ctx.getAttribute(FlowControllerConstants.ACTION_LEVEL)); - - - - - List responseList = new ArrayList(); - Response response = new Response(); - - ResponseAction ra = new ResponseAction(); - ra.setStop(true); - response.setResponseAction(ra); - - responseList.add(response); - singleTransaction.setResponses(responseList); - transactionList.add(singleTransaction); - - transactions.setTransactions(transactionList); - - log.debug("Sequence String" + transactions.toString()); - - return transactions; - } - - - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/node/JsonParsingNode.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/node/JsonParsingNode.java deleted file mode 100644 index dd56aee60..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/node/JsonParsingNode.java +++ /dev/null @@ -1,98 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.node; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; - -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.flow.controller.data.Transaction; -import org.onap.appc.flow.controller.executorImpl.RestExecutor; -import org.onap.appc.flow.controller.utils.FlowControllerConstants; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JsonParsingNode implements SvcLogicJavaPlugin{ - - - private static final EELFLogger log = EELFManager.getInstance().getLogger(JsonParsingNode.class); - private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; - - public void parse(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - String fn = "RestServiceNode.sendRequest"; - log.info("Received processParamKeys call with params : " + inParams); - String responsePrefix = inParams.get(FlowControllerConstants.INPUT_PARAM_RESPONSE_PRIFIX); - try - { - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - //Remove below for Block - if(isValidJSON(inParams.get("data")) !=null){ - JsonNode jnode = isValidJSON(inParams.get("data")); - ObjectMapper mapper = new ObjectMapper(); - Map map = new HashMap(); - map = mapper.readValue(jnode.toString(), new TypeReference>(){}); - for (Entry entry : map.entrySet()) - { - ctx.setAttribute(responsePrefix + entry.getKey(),(String) entry.getValue()); - } - - } - ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_STATUS, FlowControllerConstants.OUTPUT_STATUS_SUCCESS); - - } catch (Exception e) { - ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_STATUS, FlowControllerConstants.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - e.printStackTrace(); - log.error("Error Message : " + e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - } - - public JsonNode isValidJSON(String json) throws IOException { - JsonNode output = null; - log.info("Received response from Interface " + json); - if(json ==null || json.isEmpty()) - return null; - try{ - ObjectMapper objectMapper = new ObjectMapper(); - output = objectMapper.readTree(json); - } catch(JsonProcessingException e){ - log.warn("Response received from interface is not a valid JSON block" + json); - return null; - } - - return output; - } -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/node/RestServiceNode.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/node/RestServiceNode.java deleted file mode 100644 index 1975de3d9..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/node/RestServiceNode.java +++ /dev/null @@ -1,207 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.node; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.flow.controller.data.Transaction; -import org.onap.appc.flow.controller.executorImpl.RestExecutor; -import org.onap.appc.flow.controller.utils.FlowControllerConstants; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class RestServiceNode implements SvcLogicJavaPlugin{ - - - private static final EELFLogger log = EELFManager.getInstance().getLogger(RestServiceNode.class); - private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; - - public void sendRequest(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - String fn = "RestServiceNode.sendRequest"; - log.info("Received processParamKeys call with params : " + inParams); - String responsePrefix = inParams.get(FlowControllerConstants.INPUT_PARAM_RESPONSE_PRIFIX); - try - { - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - //Remove below for Block - for (Object key : ctx.getAttributeKeySet()) { - String parmName = (String) key; - String parmValue = ctx.getAttribute(parmName); - log.info(fn + "Getting Key = " + parmName + "and Value = " + parmValue); - } - - send(ctx, inParams); - ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_STATUS, FlowControllerConstants.OUTPUT_STATUS_SUCCESS); - - } catch (Exception e) { - ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_STATUS, FlowControllerConstants.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - e.printStackTrace(); - log.error("Error Message : " + e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - } - - public void send(SvcLogicContext ctx, Map inParams) throws Exception{ - try{ - Properties prop = loadProperties(); - log.info("Loaded Properties " + prop.toString()); - String responsePrefix = inParams.get(FlowControllerConstants.INPUT_PARAM_RESPONSE_PRIFIX); - RestExecutor restRequestExecutor = new RestExecutor(); - String resourceUri = ""; - if(ctx.getAttribute(FlowControllerConstants.INPUT_URL) != null && !(ctx.getAttribute(FlowControllerConstants.INPUT_URL).isEmpty())) - resourceUri = ctx.getAttribute(FlowControllerConstants.INPUT_URL); - else{ - resourceUri = resourceUri.concat(FlowControllerConstants.HTTP); - log.info("resourceUri= " + resourceUri ); - resourceUri = resourceUri.concat(ctx.getAttribute(FlowControllerConstants.INPUT_HOST_IP_ADDRESS)); - resourceUri = resourceUri.concat(":"); - resourceUri = resourceUri.concat(ctx.getAttribute(FlowControllerConstants.INPUT_PORT_NUMBER)); - - if(ctx.getAttribute(FlowControllerConstants.INPUT_CONTEXT) != null && !ctx.getAttribute(FlowControllerConstants.INPUT_CONTEXT).isEmpty()){ - resourceUri = resourceUri.concat("/").concat(ctx.getAttribute(FlowControllerConstants.INPUT_CONTEXT)); - log.info("resourceUri= " + resourceUri ); - } - else if(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".context")) != null ){ - log.info("resourceUri = " + resourceUri ); - resourceUri = resourceUri.concat("/").concat(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".context"))); - } - else - throw new Exception("Could Not found the context for operation " + ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION)); - - - if(ctx.getAttribute(FlowControllerConstants.INPUT_SUB_CONTEXT) != null && !ctx.getAttribute(FlowControllerConstants.INPUT_SUB_CONTEXT).isEmpty()){ - resourceUri = resourceUri.concat("/").concat(ctx.getAttribute(FlowControllerConstants.INPUT_SUB_CONTEXT)); - log.info("resourceUri" + resourceUri ); - } - else if(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".sub-context")) != null ){ - resourceUri = resourceUri.concat("/").concat(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".sub-context"))); - log.info("resourceUri" + resourceUri ); - } - } - - log.info("Rest Constructed URL : " + resourceUri); - Transaction transaction = new Transaction(); - - transaction.setExecutionEndPoint(resourceUri); - transaction.setExecutionRPC(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION_TYPE)); - transaction.setAction(FlowControllerConstants.INPUT_REQUEST_ACTION); - if(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION_TYPE) == null || ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION_TYPE).isEmpty()) - throw new Exception("Dont know REST operation for Action " + transaction.getExecutionRPC()); - if(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION) == null || ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).isEmpty()) - throw new Exception("Dont know request-action " + transaction.getAction()); - - //This code need to get changed to get the UserID and pass from a common place. - if(transaction.getuId() == null ) - transaction.setuId(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".default-rest-user"))); - if(transaction.getPswd() == null) - transaction.setPswd(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".default-rest-pass"))); - - HashMap output = restRequestExecutor.execute(transaction, ctx); - - if(output.get("restResponse") !=null && isValidJSON(output.get("restResponse")) != null) - { - ctx.setAttribute(responsePrefix + "." + FlowControllerConstants.OUTPUT_STATUS_MESSAGE , output.get("restResponse")); -// JsonNode restResponse = isValidJSON(output.get("restResponse")); -// for (String key : inParams.keySet()) { -// if(key !=null && key.startsWith("output-")){ -// log.info("Found Key = " + key); -// log.info("Found Key in Params " + inParams.get(key) + "."); -// JsonNode setValue = restResponse.findValue(inParams.get(key)); -// log.info("Found value = " + setValue); -// if(setValue !=null && setValue.textValue() !=null && !setValue.textValue().isEmpty()) -// ctx.setAttribute(responsePrefix + "." + key, setValue.textValue()); -// else -// ctx.setAttribute(responsePrefix + "." + key, null); -// } -// } - } - log.info("Response from Rest :" ); - } - catch(Exception e) - { - e.printStackTrace(); - log.error("Error Message " + e.getMessage()); - throw e; - } - } - - private Properties loadProperties() throws Exception { - Properties props = new Properties(); - String propDir = System.getenv(SDNC_CONFIG_DIR_VAR); - if (propDir == null) - throw new Exception("Cannot find Property file -" + SDNC_CONFIG_DIR_VAR); - String propFile = propDir + FlowControllerConstants.APPC_FLOW_CONTROLLER; - InputStream propStream = new FileInputStream(propFile); - try - { - props.load(propStream); - } - catch (Exception e) - { - throw new Exception("Could not load properties file " + propFile, e); - } - finally - { - try - { - propStream.close(); - } - catch (Exception e) - { - log.warn("Could not close FileInputStream", e); - } - } - // TODO Auto-generated method stub - return props; - } - - public JsonNode isValidJSON(String json) throws IOException { - JsonNode output = null; - log.info("Received response from Interface " + json); - if(json ==null || json.isEmpty()) - return null; - try{ - ObjectMapper objectMapper = new ObjectMapper(); - output = objectMapper.readTree(json); - } catch(JsonProcessingException e){ - log.warn("Response received from interface is not a valid JSON block" + json); - return null; - } - log.info("state is " + output.findValue("state")); - - return output; - } -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/utils/EscapeUtils.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/utils/EscapeUtils.java deleted file mode 100644 index 40bf7593f..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/utils/EscapeUtils.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.utils; - -import org.apache.commons.lang3.StringUtils; - -public class EscapeUtils { - - public EscapeUtils() { - } - - public static String escapeSql(String str) { - if (str == null) { - return null; - } - String searchList[] = new String[]{"'","\\", "\"" }; - String replacementList[] = new String[]{ "''","\\\\" ,"\\\""}; - return StringUtils.replaceEach(str,searchList, replacementList); - } - -} diff --git a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/utils/FlowControllerConstants.java b/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/utils/FlowControllerConstants.java deleted file mode 100644 index 1881e3e45..000000000 --- a/appc-config/appc-flow-controller/provider/src/main/java/org/openecomp/appc/flow/controller/utils/FlowControllerConstants.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.controller.utils; - -public class FlowControllerConstants { - - public static String STRING_ENCODING = "utf-8"; - public static String Y = "Y"; - public static String N = "N"; - public static String DATA_TYPE_TEXT = "TEXT"; - public static String DATA_TYPE_JSON = "JSON"; - public static String DATA_TYPE_XML = "XML"; - public static String DATA_TYPE_SQL = "SQL"; - - public static String INPUT_PARAM_RESPONSE_PRIFIX = "responsePrefix"; - - public static String OUTPUT_PARAM_STATUS = "status"; - public static String OUTPUT_PARAM_ERROR_MESSAGE = "error-message"; - public static String OUTPUT_STATUS_SUCCESS = "success"; - public static String OUTPUT_STATUS_FAILURE = "failure"; - - public static final String DESINGTIME = "DesignTime"; - public static final String RUNTIME = "RunTime"; - public static final String APPC_FLOW_CONTROLLER = "/appc-flow-controller.properties"; - public static final String VNF_TYPE = "vnf-type"; - public static final String ACTION = "action"; - public static final String VNFC_TYPE = "vnfc-type"; - public static final String VM_INSTANCE = "vm-instance"; - public static final String VM = "vm"; - public static final String VNFC = "vnfc"; - public static final String REFERENCE = "reference"; - public static final String VNFC_INSTANCE = "vnfc-instance"; - public static final String DEVICE_PROTOCOL = "device-protocol"; - public static final String DG_RPC = "dg-rpc"; - public static final String MODULE = "module"; - public static final String USER_NAME = "user-name"; - public static final String PORT_NUMBER = "port-number"; - public static final String DOWNLOAD_DG_REFERENCE = "download-dg-reference"; - public static final String REQUEST_ACTION = "request-action"; - public static final String VNF = "vnf"; - public static final String EXTERNAL = "External"; - public static final String ACTION_LEVEL = "action-level"; - public static final String ARTIFACT_NAME = "artifact-name"; - - public static enum endPointType {DG,REST,NODE}; - public static enum flowStatus {PENDING,IN_PROCESS,COMPLETED}; - - public static final String GENERATION_NODE = "GENERATION-NODE"; - public static final String SEQUENCE_TYPE = "SEQUENCE-TYPE"; - public static final String CATEGORY = "CATEGORY"; - public static final String EXECUTION_NODE = "EXECUTION-NODE"; - - - public static final String REQUEST_ID = "reqeust-id"; - public static final String ARTIFACT_CONTENT = "artifact-content"; - public static final String ARTIFACT_CONTENT_ESCAPED = "artifact-content-escaped"; - public static final String FLOW_SEQUENCE = "flow-sequence"; - public static final String EXECUTTION_MODULE = "execution-module"; - public static final String EXECUTION_RPC = "execution-rpc"; - public static final String EXECUTION_TYPE = "execution-type"; - public static final String GRAPH = "graph"; - public static final String NODE = "node"; - public static final String REST = "rest"; - - - public static final String DB_SDC_ARTIFACTS = "ASDC_ARTIFACTS"; - public static final String DB_SDC_REFERENCE = "ASDC_REFERENCE"; - public static final String DB_REQUEST_ARTIFACTS = "REQUEST_ARTIFACTS"; - public static final String DB_MULTISTEP_FLOW_REFERENCE = "MULTISTEP_FLOW_REFERENCE"; - public static final String DB_PROTOCOL_REFERENCE = "PROTOCOL_REFERENCE"; - public static final String DB_PROCESS_FLOW_REFERENCE = "PROCESS_FLOW_REFERENCE"; - public static final String MOCK_HEALTHCHECK = "mock-healthcheck"; - public static final String ACTION_IDENTIFIER = "action-identifier"; - public static final String PAYLOAD = "payload"; - public static final String FAILURE = "failure"; - public static final String SUCCESS = "success"; - public static final String OTHERS = "Others"; - public static final String RESPONSE_PREFIX = "response-prefix"; - public static final String OUTPUT_STATUS_MESSAGE = "status-message"; - public static final String HEALTHY = "healthy"; - public static final String INPUT_URL = "input.url"; - public static final String INPUT_HOST_IP_ADDRESS = "host-ip-address"; - public static final String INPUT_PORT_NUMBER = "port-number"; - public static final String INPUT_CONTEXT = "context"; - public static final String INPUT_SUB_CONTEXT = "sub-context"; - public static final String INPUT_REQUEST_ACTION_TYPE = "request-action-type"; - public static final String INPUT_REQUEST_ACTION = "request-action"; - public static final String HTTP = "http://"; - - public static final String VNF_ID = "vnf-id"; - public static final String VSERVER_ID = "vserver-id"; - public static final String SEQ_GENERATOR_URL = "seq_generator_url"; - public static final String SEQ_GENERATOR_UID = "seq_generator.uid"; - public static final String SEQ_GENERATOR_PWD = "seq_generator.pwd"; - public static final String CAPABILITY ="capability"; - public static final String DEPENDENCYMODEL ="tosca_dependency_model"; - public static final String VF_MODULE ="vf-module"; - public static final String VNFC_NAME = "vnfc-name"; - } diff --git a/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/FlowControlDBServiceTest.java b/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/FlowControlDBServiceTest.java new file mode 100644 index 000000000..4c44e0d86 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/FlowControlDBServiceTest.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.flow.executor.node; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Matchers.anyString; + +import java.util.Map; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.onap.appc.flow.controller.data.Transaction; +import org.onap.appc.flow.controller.dbervices.FlowControlDBService; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; +import org.onap.ccsdk.sli.core.dblib.DbLibService; +import org.onap.ccsdk.sli.adaptors.resource.sql.SqlResource; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; +import org.powermock.modules.junit4.PowerMockRunner; + +@PrepareForTest({ SqlResource.class, SvcLogicResource.class }) +@RunWith(PowerMockRunner.class) +public class FlowControlDBServiceTest { + +@Mock + SvcLogicResource serviceLogic; +@Mock +SqlResource sqlrs; +@Mock +QueryStatus dblibSvc ; + + private static FlowControlDBService dgGeneralDBService = FlowControlDBService.initialise(); + + private Transaction transaction;; + + @Before + public void setUp() throws Exception { + serviceLogic = new SqlResource(); + } + + + /*public final void testGetFlowReferenceData() throws Exception { + + SvcLogicContext localContext = new SvcLogicContext(); + FlowControlDBService dgGeneralDBService = FlowControlDBService.initialise(); + PowerMockito.spy(SqlResource.class); + + Map inParams = null; + //PowerMockito.doReturn(dblibSvc).when(SqlResource.class, "query"); + Whitebox.invokeMethod(SqlResource.class, "query",anyString(), anyBoolean(), anyString(), anyString(), anyString(), anyString(), any(SvcLogicContext.class)); + + dgGeneralDBService.getFlowReferenceData(localContext, inParams, localContext); + //Assert.assertEquals("SUCCESS", status); + //Assert.assertNotEquals("Error - while getting FlowReferenceData", "FAILURE", status); + + }*/ + + @Test(expected=Exception.class) + public final void testGetFlowReferenceData() throws Exception { + + SvcLogicContext localContext = new SvcLogicContext(); + FlowControlDBService dgGeneralDBService = FlowControlDBService.initialise(); + PowerMockito.spy(FlowControlDBService.class); + + + PowerMockito.doReturn(dgGeneralDBService).when(SqlResource.class, "query"); + String status = dgGeneralDBService.getDesignTimeFlowModel(localContext); + Assert.assertEquals("SUCCESS", status); + Assert.assertNotEquals("Error - while getting FlowReferenceData", "FAILURE", status); + + } + + + @Ignore("Test is taking 60 seconds") + @Test(expected=Exception.class) + public final void testGetDesignTimeFlowModel() throws Exception { + SvcLogicContext localContext = new SvcLogicContext(); + String status = dgGeneralDBService.getDesignTimeFlowModel(localContext) ; + Assert.assertEquals("SUCCESS", status); + Assert.assertNotEquals("Error - while getting FlowReferenceData", "FAILURE", status); + + + + + } + + @Ignore("Test is taking 60 seconds") + @Test(expected=Exception.class) + public final void testLoadSequenceIntoDB() throws SvcLogicException { + + + SvcLogicContext localContext = new SvcLogicContext(); + QueryStatus status = dgGeneralDBService.loadSequenceIntoDB(localContext) ; + Assert.assertEquals("SUCCESS", status); + Assert.assertNotEquals("Error - while getting FlowReferenceData", "FAILURE", status); + /*SvcLogicContext ctx = new SvcLogicContext(); + + if (serviceLogic != null && localContext != null) { + String queryString = "INSERT INTO " + FlowControllerConstants.DB_REQUEST_ARTIFACTS + + " set request_id = ' kusuma_test' , action = 'Configure', action_level = 'VNF' , vnf_type = 'vComp' , category = 'config_Template' , artifact_content = '', updated_date = sysdate() "; + Mockito.when(serviceLogic.save("SQL", false, false, queryString, null, null, localContext)) + .thenReturn(status); + Assert.assertEquals("SUCCESS", status); + Assert.assertNotEquals("Error - while getting FlowReferenceData", "FAILURE", status);*/ + + + + } + + @Test(expected=Exception.class) + public final void testPopulateModuleAndRPC() throws SvcLogicException { + SvcLogicContext localContext = new SvcLogicContext(); + SvcLogicContext ctx = new SvcLogicContext(); + String vnf_type = "test"; + dgGeneralDBService.populateModuleAndRPC(transaction, vnf_type);; + + + } + + @Ignore("Test is taking 60 seconds") + @Test(expected=Exception.class) + public final void testGetDependencyInfo() throws SvcLogicException { + SvcLogicContext localContext = new SvcLogicContext(); + String status = dgGeneralDBService.getDependencyInfo(localContext); + Assert.assertEquals("SUCCESS", status); + Assert.assertNotEquals("Error - while getting FlowReferenceData", "FAILURE", status); + + } + + @Ignore("Test is taking 60 seconds") + @Test(expected=Exception.class) + public final void testGetCapabilitiesData() throws SvcLogicException { + SvcLogicContext localContext = new SvcLogicContext(); + String status = dgGeneralDBService.getCapabilitiesData(localContext); + Assert.assertEquals("SUCCESS", status); + Assert.assertNotEquals("Error - while getting FlowReferenceData", "FAILURE", status); + + } + +} diff --git a/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/FlowControlNodeTest.java b/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/FlowControlNodeTest.java new file mode 100644 index 000000000..f29628dcc --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/FlowControlNodeTest.java @@ -0,0 +1,165 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.executor.node; + +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; + +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.appc.flow.controller.data.Transaction; +import org.onap.appc.flow.controller.data.Transactions; +import org.onap.appc.flow.controller.dbervices.FlowControlDBService; +import org.onap.appc.flow.controller.node.FlowControlNode; +import org.onap.appc.flow.controller.utils.FlowControllerConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.reflect.Whitebox; + +public class FlowControlNodeTest { + @Mock + FlowControlDBService dbservice = FlowControlDBService.initialise(); + @Mock + FlowControlNode f = new FlowControlNode(); + + Properties props = new Properties(); + private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; + @Before + public void setUp() throws Exception + + { + FlowControlDBService dbservice = FlowControlDBService.initialise(); + } + @Ignore("Test is taking 60 seconds") + @Test(expected=Exception.class) + public final void testProcessFlow() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + + ctx.setAttribute("request-id","test"); + ctx.setAttribute("vnf-type","test"); + ctx.setAttribute("action-level","HealthCheck"); + ctx.setAttribute("request-action","HealthCheck"); + ctx.setAttribute("response-prefix","response-prefix"); + + Map inParams = new HashMap(); + inParams.put("responsePrefix", "responsePrefix"); + + + Whitebox.invokeMethod(f, "processFlow",inParams, ctx); + /*Properties props = new Properties(); + PowerMockito.spy(FlowControlNode.class); + Transactions trans =null; + HashMap transactionMap = null; + String artifact_content="{‘PlaybookName’:’service_start’,‘EnvParameters’:{‘vnf_instance’:’$vnf_instance’},’Timeout’:600}"; + String capabilitiesData = "SUCCESS"; + System.out.println("End Test when");*/ + + + } + @Test + public void testgetInventoryInfo() throws Exception + { + SvcLogicContext ctx = new SvcLogicContext(); + String vnfid = "test"; + ctx.setAttribute( " tmp.vnfInfo.vnf.vnf-name","test"); + ctx.setAttribute("tmp.vnfInfo.vm-count", "0"); + ctx.setAttribute( " tmp.vnfInfo.vnf.vnf-type","test"); + ctx.setAttribute( "tmp.vnfInfo.vm[0 ].vserverId","test" ); + ctx.setAttribute( "tmp.vnfInfo.vm[0 ].vnfc-name","test" ); + ctx.setAttribute( "tmp.vnfInfo.vm[0].vnfc-type","test" ); + ctx.setAttribute( " tmp.vnfInfo.vm[0].vnfc-count","1"); + + Whitebox.invokeMethod(f, "getInventoryInfo", ctx, vnfid); + + } + @Ignore("Test is taking 60 seconds") + @Test(expected=Exception.class) + public void testprocessFlowSequence() throws Exception + { + Map inparams = new HashMap(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute( " SEQUENCE-TYPE","test"); + ctx.setAttribute("flow-sequence", "1"); + ctx.setAttribute( "DesignTime","test"); + ctx.setAttribute( "vnf-type","test" ); + + Whitebox.invokeMethod(f, "processFlowSequence",inparams, ctx, ctx); + + } + @Test + public void testexeuteAllTransaction() throws Exception + { + Map transactionMap = new HashMap(); + SvcLogicContext ctx = new SvcLogicContext(); + Whitebox.invokeMethod(f, "exeuteAllTransaction",transactionMap, ctx); + + } + @Test + public void testexeutepreProcessor() throws Exception + { + Map transactionMap = new HashMap(); + Transaction transaction = new Transaction(); + Whitebox.invokeMethod(f, "preProcessor",transactionMap, transaction); + + } + @Test(expected=Exception.class) + public void testcollectInputParams() throws Exception + { + SvcLogicContext ctx = new SvcLogicContext(); + + Transaction transaction = new Transaction(); + Whitebox.invokeMethod(f, "collectInputParams",ctx, transaction); + + } + @Ignore("Test is taking 60 seconds") + @Test(expected=Exception.class) + public void testgetDependencyInfo() throws Exception + { + SvcLogicContext ctx = new SvcLogicContext(); + Whitebox.invokeMethod(f, "getDependencyInfo",ctx); + + } + public void testgetCapabilitesDatass() throws Exception + { + SvcLogicContext ctx = new SvcLogicContext(); + Whitebox.invokeMethod(f, "getDependencyInfo",ctx); + + } + + +} diff --git a/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/RestExecutorTest.java b/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/RestExecutorTest.java new file mode 100644 index 000000000..11ddbe024 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/RestExecutorTest.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.flow.executor.node; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.net.URI; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; + +import javax.net.ssl.SSLContext; +import javax.ws.rs.core.MediaType; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.appc.flow.controller.executorImpl.RestExecutor; +import org.powermock.api.mockito.PowerMockito; + +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.config.DefaultClientConfig; +import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; + +public class RestExecutorTest { + + + private static final String URL = null; + + @Mock + private DefaultClientConfig clientConfig; + + @Mock + private com.sun.jersey.api.client.WebResource webResource; + + @InjectMocks + private Client client; + @Mock + private ClientResponse res; + @Mock + URI resourceUri; +@Mock +RestExecutor restEx; + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + clientConfig = Mockito.mock(DefaultClientConfig.class); + Client mockClient = Client.create(); + client = Client.create(clientConfig); + doReturn(mockClient).when(client).create(); + webResource= mockClient.resource(URL); + doReturn(webResource).when(mockClient).resource(URL); + when(webResource.get((Class) any())).thenReturn("OK") ; + } + + @After + public void tearDown() throws Exception { + } + + + + + +} diff --git a/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/TestFlowExecutorNode.java b/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/TestFlowExecutorNode.java new file mode 100644 index 000000000..3fe545334 --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/TestFlowExecutorNode.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.executor.node; + +import java.io.InputStream; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Properties; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.appc.flow.controller.node.FlowControlNode; +import org.onap.appc.flow.controller.utils.FlowControllerConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TestFlowExecutorNode { + + private final Logger logger = LoggerFactory.getLogger(TestFlowExecutorNode.class); + + + //@Before + public void setUp() { + Properties props = new Properties(); + InputStream propStr = getClass().getResourceAsStream("/svclogic.properties"); + if (propStr == null) { + } + try { + props.load(propStr); + propStr.close(); + } catch (Exception e) { + e.printStackTrace(); + } + // Add properties to global properties + + Enumeration propNames = props.keys(); + + while (propNames.hasMoreElements()) { + + String propName = (String) propNames.nextElement(); + System.setProperty(propName, props.getProperty(propName)); + } + + } + + @Ignore("Test is taking 60 seconds") + @Test(expected=Exception.class) + public void testFlowExecutorNode() throws Exception { + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute(FlowControllerConstants.VNF_TYPE, "vUSP - vDBE-IPX HUB"); + ctx.setAttribute(FlowControllerConstants.REQUEST_ACTION, "Configure"); + ctx.setAttribute(FlowControllerConstants.VNFC_TYPE, "");; + ctx.setAttribute(FlowControllerConstants.REQUEST_ID,"TESTCOMMONFRMWK"); + HashMap inParams = new HashMap(); + FlowControlNode fen = new FlowControlNode(); + fen.processFlow(inParams, ctx); + } +} diff --git a/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/TestParsingNode.java b/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/TestParsingNode.java new file mode 100644 index 000000000..ca84ca56a --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/TestParsingNode.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.executor.node; + +import java.io.InputStream; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.flow.controller.node.FlowControlNode; +import org.onap.appc.flow.controller.node.JsonParsingNode; +import org.onap.appc.flow.controller.node.RestServiceNode; +import org.onap.appc.flow.controller.utils.FlowControllerConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class TestParsingNode { + + @Test + public void testRestServiceNode() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + HashMap inParams = new HashMap(); + JsonParsingNode rsn = new JsonParsingNode(); + inParams.put("data", "{\"identifier\": \"scope represented\",\"state\": \"healthy\",\"test\": \"passed\", \"time\": \"01-01-1000:0000\"}"); + inParams.put("responsePrefix", "APPC.healthcheck"); + rsn.parse(inParams, ctx); + for (Object key : ctx.getAttributeKeySet()) { + String parmName = (String) key; + String parmValue = ctx.getAttribute(parmName); + } + + } +} diff --git a/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/TestRestServiceNode.java b/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/TestRestServiceNode.java new file mode 100644 index 000000000..ef661e3db --- /dev/null +++ b/appc-config/appc-flow-controller/provider/src/test/java/org/onap/appc/flow/executor/node/TestRestServiceNode.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.flow.executor.node; + +import java.io.InputStream; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.flow.controller.data.Transaction; +import org.onap.appc.flow.controller.executorImpl.RestExecutor; +import org.onap.appc.flow.controller.interfaceData.ActionIdentifier; +import org.onap.appc.flow.controller.interfaceData.InventoryInfo; +import org.onap.appc.flow.controller.interfaceData.RequestInfo; +import org.onap.appc.flow.controller.interfaceData.Vm; +import org.onap.appc.flow.controller.interfaceData.VnfInfo; +import org.onap.appc.flow.controller.interfaceData.Vnfcslist; +import org.onap.appc.flow.controller.node.FlowControlNode; +import org.onap.appc.flow.controller.node.RestServiceNode; +import org.onap.appc.flow.controller.utils.FlowControllerConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class TestRestServiceNode { + + @Test(expected=Exception.class) + public void testRestServiceNode() throws Exception { + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute(FlowControllerConstants.VNF_TYPE, "vUSP - vDBE-IPX HUB"); + ctx.setAttribute(FlowControllerConstants.REQUEST_ACTION, "healthcheck"); + ctx.setAttribute(FlowControllerConstants.VNFC_TYPE, "TESTVNFC-CF"); + ctx.setAttribute(FlowControllerConstants.REQUEST_ID,"TESTCOMMONFRMWK"); + ctx.setAttribute("host-ip-address","127.0.0.1"); + ctx.setAttribute("port-number","8888"); + ctx.setAttribute("request-action-type","GET"); + ctx.setAttribute("context", "loader/restconf/operations/appc-provider-lcm:health-check"); + + HashMap inParams = new HashMap(); + RestServiceNode rsn = new RestServiceNode(); + inParams.put("output-state", "state"); + inParams.put("responsePrefix", "healthcheck"); + rsn.sendRequest(inParams, ctx); + + for (Object key : ctx.getAttributeKeySet()) { + String parmName = (String) key; + String parmValue = ctx.getAttribute(parmName); + } + + + } + + + @Test(expected=Exception.class) + public void testInputParamsRestServiceNode() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("vnf-id", "test"); + ctx.setAttribute("tmp.vnfInfo.vm-count", "1"); + ctx.setAttribute("tmp.vnfInfo.vm[0].vnfc-count", "1"); + RestExecutor restExe = new RestExecutor(); + Transaction transaction = new Transaction(); + + FlowControlNode node = new FlowControlNode(); + HashMapflowSeq= restExe.execute(transaction, ctx); + String flowSequnce=flowSeq.get("restResponse"); + + } +} diff --git a/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/FlowControlDBServiceTest.java b/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/FlowControlDBServiceTest.java deleted file mode 100644 index 4c44e0d86..000000000 --- a/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/FlowControlDBServiceTest.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.flow.executor.node; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyString; - -import java.util.Map; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.onap.appc.flow.controller.data.Transaction; -import org.onap.appc.flow.controller.dbervices.FlowControlDBService; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; -import org.onap.ccsdk.sli.core.dblib.DbLibService; -import org.onap.ccsdk.sli.adaptors.resource.sql.SqlResource; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; -import org.powermock.modules.junit4.PowerMockRunner; - -@PrepareForTest({ SqlResource.class, SvcLogicResource.class }) -@RunWith(PowerMockRunner.class) -public class FlowControlDBServiceTest { - -@Mock - SvcLogicResource serviceLogic; -@Mock -SqlResource sqlrs; -@Mock -QueryStatus dblibSvc ; - - private static FlowControlDBService dgGeneralDBService = FlowControlDBService.initialise(); - - private Transaction transaction;; - - @Before - public void setUp() throws Exception { - serviceLogic = new SqlResource(); - } - - - /*public final void testGetFlowReferenceData() throws Exception { - - SvcLogicContext localContext = new SvcLogicContext(); - FlowControlDBService dgGeneralDBService = FlowControlDBService.initialise(); - PowerMockito.spy(SqlResource.class); - - Map inParams = null; - //PowerMockito.doReturn(dblibSvc).when(SqlResource.class, "query"); - Whitebox.invokeMethod(SqlResource.class, "query",anyString(), anyBoolean(), anyString(), anyString(), anyString(), anyString(), any(SvcLogicContext.class)); - - dgGeneralDBService.getFlowReferenceData(localContext, inParams, localContext); - //Assert.assertEquals("SUCCESS", status); - //Assert.assertNotEquals("Error - while getting FlowReferenceData", "FAILURE", status); - - }*/ - - @Test(expected=Exception.class) - public final void testGetFlowReferenceData() throws Exception { - - SvcLogicContext localContext = new SvcLogicContext(); - FlowControlDBService dgGeneralDBService = FlowControlDBService.initialise(); - PowerMockito.spy(FlowControlDBService.class); - - - PowerMockito.doReturn(dgGeneralDBService).when(SqlResource.class, "query"); - String status = dgGeneralDBService.getDesignTimeFlowModel(localContext); - Assert.assertEquals("SUCCESS", status); - Assert.assertNotEquals("Error - while getting FlowReferenceData", "FAILURE", status); - - } - - - @Ignore("Test is taking 60 seconds") - @Test(expected=Exception.class) - public final void testGetDesignTimeFlowModel() throws Exception { - SvcLogicContext localContext = new SvcLogicContext(); - String status = dgGeneralDBService.getDesignTimeFlowModel(localContext) ; - Assert.assertEquals("SUCCESS", status); - Assert.assertNotEquals("Error - while getting FlowReferenceData", "FAILURE", status); - - - - - } - - @Ignore("Test is taking 60 seconds") - @Test(expected=Exception.class) - public final void testLoadSequenceIntoDB() throws SvcLogicException { - - - SvcLogicContext localContext = new SvcLogicContext(); - QueryStatus status = dgGeneralDBService.loadSequenceIntoDB(localContext) ; - Assert.assertEquals("SUCCESS", status); - Assert.assertNotEquals("Error - while getting FlowReferenceData", "FAILURE", status); - /*SvcLogicContext ctx = new SvcLogicContext(); - - if (serviceLogic != null && localContext != null) { - String queryString = "INSERT INTO " + FlowControllerConstants.DB_REQUEST_ARTIFACTS - + " set request_id = ' kusuma_test' , action = 'Configure', action_level = 'VNF' , vnf_type = 'vComp' , category = 'config_Template' , artifact_content = '', updated_date = sysdate() "; - Mockito.when(serviceLogic.save("SQL", false, false, queryString, null, null, localContext)) - .thenReturn(status); - Assert.assertEquals("SUCCESS", status); - Assert.assertNotEquals("Error - while getting FlowReferenceData", "FAILURE", status);*/ - - - - } - - @Test(expected=Exception.class) - public final void testPopulateModuleAndRPC() throws SvcLogicException { - SvcLogicContext localContext = new SvcLogicContext(); - SvcLogicContext ctx = new SvcLogicContext(); - String vnf_type = "test"; - dgGeneralDBService.populateModuleAndRPC(transaction, vnf_type);; - - - } - - @Ignore("Test is taking 60 seconds") - @Test(expected=Exception.class) - public final void testGetDependencyInfo() throws SvcLogicException { - SvcLogicContext localContext = new SvcLogicContext(); - String status = dgGeneralDBService.getDependencyInfo(localContext); - Assert.assertEquals("SUCCESS", status); - Assert.assertNotEquals("Error - while getting FlowReferenceData", "FAILURE", status); - - } - - @Ignore("Test is taking 60 seconds") - @Test(expected=Exception.class) - public final void testGetCapabilitiesData() throws SvcLogicException { - SvcLogicContext localContext = new SvcLogicContext(); - String status = dgGeneralDBService.getCapabilitiesData(localContext); - Assert.assertEquals("SUCCESS", status); - Assert.assertNotEquals("Error - while getting FlowReferenceData", "FAILURE", status); - - } - -} diff --git a/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/FlowControlNodeTest.java b/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/FlowControlNodeTest.java deleted file mode 100644 index f29628dcc..000000000 --- a/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/FlowControlNodeTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.executor.node; - -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.verify; - -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.appc.flow.controller.data.Transaction; -import org.onap.appc.flow.controller.data.Transactions; -import org.onap.appc.flow.controller.dbervices.FlowControlDBService; -import org.onap.appc.flow.controller.node.FlowControlNode; -import org.onap.appc.flow.controller.utils.FlowControllerConstants; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.reflect.Whitebox; - -public class FlowControlNodeTest { - @Mock - FlowControlDBService dbservice = FlowControlDBService.initialise(); - @Mock - FlowControlNode f = new FlowControlNode(); - - Properties props = new Properties(); - private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; - @Before - public void setUp() throws Exception - - { - FlowControlDBService dbservice = FlowControlDBService.initialise(); - } - @Ignore("Test is taking 60 seconds") - @Test(expected=Exception.class) - public final void testProcessFlow() throws Exception { - SvcLogicContext ctx = new SvcLogicContext(); - - ctx.setAttribute("request-id","test"); - ctx.setAttribute("vnf-type","test"); - ctx.setAttribute("action-level","HealthCheck"); - ctx.setAttribute("request-action","HealthCheck"); - ctx.setAttribute("response-prefix","response-prefix"); - - Map inParams = new HashMap(); - inParams.put("responsePrefix", "responsePrefix"); - - - Whitebox.invokeMethod(f, "processFlow",inParams, ctx); - /*Properties props = new Properties(); - PowerMockito.spy(FlowControlNode.class); - Transactions trans =null; - HashMap transactionMap = null; - String artifact_content="{‘PlaybookName’:’service_start’,‘EnvParameters’:{‘vnf_instance’:’$vnf_instance’},’Timeout’:600}"; - String capabilitiesData = "SUCCESS"; - System.out.println("End Test when");*/ - - - } - @Test - public void testgetInventoryInfo() throws Exception - { - SvcLogicContext ctx = new SvcLogicContext(); - String vnfid = "test"; - ctx.setAttribute( " tmp.vnfInfo.vnf.vnf-name","test"); - ctx.setAttribute("tmp.vnfInfo.vm-count", "0"); - ctx.setAttribute( " tmp.vnfInfo.vnf.vnf-type","test"); - ctx.setAttribute( "tmp.vnfInfo.vm[0 ].vserverId","test" ); - ctx.setAttribute( "tmp.vnfInfo.vm[0 ].vnfc-name","test" ); - ctx.setAttribute( "tmp.vnfInfo.vm[0].vnfc-type","test" ); - ctx.setAttribute( " tmp.vnfInfo.vm[0].vnfc-count","1"); - - Whitebox.invokeMethod(f, "getInventoryInfo", ctx, vnfid); - - } - @Ignore("Test is taking 60 seconds") - @Test(expected=Exception.class) - public void testprocessFlowSequence() throws Exception - { - Map inparams = new HashMap(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute( " SEQUENCE-TYPE","test"); - ctx.setAttribute("flow-sequence", "1"); - ctx.setAttribute( "DesignTime","test"); - ctx.setAttribute( "vnf-type","test" ); - - Whitebox.invokeMethod(f, "processFlowSequence",inparams, ctx, ctx); - - } - @Test - public void testexeuteAllTransaction() throws Exception - { - Map transactionMap = new HashMap(); - SvcLogicContext ctx = new SvcLogicContext(); - Whitebox.invokeMethod(f, "exeuteAllTransaction",transactionMap, ctx); - - } - @Test - public void testexeutepreProcessor() throws Exception - { - Map transactionMap = new HashMap(); - Transaction transaction = new Transaction(); - Whitebox.invokeMethod(f, "preProcessor",transactionMap, transaction); - - } - @Test(expected=Exception.class) - public void testcollectInputParams() throws Exception - { - SvcLogicContext ctx = new SvcLogicContext(); - - Transaction transaction = new Transaction(); - Whitebox.invokeMethod(f, "collectInputParams",ctx, transaction); - - } - @Ignore("Test is taking 60 seconds") - @Test(expected=Exception.class) - public void testgetDependencyInfo() throws Exception - { - SvcLogicContext ctx = new SvcLogicContext(); - Whitebox.invokeMethod(f, "getDependencyInfo",ctx); - - } - public void testgetCapabilitesDatass() throws Exception - { - SvcLogicContext ctx = new SvcLogicContext(); - Whitebox.invokeMethod(f, "getDependencyInfo",ctx); - - } - - -} diff --git a/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/RestExecutorTest.java b/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/RestExecutorTest.java deleted file mode 100644 index 11ddbe024..000000000 --- a/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/RestExecutorTest.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.flow.executor.node; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.net.URI; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; - -import javax.net.ssl.SSLContext; -import javax.ws.rs.core.MediaType; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.appc.flow.controller.executorImpl.RestExecutor; -import org.powermock.api.mockito.PowerMockito; - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; - -public class RestExecutorTest { - - - private static final String URL = null; - - @Mock - private DefaultClientConfig clientConfig; - - @Mock - private com.sun.jersey.api.client.WebResource webResource; - - @InjectMocks - private Client client; - @Mock - private ClientResponse res; - @Mock - URI resourceUri; -@Mock -RestExecutor restEx; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - clientConfig = Mockito.mock(DefaultClientConfig.class); - Client mockClient = Client.create(); - client = Client.create(clientConfig); - doReturn(mockClient).when(client).create(); - webResource= mockClient.resource(URL); - doReturn(webResource).when(mockClient).resource(URL); - when(webResource.get((Class) any())).thenReturn("OK") ; - } - - @After - public void tearDown() throws Exception { - } - - - - - -} diff --git a/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/TestFlowExecutorNode.java b/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/TestFlowExecutorNode.java deleted file mode 100644 index 3fe545334..000000000 --- a/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/TestFlowExecutorNode.java +++ /dev/null @@ -1,79 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.executor.node; - -import java.io.InputStream; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Properties; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.appc.flow.controller.node.FlowControlNode; -import org.onap.appc.flow.controller.utils.FlowControllerConstants; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class TestFlowExecutorNode { - - private final Logger logger = LoggerFactory.getLogger(TestFlowExecutorNode.class); - - - //@Before - public void setUp() { - Properties props = new Properties(); - InputStream propStr = getClass().getResourceAsStream("/svclogic.properties"); - if (propStr == null) { - } - try { - props.load(propStr); - propStr.close(); - } catch (Exception e) { - e.printStackTrace(); - } - // Add properties to global properties - - Enumeration propNames = props.keys(); - - while (propNames.hasMoreElements()) { - - String propName = (String) propNames.nextElement(); - System.setProperty(propName, props.getProperty(propName)); - } - - } - - @Ignore("Test is taking 60 seconds") - @Test(expected=Exception.class) - public void testFlowExecutorNode() throws Exception { - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute(FlowControllerConstants.VNF_TYPE, "vUSP - vDBE-IPX HUB"); - ctx.setAttribute(FlowControllerConstants.REQUEST_ACTION, "Configure"); - ctx.setAttribute(FlowControllerConstants.VNFC_TYPE, "");; - ctx.setAttribute(FlowControllerConstants.REQUEST_ID,"TESTCOMMONFRMWK"); - HashMap inParams = new HashMap(); - FlowControlNode fen = new FlowControlNode(); - fen.processFlow(inParams, ctx); - } -} diff --git a/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/TestParsingNode.java b/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/TestParsingNode.java deleted file mode 100644 index ca84ca56a..000000000 --- a/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/TestParsingNode.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.executor.node; - -import java.io.InputStream; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Properties; - -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.flow.controller.node.FlowControlNode; -import org.onap.appc.flow.controller.node.JsonParsingNode; -import org.onap.appc.flow.controller.node.RestServiceNode; -import org.onap.appc.flow.controller.utils.FlowControllerConstants; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class TestParsingNode { - - @Test - public void testRestServiceNode() throws Exception { - SvcLogicContext ctx = new SvcLogicContext(); - HashMap inParams = new HashMap(); - JsonParsingNode rsn = new JsonParsingNode(); - inParams.put("data", "{\"identifier\": \"scope represented\",\"state\": \"healthy\",\"test\": \"passed\", \"time\": \"01-01-1000:0000\"}"); - inParams.put("responsePrefix", "APPC.healthcheck"); - rsn.parse(inParams, ctx); - for (Object key : ctx.getAttributeKeySet()) { - String parmName = (String) key; - String parmValue = ctx.getAttribute(parmName); - } - - } -} diff --git a/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/TestRestServiceNode.java b/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/TestRestServiceNode.java deleted file mode 100644 index ef661e3db..000000000 --- a/appc-config/appc-flow-controller/provider/src/test/java/org/openecomp/appc/flow/executor/node/TestRestServiceNode.java +++ /dev/null @@ -1,87 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.flow.executor.node; - -import java.io.InputStream; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Properties; - -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.flow.controller.data.Transaction; -import org.onap.appc.flow.controller.executorImpl.RestExecutor; -import org.onap.appc.flow.controller.interfaceData.ActionIdentifier; -import org.onap.appc.flow.controller.interfaceData.InventoryInfo; -import org.onap.appc.flow.controller.interfaceData.RequestInfo; -import org.onap.appc.flow.controller.interfaceData.Vm; -import org.onap.appc.flow.controller.interfaceData.VnfInfo; -import org.onap.appc.flow.controller.interfaceData.Vnfcslist; -import org.onap.appc.flow.controller.node.FlowControlNode; -import org.onap.appc.flow.controller.node.RestServiceNode; -import org.onap.appc.flow.controller.utils.FlowControllerConstants; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class TestRestServiceNode { - - @Test(expected=Exception.class) - public void testRestServiceNode() throws Exception { - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute(FlowControllerConstants.VNF_TYPE, "vUSP - vDBE-IPX HUB"); - ctx.setAttribute(FlowControllerConstants.REQUEST_ACTION, "healthcheck"); - ctx.setAttribute(FlowControllerConstants.VNFC_TYPE, "TESTVNFC-CF"); - ctx.setAttribute(FlowControllerConstants.REQUEST_ID,"TESTCOMMONFRMWK"); - ctx.setAttribute("host-ip-address","127.0.0.1"); - ctx.setAttribute("port-number","8888"); - ctx.setAttribute("request-action-type","GET"); - ctx.setAttribute("context", "loader/restconf/operations/appc-provider-lcm:health-check"); - - HashMap inParams = new HashMap(); - RestServiceNode rsn = new RestServiceNode(); - inParams.put("output-state", "state"); - inParams.put("responsePrefix", "healthcheck"); - rsn.sendRequest(inParams, ctx); - - for (Object key : ctx.getAttributeKeySet()) { - String parmName = (String) key; - String parmValue = ctx.getAttribute(parmName); - } - - - } - - - @Test(expected=Exception.class) - public void testInputParamsRestServiceNode() throws Exception { - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("vnf-id", "test"); - ctx.setAttribute("tmp.vnfInfo.vm-count", "1"); - ctx.setAttribute("tmp.vnfInfo.vm[0].vnfc-count", "1"); - RestExecutor restExe = new RestExecutor(); - Transaction transaction = new Transaction(); - - FlowControlNode node = new FlowControlNode(); - HashMapflowSeq= restExe.execute(transaction, ctx); - String flowSequnce=flowSeq.get("restResponse"); - - } -} -- cgit 1.2.3-korg