From e8d8a37da95c6fea435e0b3e93a477b5aa45b9b1 Mon Sep 17 00:00:00 2001 From: Yuli Shlosberg Date: Wed, 7 Mar 2018 16:29:57 +0200 Subject: update distribution-client package names Change-Id: Ic6f81bc8fdd3b021033c7c68e44f876a6ee1d21a Issue-ID: SDC-952 Signed-off-by: Yuli Shlosberg --- README.md | 10 +- pom.xml | 6 +- sdc-distribution-ci/log4j.properties | 2 +- sdc-distribution-ci/pom.xml | 12 +- .../main/java/org/onap/test/AdvanceCallBack.java | 70 ++ .../main/java/org/onap/test/ArtifactTypeEnum.java | 111 +++ .../src/main/java/org/onap/test/ClientTest.java | 113 +++ .../main/java/org/onap/test/CsarToscaTester.java | 121 ++++ .../src/main/java/org/onap/test/Decoder.java | 58 ++ .../java/org/onap/test/NotificationCallback.java | 39 ++ .../main/java/org/onap/test/SimpleCallback.java | 356 ++++++++++ .../java/org/onap/test/SimpleConfiguration.java | 204 ++++++ .../java/org/openecomp/test/AdvanceCallBack.java | 70 -- .../java/org/openecomp/test/ArtifactTypeEnum.java | 111 --- .../main/java/org/openecomp/test/ClientTest.java | 113 --- .../java/org/openecomp/test/CsarToscaTester.java | 121 ---- .../src/main/java/org/openecomp/test/Decoder.java | 58 -- .../org/openecomp/test/NotificationCallback.java | 39 -- .../java/org/openecomp/test/SimpleCallback.java | 356 ---------- .../org/openecomp/test/SimpleConfiguration.java | 204 ------ .../main/resources/ci/conf/attsdc-packages.yaml | 18 +- .../src/main/resources/ci/conf/log4j.properties | 4 +- .../src/main/resources/ci/scripts/startTest.sh | 2 +- .../ClientDownloadArtifact.java | 511 ++++++++++++++ .../ClientDownloadArtifact.java | 511 -------------- sdc-distribution-client/pom.xml | 4 +- .../java/org/onap/sdc/api/IDistributionClient.java | 210 ++++++ .../api/IDistributionStatusMessageJsonBuilder.java | 25 + .../org/onap/sdc/api/asdc/RegistrationRequest.java | 56 ++ .../org/onap/sdc/api/asdc/ServerListResponse.java | 36 + .../api/consumer/IComponentDoneStatusMessage.java | 7 + .../org/onap/sdc/api/consumer/IConfiguration.java | 157 +++++ .../api/consumer/IDistributionStatusMessage.java | 28 + .../consumer/IDistributionStatusMessageBasic.java | 28 + .../sdc/api/consumer/IFinalDistrStatusMessage.java | 9 + .../sdc/api/consumer/INotificationCallback.java | 29 + .../org/onap/sdc/api/consumer/IStatusCallback.java | 35 + .../onap/sdc/api/notification/IArtifactInfo.java | 104 +++ .../sdc/api/notification/INotificationData.java | 71 ++ .../sdc/api/notification/IResourceInstance.java | 65 ++ .../org/onap/sdc/api/notification/IStatusData.java | 65 ++ .../sdc/api/notification/IVfModuleMetadata.java | 63 ++ .../results/IDistributionClientDownloadResult.java | 45 ++ .../sdc/api/results/IDistributionClientResult.java | 28 + .../src/main/java/org/onap/sdc/http/AsdcUrls.java | 30 + .../java/org/onap/sdc/http/HttpAsdcClient.java | 351 ++++++++++ .../java/org/onap/sdc/http/HttpAsdcResponse.java | 71 ++ .../java/org/onap/sdc/http/IHttpAsdcClient.java | 33 + .../java/org/onap/sdc/http/SdcConnectorClient.java | 398 +++++++++++ .../onap/sdc/http/TopicRegistrationResponse.java | 41 ++ .../java/org/onap/sdc/impl/ArtifactInfoImpl.java | 192 +++++ .../main/java/org/onap/sdc/impl/Configuration.java | 225 ++++++ .../impl/DistributionClientDownloadResultImpl.java | 74 ++ .../onap/sdc/impl/DistributionClientFactory.java | 34 + .../org/onap/sdc/impl/DistributionClientImpl.java | 779 +++++++++++++++++++++ .../sdc/impl/DistributionClientResultImpl.java | 50 ++ .../sdc/impl/DistributionStatusMessageImpl.java | 113 +++ ...istributionStatusMessageJsonBuilderFactory.java | 148 ++++ .../sdc/impl/JsonContainerResourceInstance.java | 158 +++++ .../org/onap/sdc/impl/NotificationConsumer.java | 181 +++++ .../org/onap/sdc/impl/NotificationDataImpl.java | 179 +++++ .../java/org/onap/sdc/impl/StatusConsumer.java | 66 ++ .../java/org/onap/sdc/impl/StatusDataImpl.java | 95 +++ .../java/org/onap/sdc/impl/VfModuleMetadata.java | 61 ++ .../DistributionClientDownloadResultStubImpl.java | 78 +++ .../mock/DistributionClientResultStubImpl.java | 37 + .../sdc/impl/mock/DistributionClientStubImpl.java | 127 ++++ .../java/org/onap/sdc/utils/ArtifactTypeEnum.java | 46 ++ .../sdc/utils/DistributionActionResultEnum.java | 58 ++ .../sdc/utils/DistributionClientConstants.java | 44 ++ .../org/onap/sdc/utils/DistributionStatusEnum.java | 56 ++ .../main/java/org/onap/sdc/utils/GeneralUtils.java | 92 +++ .../src/main/java/org/onap/sdc/utils/Pair.java | 39 ++ .../src/main/java/org/onap/sdc/utils/Wrapper.java | 45 ++ .../org/onap/sdc/utils/YamlToObjectConverter.java | 155 ++++ .../org/onap/sdc/utils/heat/HeatConfiguration.java | 42 ++ .../org/onap/sdc/utils/heat/HeatParameter.java | 207 ++++++ .../sdc/utils/heat/HeatParameterConstraint.java | 93 +++ .../java/org/onap/sdc/utils/heat/HeatParser.java | 75 ++ .../org/openecomp/sdc/api/IDistributionClient.java | 210 ------ .../api/IDistributionStatusMessageJsonBuilder.java | 25 - .../sdc/api/asdc/RegistrationRequest.java | 56 -- .../openecomp/sdc/api/asdc/ServerListResponse.java | 36 - .../api/consumer/IComponentDoneStatusMessage.java | 7 - .../openecomp/sdc/api/consumer/IConfiguration.java | 157 ----- .../api/consumer/IDistributionStatusMessage.java | 28 - .../consumer/IDistributionStatusMessageBasic.java | 28 - .../sdc/api/consumer/IFinalDistrStatusMessage.java | 9 - .../sdc/api/consumer/INotificationCallback.java | 29 - .../sdc/api/consumer/IStatusCallback.java | 35 - .../sdc/api/notification/IArtifactInfo.java | 104 --- .../sdc/api/notification/INotificationData.java | 71 -- .../sdc/api/notification/IResourceInstance.java | 65 -- .../sdc/api/notification/IStatusData.java | 65 -- .../sdc/api/notification/IVfModuleMetadata.java | 63 -- .../results/IDistributionClientDownloadResult.java | 45 -- .../sdc/api/results/IDistributionClientResult.java | 28 - .../main/java/org/openecomp/sdc/http/AsdcUrls.java | 30 - .../org/openecomp/sdc/http/HttpAsdcClient.java | 351 ---------- .../org/openecomp/sdc/http/HttpAsdcResponse.java | 71 -- .../org/openecomp/sdc/http/IHttpAsdcClient.java | 33 - .../org/openecomp/sdc/http/SdcConnectorClient.java | 398 ----------- .../sdc/http/TopicRegistrationResponse.java | 41 -- .../org/openecomp/sdc/impl/ArtifactInfoImpl.java | 192 ----- .../java/org/openecomp/sdc/impl/Configuration.java | 228 ------ .../impl/DistributionClientDownloadResultImpl.java | 74 -- .../sdc/impl/DistributionClientFactory.java | 34 - .../openecomp/sdc/impl/DistributionClientImpl.java | 778 -------------------- .../sdc/impl/DistributionClientResultImpl.java | 50 -- .../sdc/impl/DistributionStatusMessageImpl.java | 113 --- ...istributionStatusMessageJsonBuilderFactory.java | 148 ---- .../sdc/impl/JsonContainerResourceInstance.java | 158 ----- .../openecomp/sdc/impl/NotificationConsumer.java | 181 ----- .../openecomp/sdc/impl/NotificationDataImpl.java | 179 ----- .../org/openecomp/sdc/impl/StatusConsumer.java | 66 -- .../org/openecomp/sdc/impl/StatusDataImpl.java | 95 --- .../org/openecomp/sdc/impl/VfModuleMetadata.java | 61 -- .../DistributionClientDownloadResultStubImpl.java | 78 --- .../mock/DistributionClientResultStubImpl.java | 37 - .../sdc/impl/mock/DistributionClientStubImpl.java | 125 ---- .../org/openecomp/sdc/utils/ArtifactTypeEnum.java | 46 -- .../sdc/utils/DistributionActionResultEnum.java | 58 -- .../sdc/utils/DistributionClientConstants.java | 44 -- .../sdc/utils/DistributionStatusEnum.java | 56 -- .../java/org/openecomp/sdc/utils/GeneralUtils.java | 92 --- .../main/java/org/openecomp/sdc/utils/Pair.java | 39 -- .../main/java/org/openecomp/sdc/utils/Wrapper.java | 45 -- .../openecomp/sdc/utils/YamlToObjectConverter.java | 155 ---- .../sdc/utils/heat/HeatConfiguration.java | 42 -- .../openecomp/sdc/utils/heat/HeatParameter.java | 207 ------ .../sdc/utils/heat/HeatParameterConstraint.java | 93 --- .../org/openecomp/sdc/utils/heat/HeatParser.java | 75 -- .../org/onap/sdc/http/SdcConnectorClientTest.java | 119 ++++ .../impl/DistributionClientDownloadResultTest.java | 55 ++ .../org/onap/sdc/impl/DistributionClientTest.java | 505 +++++++++++++ .../java/org/onap/sdc/impl/HeatParserTest.java | 139 ++++ .../onap/sdc/impl/NotificationConsumerTest.java | 352 ++++++++++ .../java/org/onap/sdc/utils/ArtifactsUtils.java | 46 ++ .../java/org/onap/sdc/utils/TestConfiguration.java | 299 ++++++++ .../onap/sdc/utils/TestNotificationCallback.java | 34 + .../openecomp/sdc/http/SdcConnectorClientTest.java | 119 ---- .../impl/DistributionClientDownloadResultTest.java | 55 -- .../openecomp/sdc/impl/DistributionClientTest.java | 505 ------------- .../org/openecomp/sdc/impl/HeatParserTest.java | 139 ---- .../sdc/impl/NotificationConsumerTest.java | 352 ---------- .../org/openecomp/sdc/utils/ArtifactsUtils.java | 48 -- .../org/openecomp/sdc/utils/TestConfiguration.java | 299 -------- .../sdc/utils/TestNotificationCallback.java | 34 - version.properties | 4 +- 149 files changed, 8697 insertions(+), 8699 deletions(-) create mode 100644 sdc-distribution-ci/src/main/java/org/onap/test/AdvanceCallBack.java create mode 100644 sdc-distribution-ci/src/main/java/org/onap/test/ArtifactTypeEnum.java create mode 100644 sdc-distribution-ci/src/main/java/org/onap/test/ClientTest.java create mode 100644 sdc-distribution-ci/src/main/java/org/onap/test/CsarToscaTester.java create mode 100644 sdc-distribution-ci/src/main/java/org/onap/test/Decoder.java create mode 100644 sdc-distribution-ci/src/main/java/org/onap/test/NotificationCallback.java create mode 100644 sdc-distribution-ci/src/main/java/org/onap/test/SimpleCallback.java create mode 100644 sdc-distribution-ci/src/main/java/org/onap/test/SimpleConfiguration.java delete mode 100644 sdc-distribution-ci/src/main/java/org/openecomp/test/AdvanceCallBack.java delete mode 100644 sdc-distribution-ci/src/main/java/org/openecomp/test/ArtifactTypeEnum.java delete mode 100644 sdc-distribution-ci/src/main/java/org/openecomp/test/ClientTest.java delete mode 100644 sdc-distribution-ci/src/main/java/org/openecomp/test/CsarToscaTester.java delete mode 100644 sdc-distribution-ci/src/main/java/org/openecomp/test/Decoder.java delete mode 100644 sdc-distribution-ci/src/main/java/org/openecomp/test/NotificationCallback.java delete mode 100644 sdc-distribution-ci/src/main/java/org/openecomp/test/SimpleCallback.java delete mode 100644 sdc-distribution-ci/src/main/java/org/openecomp/test/SimpleConfiguration.java create mode 100644 sdc-distribution-ci/src/test/java/org/onap/sdc/ci/tests/execute/downloadArtifactUGN/ClientDownloadArtifact.java delete mode 100644 sdc-distribution-ci/src/test/java/org/openecomp/sdc/ci/tests/execute/downloadArtifactUGN/ClientDownloadArtifact.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/IDistributionClient.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/IDistributionStatusMessageJsonBuilder.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/RegistrationRequest.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/ServerListResponse.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IComponentDoneStatusMessage.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IConfiguration.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IDistributionStatusMessage.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IDistributionStatusMessageBasic.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IFinalDistrStatusMessage.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/INotificationCallback.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IStatusCallback.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IArtifactInfo.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/INotificationData.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IResourceInstance.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IStatusData.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IVfModuleMetadata.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/results/IDistributionClientDownloadResult.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/api/results/IDistributionClientResult.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/http/AsdcUrls.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/http/HttpAsdcClient.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/http/HttpAsdcResponse.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/http/IHttpAsdcClient.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/http/SdcConnectorClient.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/http/TopicRegistrationResponse.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/impl/ArtifactInfoImpl.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/impl/Configuration.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientDownloadResultImpl.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientFactory.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientImpl.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientResultImpl.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionStatusMessageImpl.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionStatusMessageJsonBuilderFactory.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/impl/JsonContainerResourceInstance.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/impl/NotificationConsumer.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/impl/NotificationDataImpl.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusConsumer.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusDataImpl.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/impl/VfModuleMetadata.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientDownloadResultStubImpl.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientResultStubImpl.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientStubImpl.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/utils/ArtifactTypeEnum.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionActionResultEnum.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionClientConstants.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionStatusEnum.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/utils/GeneralUtils.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/utils/Pair.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/utils/Wrapper.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/utils/YamlToObjectConverter.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatConfiguration.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParameter.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParameterConstraint.java create mode 100644 sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParser.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/IDistributionClient.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/IDistributionStatusMessageJsonBuilder.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/asdc/RegistrationRequest.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/asdc/ServerListResponse.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IComponentDoneStatusMessage.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IConfiguration.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IDistributionStatusMessage.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IDistributionStatusMessageBasic.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IFinalDistrStatusMessage.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/INotificationCallback.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IStatusCallback.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/IArtifactInfo.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/INotificationData.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/IResourceInstance.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/IStatusData.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/IVfModuleMetadata.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/results/IDistributionClientDownloadResult.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/api/results/IDistributionClientResult.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/http/AsdcUrls.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/http/HttpAsdcClient.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/http/HttpAsdcResponse.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/http/IHttpAsdcClient.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/http/SdcConnectorClient.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/http/TopicRegistrationResponse.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/ArtifactInfoImpl.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/Configuration.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionClientDownloadResultImpl.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionClientFactory.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionClientImpl.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionClientResultImpl.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionStatusMessageImpl.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionStatusMessageJsonBuilderFactory.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/JsonContainerResourceInstance.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/NotificationConsumer.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/NotificationDataImpl.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/StatusConsumer.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/StatusDataImpl.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/VfModuleMetadata.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/mock/DistributionClientDownloadResultStubImpl.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/mock/DistributionClientResultStubImpl.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/mock/DistributionClientStubImpl.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/ArtifactTypeEnum.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/DistributionActionResultEnum.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/DistributionClientConstants.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/DistributionStatusEnum.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/GeneralUtils.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/Pair.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/Wrapper.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/YamlToObjectConverter.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/heat/HeatConfiguration.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/heat/HeatParameter.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/heat/HeatParameterConstraint.java delete mode 100644 sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/heat/HeatParser.java create mode 100644 sdc-distribution-client/src/test/java/org/onap/sdc/http/SdcConnectorClientTest.java create mode 100644 sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionClientDownloadResultTest.java create mode 100644 sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionClientTest.java create mode 100644 sdc-distribution-client/src/test/java/org/onap/sdc/impl/HeatParserTest.java create mode 100644 sdc-distribution-client/src/test/java/org/onap/sdc/impl/NotificationConsumerTest.java create mode 100644 sdc-distribution-client/src/test/java/org/onap/sdc/utils/ArtifactsUtils.java create mode 100644 sdc-distribution-client/src/test/java/org/onap/sdc/utils/TestConfiguration.java create mode 100644 sdc-distribution-client/src/test/java/org/onap/sdc/utils/TestNotificationCallback.java delete mode 100644 sdc-distribution-client/src/test/java/org/openecomp/sdc/http/SdcConnectorClientTest.java delete mode 100644 sdc-distribution-client/src/test/java/org/openecomp/sdc/impl/DistributionClientDownloadResultTest.java delete mode 100644 sdc-distribution-client/src/test/java/org/openecomp/sdc/impl/DistributionClientTest.java delete mode 100644 sdc-distribution-client/src/test/java/org/openecomp/sdc/impl/HeatParserTest.java delete mode 100644 sdc-distribution-client/src/test/java/org/openecomp/sdc/impl/NotificationConsumerTest.java delete mode 100644 sdc-distribution-client/src/test/java/org/openecomp/sdc/utils/ArtifactsUtils.java delete mode 100644 sdc-distribution-client/src/test/java/org/openecomp/sdc/utils/TestConfiguration.java delete mode 100644 sdc-distribution-client/src/test/java/org/openecomp/sdc/utils/TestNotificationCallback.java diff --git a/README.md b/README.md index 38c70ec..5f32672 100644 --- a/README.md +++ b/README.md @@ -36,13 +36,13 @@ activateServerTLSAuth : Sets whether ASDC server TLS authentication is activated Example of configuration file implementing IConfiguration interface: -------------------------------------------------------------------- -package org.openecomp.conf; +package org.onap.conf; import java.util.ArrayList; import java.util.List; -import org.openecomp.asdc.api.consumer.IConfiguration; -import org.openecomp.asdc.utils.ArtifactTypeEnum; +import org.onap.asdc.api.consumer.IConfiguration; +import org.onap.asdc.utils.ArtifactTypeEnum; public class SimpleConfiguration implements IConfiguration{ int randomSeed; @@ -116,7 +116,7 @@ Loggin can be done using log4j Example of log.properties file: ------------------------------- log4j.rootCategory=DEBUG, CONSOLE, LOGFILE -log4j.logger.org.openecomp=TRACE, CONSOLE, LOGFILE +log4j.logger.org.onap=TRACE, CONSOLE, LOGFILE # CONSOLE is set to be a ConsoleAppender using a PatternLayout. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender @@ -137,7 +137,7 @@ log4j.appender.LOGFILE.MaxBackupIndex=10 *** to be completed on release *** -SDC@lists.openecomp.org +SDC@lists.onap.org SDC Javadoc and Maven site diff --git a/pom.xml b/pom.xml index a9390d4..2996647 100644 --- a/pom.xml +++ b/pom.xml @@ -2,9 +2,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - org.openecomp.sdc.sdc-distribution-client + org.onap.sdc.sdc-distribution-client sdc-main-distribution-client - 1.2.3-SNAPSHOT + 1.3.0-SNAPSHOT pom sdc-sdc-distribution-client @@ -40,7 +40,7 @@ ${project.basedir}/target/jacoco.exec https://nexus.onap.org - /content/sites/site/org/openecomp/sdc/sdc-distribution-client/${project.version} + /content/sites/site/org/onap/sdc/sdc-distribution-client/${project.version} snapshots releases 176c31dfe190a diff --git a/sdc-distribution-ci/log4j.properties b/sdc-distribution-ci/log4j.properties index 80b2ca8..f71e8ce 100644 --- a/sdc-distribution-ci/log4j.properties +++ b/sdc-distribution-ci/log4j.properties @@ -1,6 +1,6 @@ log4j.rootCategory=DEBUG, CONSOLE, LOGFILE -log4j.logger.org.openecomp.sdc=TRACE, CONSOLE, LOGFILE +log4j.logger.org.onap.sdc=TRACE, CONSOLE, LOGFILE # CONSOLE is set to be a ConsoleAppender using a PatternLayout. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender diff --git a/sdc-distribution-ci/pom.xml b/sdc-distribution-ci/pom.xml index 326bdb9..1914d07 100644 --- a/sdc-distribution-ci/pom.xml +++ b/sdc-distribution-ci/pom.xml @@ -4,9 +4,9 @@ 4.0.0 - org.openecomp.sdc.sdc-distribution-client + org.onap.sdc.sdc-distribution-client sdc-main-distribution-client - 1.2.2-SNAPSHOT + 1.3.0-SNAPSHOT sdc-distribution-ci @@ -23,16 +23,16 @@ - org.openecomp.sdc.sdc-distribution-client + org.onap.sdc.sdc-distribution-client sdc-distribution-client ${project.version} compile - org.openecomp.sdc.sdc-tosca + org.onap.sdc.sdc-tosca sdc-tosca - 1.1.55-SNAPSHOT + 1.3.0-SNAPSHOT compile @@ -87,7 +87,7 @@ spring-boot - org.openecomp.test.ClientTest + org.onap.test.ClientTest diff --git a/sdc-distribution-ci/src/main/java/org/onap/test/AdvanceCallBack.java b/sdc-distribution-ci/src/main/java/org/onap/test/AdvanceCallBack.java new file mode 100644 index 0000000..a122ca0 --- /dev/null +++ b/sdc-distribution-ci/src/main/java/org/onap/test/AdvanceCallBack.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.test; + +import java.io.FileOutputStream; +import java.io.IOException; + +import org.onap.sdc.api.IDistributionClient; +import org.onap.sdc.api.results.IDistributionClientDownloadResult; +import org.onap.sdc.utils.DistributionActionResultEnum; + +/** + * + * @author tg851x + * This is class used in testing and run locally in the IDE + * logging not needed it is monitored through the IDE console. + */ +public class AdvanceCallBack extends SimpleCallback{ + + public AdvanceCallBack(IDistributionClient client) { + super(client); + } + + @Override + protected void postDownloadLogic( IDistributionClientDownloadResult downloadResult) { + if( downloadResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS){ + saveArtifactPayloadToDisk(downloadResult); + } + + } + + protected void saveFile(byte[] bs, String fileName) { + String downloadPath = SimpleConfiguration.downloadPath(); + try(FileOutputStream fileOuputStream = new FileOutputStream(downloadPath + fileName);) { + fileOuputStream.write(bs); + fileOuputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + protected void saveArtifactPayloadToDisk(IDistributionClientDownloadResult downloadResult) { + System.out.println("################ Downloaded Artifact Payload Start ################"); + String fileName = downloadResult.getArtifactFilename(); + saveFile(downloadResult.getArtifactPayload(), fileName); + System.out.println("################ Downloaded Artifact Payload End ################"); + } + + + + +} diff --git a/sdc-distribution-ci/src/main/java/org/onap/test/ArtifactTypeEnum.java b/sdc-distribution-ci/src/main/java/org/onap/test/ArtifactTypeEnum.java new file mode 100644 index 0000000..1f5e799 --- /dev/null +++ b/sdc-distribution-ci/src/main/java/org/onap/test/ArtifactTypeEnum.java @@ -0,0 +1,111 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.test; + +import java.util.ArrayList; +import java.util.List; + +/** + * Enum That Represents possible Artifacts Types. + * + */ +public enum ArtifactTypeEnum { + + CHEF("CHEF"), + PUPPET("PUPPET"), + YANG("YANG"), + SHELL_SCRIPT("SHELL_SCRIPT"), + ICON("ICON"), + UNKNOWN("UNKNOWN"), + HEAT("HEAT"), + DG_XML("DG_XML"), + MURANO_PKG("MURANO_PKG"), + HEAT_ENV("HEAT_ENV"), + YANG_XML("YANG_XML"), + HEAT_VOL("HEAT_VOL"), + HEAT_NET("HEAT_NET"), + OTHER("OTHER"), + WORKFLOW("WORKFLOW"), + NETWORK_CALL_FLOW("NETWORK_CALL_FLOW"), + TOSCA_TEMPLATE("TOSCA_TEMPLATE"), + TOSCA_CSAR("TOSCA_CSAR"), + VNF_CATALOG("VNF_CATALOG"), + VF_LICENSE("VF_LICENSE"), + VENDOR_LICENSE("VENDOR_LICENSE"), + MODEL_INVENTORY_PROFILE("MODEL_INVENTORY_PROFILE"), + MODEL_QUERY_SPEC("MODEL_QUERY_SPEC"), + APPC_CONFIG("APPC_CONFIG"), + HEAT_NESTED("HEAT_NESTED"), + HEAT_ARTIFACT("HEAT_ARTIFACT"), + VF_MODULES_METADATA("VF_MODULES_METADATA"), + + // DCAE Artifacts + DCAE_TOSCA("DCAE_TOSCA"), + DCAE_JSON("DCAE_JSON"), + DCAE_POLICY("DCAE_POLICY"), + DCAE_DOC("DCAE_DOC"), + DCAE_EVENT("DCAE_EVENT"), + DCAE_INVENTORY_TOSCA("DCAE_INVENTORY_TOSCA"), + DCAE_INVENTORY_JSON("DCAE_INVENTORY_JSON"), + DCAE_INVENTORY_POLICY("DCAE_INVENTORY_POLICY"), + DCAE_INVENTORY_DOC("DCAE_INVENTORY_DOC"), + DCAE_INVENTORY_BLUEPRINT("DCAE_INVENTORY_BLUEPRINT"), + DCAE_INVENTORY_EVENT("DCAE_INVENTORY_EVENT"), + + // AAI Artifacts + AAI_SERVICE_MODEL("AAI_SERVICE_MODEL"), + AAI_VF_MODEL("AAI_VF_MODEL"), + AAI_VF_MODULE_MODEL("AAI_VF_MODULE_MODEL"), + AAI_VF_INSTANCE_MODEL("AAI_VF_INSTANCE_MODEL"), + + // MIB artifacts + SNMP_POLL("SNMP_POLL"), + SNMP_TRAP("SNMP_TRAP"), + GUIDE("GUIDE"); + + ArtifactTypeEnum(String type) { + this.type = type; + } + + private String type; + + public String getType() { + return type; + } + + public static ArtifactTypeEnum findType(final String type) { + for (ArtifactTypeEnum ate : ArtifactTypeEnum.values()) { + // According to Pavel/Ella + if (ate.getType().equalsIgnoreCase(type)) { + return ate; + } + } + return null; + } + + public static List getAllTypes() { + List types = new ArrayList<>(); + for (ArtifactTypeEnum ate : ArtifactTypeEnum.values()) { + types.add(ate.getType()); + } + return types; + } +} diff --git a/sdc-distribution-ci/src/main/java/org/onap/test/ClientTest.java b/sdc-distribution-ci/src/main/java/org/onap/test/ClientTest.java new file mode 100644 index 0000000..24160b5 --- /dev/null +++ b/sdc-distribution-ci/src/main/java/org/onap/test/ClientTest.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.test; + +import org.onap.sdc.api.IDistributionClient; +import org.onap.sdc.api.consumer.IComponentDoneStatusMessage; +import org.onap.sdc.api.consumer.IStatusCallback; +import org.onap.sdc.api.notification.INotificationData; +import org.onap.sdc.api.notification.IStatusData; +import org.onap.sdc.api.results.IDistributionClientResult; +import org.onap.sdc.impl.DistributionClientFactory; +import org.onap.sdc.utils.DistributionStatusEnum; + +public class ClientTest { + public static void main(String[] args) throws Exception { + + soWdListner(); + clientSender(); + + } + + private static void clientSender() { + IDistributionClient client = DistributionClientFactory.createDistributionClient(); + IDistributionClientResult result = client.init(new SimpleConfiguration(), new SimpleCallback(client)); + System.err.println("Init Status: " + result.toString()); + + IDistributionClientResult start = client.start(); + + System.err.println("Start Status: " + start.toString()); + for( int i = 0; i < 2; i++ ){ + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + client.sendComponentDoneStatus(new IComponentDoneStatusMessage() { + + @Override + public long getTimestamp() { + return System.currentTimeMillis(); + } + + @Override + public DistributionStatusEnum getStatus() { + return DistributionStatusEnum.COMPONENT_DONE_OK; + } + + @Override + public String getDistributionID() { + // TODO Auto-generated method stub + return ""; + } + + @Override + public String getConsumerID() { + return client.getConfiguration().getConsumerID(); + } + + @Override + public String getComponentName() { + return "MSO"; + } + }); + } + + } + + private static void soWdListner() { + IDistributionClient client = DistributionClientFactory.createDistributionClient(); + IDistributionClientResult result = client.init(new SimpleConfiguration() { + @Override + public boolean isConsumeProduceStatusTopic() { + return true; + } + }, new SimpleCallback(client) { + @Override + public void activateCallback(INotificationData data) { + System.err.println("Monitor Recieved Notification: " + data.toString()); + + } + }, new IStatusCallback() { + + @Override + public void activateCallback(IStatusData data) { + System.err.println("Monitor Recieved Status: " + data.toString()); + + } + }); + System.err.println("Init Status: " + result.toString()); + IDistributionClientResult start = client.start(); + + System.err.println("Start Status: " + start.toString()); + } + +} diff --git a/sdc-distribution-ci/src/main/java/org/onap/test/CsarToscaTester.java b/sdc-distribution-ci/src/main/java/org/onap/test/CsarToscaTester.java new file mode 100644 index 0000000..1102150 --- /dev/null +++ b/sdc-distribution-ci/src/main/java/org/onap/test/CsarToscaTester.java @@ -0,0 +1,121 @@ +package org.onap.test; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; +import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; +import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory; +import org.onap.sdc.tosca.parser.impl.SdcTypes; +import org.onap.sdc.toscaparser.api.Group; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.elements.Metadata; +import org.onap.sdc.toscaparser.api.parameters.Input; +import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; + +public class CsarToscaTester { + public static void main(String[] args) throws Exception { + System.out.println("CsarToscaParser - path to CSAR's Directory is " + Arrays.toString(args)); + SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance(); + + File folder = new File(args[0]); + File[] listOfFiles = folder.listFiles(); + Date now = new Date(); + SimpleDateFormat dateFormat = new SimpleDateFormat("d-MM-y-HH_mm_ss"); + String time = dateFormat.format(now); + String csarsDir = args[1] + "/csar-reports-" + time; + File dir = new File(csarsDir); + dir.mkdir(); + + + for (File file : listOfFiles) { + if (file.isFile()) { + System.out.println("File " + file.getAbsolutePath()); + String name = file.getName(); + String currentCsarDir = csarsDir+"/"+name+"-"+time; + dir = new File(currentCsarDir); + dir.mkdir(); + try { + processCsar(factory, file); + } catch (SdcToscaParserException e){ + System.out.println("SdcToscaParserException caught. Code: "+e.getCode()+", message: "+ e.getMessage()); + } + List validationIssueReport = ThreadLocalsHolder.getCollector().getValidationIssueReport(); + System.out.println("Validation issues during CSAR parsing are: " + (validationIssueReport != null ? validationIssueReport.toString() : "none")); + + try { + generateReport(time, name, currentCsarDir, validationIssueReport, "validationIssues"); + + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + } + } + + private static void processCsar(SdcToscaParserFactory factory, File file) throws SdcToscaParserException { + ISdcCsarHelper sdcCsarHelper = factory.getSdcCsarHelper(file.getAbsolutePath()); + //Service level + System.out.println("Invoking sdc-tosca methods on this CSAR...."); + String conformanceLevel = sdcCsarHelper.getConformanceLevel(); + System.out.println("getConformanceLevel() - conformance level is "+conformanceLevel); + String serviceSubstitutionMappingsTypeName = sdcCsarHelper.getServiceSubstitutionMappingsTypeName(); + System.out.println("serviceSubstitutionMappingsTypeName() - subst mappings type of service is "+serviceSubstitutionMappingsTypeName); + List serviceInputs = sdcCsarHelper.getServiceInputs(); + System.out.println("getServiceInputs() - service inputs are "+serviceInputs); + Metadata serviceMetadata = sdcCsarHelper.getServiceMetadata(); + System.out.println("getServiceMetadata() - service metadata is "+serviceMetadata); + Map serviceMetadataProperties = sdcCsarHelper.getServiceMetadataProperties(); + System.out.println("getServiceMetadataProperties() - service metadata properties is "+serviceMetadataProperties); + List allottedResources = sdcCsarHelper.getAllottedResources(); + System.out.println("getAllottedResources() - service allotted resources are "+allottedResources); + List serviceVfList = sdcCsarHelper.getServiceVfList(); + System.out.println("getServiceVfList() - VF list is "+serviceVfList); + List serviceNodeTemplateBySdcType = sdcCsarHelper.getServiceNodeTemplateBySdcType(SdcTypes.VF); + System.out.println("getServiceNodeTemplateBySdcType() - VF list is "+serviceNodeTemplateBySdcType); + List serviceNodeTemplates = sdcCsarHelper.getServiceNodeTemplates(); + System.out.println("getServiceNodeTemplates() - all node templates list of service is "+serviceNodeTemplates); + + serviceVfList.forEach(x -> { + String nodeTemplateCustomizationUuid = sdcCsarHelper.getNodeTemplateCustomizationUuid(x); + System.out.println("getNodeTemplateCustomizationUuid() - VF ID is "+nodeTemplateCustomizationUuid); + String typeOfNodeTemplate = sdcCsarHelper.getTypeOfNodeTemplate(x); + System.out.println("getTypeOfNodeTemplate() - VF tosca type is "+typeOfNodeTemplate); + List vfModulesByVf = sdcCsarHelper.getVfModulesByVf(nodeTemplateCustomizationUuid); + System.out.println("getVfModulesByVf() - VF modules list is "+vfModulesByVf); + vfModulesByVf.forEach(y -> { + List membersOfVfModule = sdcCsarHelper.getMembersOfVfModule(x, y); + System.out.println("getMembersOfVfModule() - members of VfModule are "+membersOfVfModule); + }); + List vfcListByVf = sdcCsarHelper.getVfcListByVf(nodeTemplateCustomizationUuid); + System.out.println("getVfcListByVf() - VFC list is "+vfcListByVf); + vfcListByVf.forEach(z -> { + List nodeTemplateBySdcType = sdcCsarHelper.getNodeTemplateBySdcType(z, SdcTypes.CP); + System.out.println("getNodeTemplateBySdcType() - CP children node templates of this VFC are "+nodeTemplateBySdcType); + Map> cpPropertiesFromVfcAsObject = sdcCsarHelper.getCpPropertiesFromVfcAsObject(z); + System.out.println("getCpPropertiesFromVfcAsObject() - consolidated CP properties for this VFC are "+cpPropertiesFromVfcAsObject); + boolean hasTopology = sdcCsarHelper.hasTopology(z); + System.out.println("hasTopology() - this VFC is "+(hasTopology ? "nested" : "not nested")); + }); + }); + + } + + private static void generateReport(String time, String name, String currentCsarDir, List criticalsReport, String type) + throws IOException { + FileWriter fw; + fw = new FileWriter(new File(currentCsarDir + "/" + criticalsReport.size() + "-"+type+"-" + name +"-"+time + ".txt")); + for (String exception : criticalsReport) { + fw.write(exception); + fw.write("\r\n"); + } + fw.close(); + } +} diff --git a/sdc-distribution-ci/src/main/java/org/onap/test/Decoder.java b/sdc-distribution-ci/src/main/java/org/onap/test/Decoder.java new file mode 100644 index 0000000..384d26d --- /dev/null +++ b/sdc-distribution-ci/src/main/java/org/onap/test/Decoder.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.test; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import org.apache.commons.codec.binary.Base64; + +public class Decoder { + + public static String encode(byte[] byteArrayToEncode) { + return new String(Base64.encodeBase64(byteArrayToEncode)); + } + + public static String decode(String strEncoded) { + return new String(Base64.decodeBase64(strEncoded)); + } + + public static String readFileToString(String file) throws IOException { + + try (FileReader fileReader = new FileReader(file); + BufferedReader reader = new BufferedReader(fileReader)) { + String line; + StringBuilder stringBuilder = new StringBuilder(); + String ls = System.getProperty("line.separator"); + + while ((line = reader.readLine()) != null) { + stringBuilder.append(line); + stringBuilder.append(ls); + } + + reader.close(); + fileReader.close(); + return stringBuilder.toString(); + } catch (IOException e) { + throw new IOException(e); + } + } +} diff --git a/sdc-distribution-ci/src/main/java/org/onap/test/NotificationCallback.java b/sdc-distribution-ci/src/main/java/org/onap/test/NotificationCallback.java new file mode 100644 index 0000000..48fda0a --- /dev/null +++ b/sdc-distribution-ci/src/main/java/org/onap/test/NotificationCallback.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.test; + +import org.onap.sdc.api.IDistributionClient; +import org.onap.sdc.api.notification.INotificationData; + +public class NotificationCallback extends SimpleCallback{ + INotificationData latestCallbackData; + public INotificationData getData() { + return latestCallbackData; + } + public NotificationCallback(IDistributionClient client) { + super(client); + } + + public void activateCallback(INotificationData data) { + this.latestCallbackData = data; + super.activateCallback(data); + } +} diff --git a/sdc-distribution-ci/src/main/java/org/onap/test/SimpleCallback.java b/sdc-distribution-ci/src/main/java/org/onap/test/SimpleCallback.java new file mode 100644 index 0000000..547dde2 --- /dev/null +++ b/sdc-distribution-ci/src/main/java/org/onap/test/SimpleCallback.java @@ -0,0 +1,356 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.test; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.onap.sdc.api.IDistributionClient; +import org.onap.sdc.api.consumer.IDistributionStatusMessage; +import org.onap.sdc.api.consumer.INotificationCallback; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.INotificationData; +import org.onap.sdc.api.notification.IResourceInstance; +import org.onap.sdc.api.notification.IVfModuleMetadata; +import org.onap.sdc.api.results.IDistributionClientDownloadResult; +import org.onap.sdc.api.results.IDistributionClientResult; +import org.onap.sdc.utils.ArtifactTypeEnum; +import org.onap.sdc.utils.DistributionActionResultEnum; +import org.onap.sdc.utils.DistributionStatusEnum; + +/** + * + * @author tg851x + * This is class used in testing and run locally in the IDE + * logging not needed it is monitored through the IDE console. + */ +public class SimpleCallback implements INotificationCallback { + protected IDistributionClient client; + public List iArtifactInfo; + + public final Map simpleCallbackResults = new HashMap(); + + public Map getSimpleCallbackResults() { + return simpleCallbackResults; + } + + public List getIArtifactInfo(){ + return iArtifactInfo; + } + public SimpleCallback(IDistributionClient client) { + this.client = client; + } + + + + + + public void activateCallback(INotificationData data) { + + List artifacts = getArtifacts(data); + + + for (IArtifactInfo iArtifactInfo : artifacts) { + + IArtifactInfo artifactMetadataByUUID = data.getArtifactMetadataByUUID(iArtifactInfo.getArtifactUUID()); + assertEquals("check artifact checksum", iArtifactInfo.getArtifactChecksum(), artifactMetadataByUUID.getArtifactChecksum()); + System.out.println(artifactMetadataByUUID.getArtifactURL()); + if (artifactMetadataByUUID.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA)){ + IDistributionClientDownloadResult download = client.download(iArtifactInfo); + if (download.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS){ + List decodeVfModuleArtifact = client.decodeVfModuleArtifact(download.getArtifactPayload()); +// assertEquals("decoded not equal to actual group amount ", decodeVfModuleArtifact.size(), 2); + if (!decodeVfModuleArtifact.isEmpty()){ + for (IVfModuleMetadata moduleMetadata : decodeVfModuleArtifact) { + List moduleArtifacts = moduleMetadata.getArtifacts(); + if (moduleArtifacts != null) { + + for (String artifactId : moduleArtifacts) { + + IArtifactInfo artifactInfo = data.getArtifactMetadataByUUID(artifactId); + IDistributionClientDownloadResult downloadArt = client.download(artifactInfo); + assertEquals(downloadArt.getDistributionActionResult(), DistributionActionResultEnum.SUCCESS); + + } + + } + } + } + } + } + } + + + for (IArtifactInfo relevantArtifact : artifacts){ + // Download Artifact + IDistributionClientDownloadResult downloadResult = client.download(relevantArtifact); + + postDownloadLogic(downloadResult); + + + + simpleCallbackResults.put("downloadResult", downloadResult); + System.out.println("downloadResult: " + downloadResult.toString()); + System.out.println("<<<<<<<<<<< Artifact content >>>>>>>>>>"); + System.out.println(Decoder.encode(downloadResult.getArtifactPayload())); + + /////Print artifact content to console/////// + +// byte[] contentInBytes = BaseEncoding.base64().decode(Decoder.encode(downloadResult.getArtifactPayload())); +// try { +// System.out.println("Source content: " + new String(contentInBytes, "UTF-8")); +// } catch (UnsupportedEncodingException e1) { +// // TODO Auto-generated catch block +// e1.printStackTrace(); +// } + System.out.println("ArtInfo_timeout: "+ relevantArtifact.getArtifactTimeout()); + System.out.println("ArtInfo_Art_description: "+ relevantArtifact.getArtifactDescription()); + System.out.println("ArtInfo_Art_CheckSum: "+ relevantArtifact.getArtifactChecksum()); + System.out.println("ArtInfo_Art_Url: "+ relevantArtifact.getArtifactURL()); + System.out.println("ArtInfo_Art_Type: "+ relevantArtifact.getArtifactType()); + System.out.println("ArtInfo_Art_Name: "+ relevantArtifact.getArtifactName()); + System.out.println("ArtInfo_UUID: " + relevantArtifact.getArtifactUUID()); + System.out.println("ArtInfo_Version: " + relevantArtifact.getArtifactVersion()); + System.out.println("ArtInfo_RelatedArtifacts: "+ relevantArtifact.getRelatedArtifacts()); + + System.out.println("ArtInfo_Serv_description: " + data.getServiceDescription()); + System.out.println("ArtInfo_Serv_Name: " + data.getServiceName()); + System.out.println("Get_serviceVersion: " + data.getServiceVersion()); + System.out.println("Get_Service_UUID: " + data.getServiceUUID()); + System.out.println("ArtInfo_DistributionId: " + data.getDistributionID()); + System.out.println("ArtInfo_ServiceInvariantUUID: " + data.getServiceInvariantUUID()); + + + // assertTrue("response code is not 200, returned :" + downloadResult.getDistributionActionResult(), downloadResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS ); + + try { + String payload = new String(downloadResult.getArtifactPayload()); +// System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); +// System.out.println(payload); +// System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + + } catch (Exception e) { + System.out.println("catch"); +// break; + // TODO: handle exception + } + + + + + if (downloadResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) { + handleSuccessfullDownload(data, relevantArtifact, downloadResult.getArtifactPayload()); + } else { + handleFailedDownload(data, relevantArtifact); + } + } +// if (data != null){ +// iArtifactInfo.addAll(artifacts); +// } + + } + + private List getArtifacts(INotificationData data) { + List ret = new ArrayList(); + List resources = data.getResources(); +// data.getArtifactMetadataByUUID(arg0) + List relevantArtifactTypes = client.getConfiguration().getRelevantArtifactTypes(); + + List collect = resources.stream().flatMap( e -> e.getArtifacts().stream()).filter(p -> relevantArtifactTypes.contains(p.getArtifactType() )).collect(Collectors.toList()); +// if( resources != null ){ +// for( IResourceInstance resourceInstance : resources){ +// if( resourceInstance.getArtifacts() != null ){ +// +// +// +// ret.addAll(resourceInstance.getArtifacts()); +// +// +// } +// } +// } + ret.addAll(collect); + + List servicesArt = data.getServiceArtifacts(); + if( servicesArt != null ){ + ret.addAll(servicesArt); + } + + System.out.println("I am here: " + ret.toString()); + return ret; + } + + + + private void handleFailedDownload(INotificationData data, + IArtifactInfo relevantArtifact) { + // Send Download Status + IDistributionClientResult sendDownloadStatus = client.sendDownloadStatus(buildStatusMessage(client, data, relevantArtifact, DistributionStatusEnum.DOWNLOAD_ERROR)); + postDownloadStatusSendLogic(sendDownloadStatus); + } + + private void handleSuccessfullDownload(INotificationData data, IArtifactInfo relevantArtifact, byte[] payload) { + // Send Download Status + IDistributionClientResult sendDownloadStatus = client.sendDownloadStatus(buildStatusMessage(client, data, relevantArtifact, DistributionStatusEnum.DOWNLOAD_OK)); + + simpleCallbackResults.put("sendDownloadStatus", sendDownloadStatus); +// assertTrue("response code is not 200, returned :" + sendDownloadStatus.getDistributionActionResult(), sendDownloadStatus.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS ); + + // Doing deployment ... + postDownloadStatusSendLogic(sendDownloadStatus); + boolean isDeployedSuccessfully = handleDeployment(data, relevantArtifact, payload); + IDistributionClientResult deploymentStatus; + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + if (isDeployedSuccessfully) { + deploymentStatus = client.sendDeploymentStatus(buildStatusMessage(client, data, relevantArtifact, DistributionStatusEnum.DEPLOY_OK)); + + simpleCallbackResults.put("sendDeploymentStatus", deploymentStatus); +// assertTrue("response code is not 200, returned :" + deploymentStatus.getDistributionActionResult(), deploymentStatus.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS ); + + } else { + deploymentStatus = handleFailedDeployment(data, relevantArtifact); + } + + postDeploymentStatusSendLogic(deploymentStatus); + } + + private IDistributionClientResult handleFailedDeployment(INotificationData data, IArtifactInfo relevantArtifact) { + IDistributionClientResult deploymentStatus; + boolean isAlreadyDeployed = checkIsDeployed(); + if (isAlreadyDeployed) { + deploymentStatus = client.sendDeploymentStatus(buildStatusMessage(client, data, relevantArtifact, DistributionStatusEnum.ALREADY_DEPLOYED)); + } else { + deploymentStatus = client.sendDeploymentStatus(buildStatusMessage(client, data, relevantArtifact, DistributionStatusEnum.DEPLOY_ERROR)); + } + return deploymentStatus; + } + + protected void postDownloadLogic(IDistributionClientDownloadResult downloadResult) { + // TODO Auto-generated method stub + + } + + private void postDownloadStatusSendLogic( + IDistributionClientResult sendDownloadStatus) { + // TODO Auto-generated method stub + + } + + private void postDeploymentStatusSendLogic( + IDistributionClientResult deploymentStatus) { + // TODO Auto-generated method stub + + } + + private boolean checkIsDeployed() { + return false; + } + + private boolean handleDeployment(INotificationData data, IArtifactInfo relevantArtifact, byte[] payload) { + if (relevantArtifact.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())) { + + try { + List serviceArtifacts = data.getServiceArtifacts(); + List resourcesArtifacts = data.getResources(); + + JSONArray jsonData = new JSONArray(new String(payload)); + boolean artifactIsFound = true; + for (int index = 0 ; index < jsonData.length(); index++) { + + JSONObject jsonObject = (JSONObject) jsonData.get(index); + JSONArray artifacts = (JSONArray) jsonObject.get("artifacts"); + for (int i = 0 ; i < artifacts.length(); i++) { + String artifact = artifacts.getString(i).toString(); + + Optional serviceArtifactFound = serviceArtifacts.stream().filter(x -> x.getArtifactUUID().equals(artifact)).findFirst(); + + boolean isResourceFound = false; + for (int j = 0 ; j < resourcesArtifacts.size(); j++) { + Optional resourceArtifactFound = resourcesArtifacts.get(j).getArtifacts().stream().filter(x -> x.getArtifactUUID().equals(artifact)).findFirst(); + isResourceFound = resourceArtifactFound.isPresent() || isResourceFound; + } + + if (!serviceArtifactFound.isPresent() && !isResourceFound) { + artifactIsFound = false; + System.out.println("################ Artifact: " + artifact + " NOT FOUND in Notification Data ################"); + } + } + } + return artifactIsFound; + + } catch (Exception e) { + System.out.println("################ Couldn't convert vf_modules_metadata.json to json : " + e.getMessage()); + return false; + } + } + else { + return true; + } + +// to return deploy_error use return false +// return false; + } + + public static IDistributionStatusMessage buildStatusMessage( + final IDistributionClient client, final INotificationData data, + final IArtifactInfo relevantArtifact, + final DistributionStatusEnum status) { + IDistributionStatusMessage statusMessage = new IDistributionStatusMessage() { + + public long getTimestamp() { + long currentTimeMillis = System.currentTimeMillis(); + return currentTimeMillis; + } + + public DistributionStatusEnum getStatus() { + return status; + } + + public String getDistributionID() { + return data.getDistributionID(); + } + + public String getConsumerID() { + return client.getConfiguration().getConsumerID(); + } + + public String getArtifactURL() { + return relevantArtifact.getArtifactURL(); + } + }; + return statusMessage; + } + + +} diff --git a/sdc-distribution-ci/src/main/java/org/onap/test/SimpleConfiguration.java b/sdc-distribution-ci/src/main/java/org/onap/test/SimpleConfiguration.java new file mode 100644 index 0000000..d22bcf2 --- /dev/null +++ b/sdc-distribution-ci/src/main/java/org/onap/test/SimpleConfiguration.java @@ -0,0 +1,204 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.onap.sdc.api.consumer.IConfiguration; + +public class SimpleConfiguration implements IConfiguration{ + + /*public String getUser() + { + return System.getProperty("user"); + } + + public List getRelevantArtifactTypes() { + return ArtifactTypeEnum.getAllTypes(); + } + + public int getPollingTimeout() + { + return 20; + } + + public int getPollingInterval() + { + return 20; + } + + public String getPassword() + { + return System.getProperty("password"); + } + + public String getEnvironmentName() + { + return System.getProperty("env"); + } + + public String getConsumerID() + { + return System.getProperty("consumerID"); + } + + public String getConsumerGroup() + { + return System.getProperty("groupID"); + } + + public String getAsdcAddress() + { + return System.getProperty("beAddress"); + } + + public String getKeyStorePath() + { + return ""; + } + + public String getKeyStorePassword() + { + return "Aa123456"; + } + + public boolean activateServerTLSAuth() + { + return Boolean.parseBoolean(System.getProperty("auth")); +// res.add(ArtifactTypeEnum.HEAT_ARTIFACT); +// res.add(ArtifactTypeEnum.HEAT_ENV); +// res.add(ArtifactTypeEnum.MURANO_PKG); +// res.add(ArtifactTypeEnum.VF_LICENSE); +// res.add(ArtifactTypeEnum.APPC_CONFIG); +// res.add(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE); +// res.add(ArtifactTypeEnum.VNF_CATALOG); +// res.add(ArtifactTypeEnum.APPC_CONFIG); +// res.add(ArtifactTypeEnum.VF_MODULES_METADATA); +// return "PROD-Tedy-Only"; +// return "A-AI"; +// return "A-AI"; + } + + @Override + public boolean isFilterInEmptyResources() { + return false; + } + + public static String downloadPath() { + return "c:\\temp\\"; + } + + public static Boolean toDownload() { + return false; + }*/ + + public String getUser() { + return "ci"; + } + + public List getRelevantArtifactTypes() { + +// List res = new ArrayList(); +// for (ArtifactTypeEnum type : AssetTypeEnum.values()){ +// res.add(type.name()); +// } + return ArtifactTypeEnum.getAllTypes(); + } + + + public int getPollingTimeout() { + return 20; + } + + public int getPollingInterval() { + return 20; + } + + public String getPassword() { + return "123456"; + } + + public String getEnvironmentName() { + return "PROD"; + } + + public String getConsumerID() { + return "consumerVasya"; + } + + public String getConsumerGroup() { + return "groupVasya"; + + } + + public static Boolean toDownload() { + return true; + } + + public static String downloadPath() { + return "c:\\temp\\"; + } + + public String getAsdcAddress() { + return "127.0.0.1:8443"; + } + + @Override + public List getMsgBusAddress() { + return new ArrayList<>(); + } + + @Override + public String getKeyStorePath() { + return StringUtils.EMPTY; + } + + @Override + public String getKeyStorePassword() { + + return "Aa123456"; + } + + @Override + public boolean activateServerTLSAuth() { + + return false; + } + + @Override + public boolean isFilterInEmptyResources() { + return false; + } + + @Override + public Boolean isUseHttpsWithDmaap() { + return true; + } + + @Override + public boolean isConsumeProduceStatusTopic() { + return false; + } + +} diff --git a/sdc-distribution-ci/src/main/java/org/openecomp/test/AdvanceCallBack.java b/sdc-distribution-ci/src/main/java/org/openecomp/test/AdvanceCallBack.java deleted file mode 100644 index faabaeb..0000000 --- a/sdc-distribution-ci/src/main/java/org/openecomp/test/AdvanceCallBack.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.test; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; -import org.openecomp.sdc.utils.DistributionActionResultEnum; - -/** - * - * @author tg851x - * This is class used in testing and run locally in the IDE - * logging not needed it is monitored through the IDE console. - */ -public class AdvanceCallBack extends SimpleCallback{ - - public AdvanceCallBack(IDistributionClient client) { - super(client); - } - - @Override - protected void postDownloadLogic( IDistributionClientDownloadResult downloadResult) { - if( downloadResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS){ - saveArtifactPayloadToDisk(downloadResult); - } - - } - - protected void saveFile(byte[] bs, String fileName) { - String downloadPath = SimpleConfiguration.downloadPath(); - try(FileOutputStream fileOuputStream = new FileOutputStream(downloadPath + fileName);) { - fileOuputStream.write(bs); - fileOuputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - protected void saveArtifactPayloadToDisk(IDistributionClientDownloadResult downloadResult) { - System.out.println("################ Downloaded Artifact Payload Start ################"); - String fileName = downloadResult.getArtifactFilename(); - saveFile(downloadResult.getArtifactPayload(), fileName); - System.out.println("################ Downloaded Artifact Payload End ################"); - } - - - - -} diff --git a/sdc-distribution-ci/src/main/java/org/openecomp/test/ArtifactTypeEnum.java b/sdc-distribution-ci/src/main/java/org/openecomp/test/ArtifactTypeEnum.java deleted file mode 100644 index 5c4c9e2..0000000 --- a/sdc-distribution-ci/src/main/java/org/openecomp/test/ArtifactTypeEnum.java +++ /dev/null @@ -1,111 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.test; - -import java.util.ArrayList; -import java.util.List; - -/** - * Enum That Represents possible Artifacts Types. - * - */ -public enum ArtifactTypeEnum { - - CHEF("CHEF"), - PUPPET("PUPPET"), - YANG("YANG"), - SHELL_SCRIPT("SHELL_SCRIPT"), - ICON("ICON"), - UNKNOWN("UNKNOWN"), - HEAT("HEAT"), - DG_XML("DG_XML"), - MURANO_PKG("MURANO_PKG"), - HEAT_ENV("HEAT_ENV"), - YANG_XML("YANG_XML"), - HEAT_VOL("HEAT_VOL"), - HEAT_NET("HEAT_NET"), - OTHER("OTHER"), - WORKFLOW("WORKFLOW"), - NETWORK_CALL_FLOW("NETWORK_CALL_FLOW"), - TOSCA_TEMPLATE("TOSCA_TEMPLATE"), - TOSCA_CSAR("TOSCA_CSAR"), - VNF_CATALOG("VNF_CATALOG"), - VF_LICENSE("VF_LICENSE"), - VENDOR_LICENSE("VENDOR_LICENSE"), - MODEL_INVENTORY_PROFILE("MODEL_INVENTORY_PROFILE"), - MODEL_QUERY_SPEC("MODEL_QUERY_SPEC"), - APPC_CONFIG("APPC_CONFIG"), - HEAT_NESTED("HEAT_NESTED"), - HEAT_ARTIFACT("HEAT_ARTIFACT"), - VF_MODULES_METADATA("VF_MODULES_METADATA"), - - // DCAE Artifacts - DCAE_TOSCA("DCAE_TOSCA"), - DCAE_JSON("DCAE_JSON"), - DCAE_POLICY("DCAE_POLICY"), - DCAE_DOC("DCAE_DOC"), - DCAE_EVENT("DCAE_EVENT"), - DCAE_INVENTORY_TOSCA("DCAE_INVENTORY_TOSCA"), - DCAE_INVENTORY_JSON("DCAE_INVENTORY_JSON"), - DCAE_INVENTORY_POLICY("DCAE_INVENTORY_POLICY"), - DCAE_INVENTORY_DOC("DCAE_INVENTORY_DOC"), - DCAE_INVENTORY_BLUEPRINT("DCAE_INVENTORY_BLUEPRINT"), - DCAE_INVENTORY_EVENT("DCAE_INVENTORY_EVENT"), - - // AAI Artifacts - AAI_SERVICE_MODEL("AAI_SERVICE_MODEL"), - AAI_VF_MODEL("AAI_VF_MODEL"), - AAI_VF_MODULE_MODEL("AAI_VF_MODULE_MODEL"), - AAI_VF_INSTANCE_MODEL("AAI_VF_INSTANCE_MODEL"), - - // MIB artifacts - SNMP_POLL("SNMP_POLL"), - SNMP_TRAP("SNMP_TRAP"), - GUIDE("GUIDE"); - - ArtifactTypeEnum(String type) { - this.type = type; - } - - private String type; - - public String getType() { - return type; - } - - public static ArtifactTypeEnum findType(final String type) { - for (ArtifactTypeEnum ate : ArtifactTypeEnum.values()) { - // According to Pavel/Ella - if (ate.getType().equalsIgnoreCase(type)) { - return ate; - } - } - return null; - } - - public static List getAllTypes() { - List types = new ArrayList<>(); - for (ArtifactTypeEnum ate : ArtifactTypeEnum.values()) { - types.add(ate.getType()); - } - return types; - } -} diff --git a/sdc-distribution-ci/src/main/java/org/openecomp/test/ClientTest.java b/sdc-distribution-ci/src/main/java/org/openecomp/test/ClientTest.java deleted file mode 100644 index 872240b..0000000 --- a/sdc-distribution-ci/src/main/java/org/openecomp/test/ClientTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.test; - -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.consumer.IComponentDoneStatusMessage; -import org.openecomp.sdc.api.consumer.IStatusCallback; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IStatusData; -import org.openecomp.sdc.api.results.IDistributionClientResult; -import org.openecomp.sdc.impl.DistributionClientFactory; -import org.openecomp.sdc.utils.DistributionStatusEnum; - -public class ClientTest { - public static void main(String[] args) throws Exception { - - soWdListner(); - clientSender(); - - } - - private static void clientSender() { - IDistributionClient client = DistributionClientFactory.createDistributionClient(); - IDistributionClientResult result = client.init(new SimpleConfiguration(), new SimpleCallback(client)); - System.err.println("Init Status: " + result.toString()); - - IDistributionClientResult start = client.start(); - - System.err.println("Start Status: " + start.toString()); - for( int i = 0; i < 2; i++ ){ - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - client.sendComponentDoneStatus(new IComponentDoneStatusMessage() { - - @Override - public long getTimestamp() { - return System.currentTimeMillis(); - } - - @Override - public DistributionStatusEnum getStatus() { - return DistributionStatusEnum.COMPONENT_DONE_OK; - } - - @Override - public String getDistributionID() { - // TODO Auto-generated method stub - return ""; - } - - @Override - public String getConsumerID() { - return client.getConfiguration().getConsumerID(); - } - - @Override - public String getComponentName() { - return "MSO"; - } - }); - } - - } - - private static void soWdListner() { - IDistributionClient client = DistributionClientFactory.createDistributionClient(); - IDistributionClientResult result = client.init(new SimpleConfiguration() { - @Override - public boolean isConsumeProduceStatusTopic() { - return true; - } - }, new SimpleCallback(client) { - @Override - public void activateCallback(INotificationData data) { - System.err.println("Monitor Recieved Notification: " + data.toString()); - - } - }, new IStatusCallback() { - - @Override - public void activateCallback(IStatusData data) { - System.err.println("Monitor Recieved Status: " + data.toString()); - - } - }); - System.err.println("Init Status: " + result.toString()); - IDistributionClientResult start = client.start(); - - System.err.println("Start Status: " + start.toString()); - } - -} diff --git a/sdc-distribution-ci/src/main/java/org/openecomp/test/CsarToscaTester.java b/sdc-distribution-ci/src/main/java/org/openecomp/test/CsarToscaTester.java deleted file mode 100644 index 98072fa..0000000 --- a/sdc-distribution-ci/src/main/java/org/openecomp/test/CsarToscaTester.java +++ /dev/null @@ -1,121 +0,0 @@ -package org.openecomp.test; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; -import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException; -import org.openecomp.sdc.tosca.parser.impl.SdcToscaParserFactory; -import org.openecomp.sdc.tosca.parser.impl.SdcTypes; -import org.openecomp.sdc.toscaparser.api.Group; -import org.openecomp.sdc.toscaparser.api.NodeTemplate; -import org.openecomp.sdc.toscaparser.api.elements.Metadata; -import org.openecomp.sdc.toscaparser.api.parameters.Input; -import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder; - -public class CsarToscaTester { - public static void main(String[] args) throws Exception { - System.out.println("CsarToscaParser - path to CSAR's Directory is " + Arrays.toString(args)); - SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance(); - - File folder = new File(args[0]); - File[] listOfFiles = folder.listFiles(); - Date now = new Date(); - SimpleDateFormat dateFormat = new SimpleDateFormat("d-MM-y-HH_mm_ss"); - String time = dateFormat.format(now); - String csarsDir = args[1] + "/csar-reports-" + time; - File dir = new File(csarsDir); - dir.mkdir(); - - - for (File file : listOfFiles) { - if (file.isFile()) { - System.out.println("File " + file.getAbsolutePath()); - String name = file.getName(); - String currentCsarDir = csarsDir+"/"+name+"-"+time; - dir = new File(currentCsarDir); - dir.mkdir(); - try { - processCsar(factory, file); - } catch (SdcToscaParserException e){ - System.out.println("SdcToscaParserException caught. Code: "+e.getCode()+", message: "+ e.getMessage()); - } - List validationIssueReport = ThreadLocalsHolder.getCollector().getValidationIssueReport(); - System.out.println("Validation issues during CSAR parsing are: " + (validationIssueReport != null ? validationIssueReport.toString() : "none")); - - try { - generateReport(time, name, currentCsarDir, validationIssueReport, "validationIssues"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - } - - } - } - - private static void processCsar(SdcToscaParserFactory factory, File file) throws SdcToscaParserException { - ISdcCsarHelper sdcCsarHelper = factory.getSdcCsarHelper(file.getAbsolutePath()); - //Service level - System.out.println("Invoking sdc-tosca methods on this CSAR...."); - String conformanceLevel = sdcCsarHelper.getConformanceLevel(); - System.out.println("getConformanceLevel() - conformance level is "+conformanceLevel); - String serviceSubstitutionMappingsTypeName = sdcCsarHelper.getServiceSubstitutionMappingsTypeName(); - System.out.println("serviceSubstitutionMappingsTypeName() - subst mappings type of service is "+serviceSubstitutionMappingsTypeName); - List serviceInputs = sdcCsarHelper.getServiceInputs(); - System.out.println("getServiceInputs() - service inputs are "+serviceInputs); - Metadata serviceMetadata = sdcCsarHelper.getServiceMetadata(); - System.out.println("getServiceMetadata() - service metadata is "+serviceMetadata); - Map serviceMetadataProperties = sdcCsarHelper.getServiceMetadataProperties(); - System.out.println("getServiceMetadataProperties() - service metadata properties is "+serviceMetadataProperties); - List allottedResources = sdcCsarHelper.getAllottedResources(); - System.out.println("getAllottedResources() - service allotted resources are "+allottedResources); - List serviceVfList = sdcCsarHelper.getServiceVfList(); - System.out.println("getServiceVfList() - VF list is "+serviceVfList); - List serviceNodeTemplateBySdcType = sdcCsarHelper.getServiceNodeTemplateBySdcType(SdcTypes.VF); - System.out.println("getServiceNodeTemplateBySdcType() - VF list is "+serviceNodeTemplateBySdcType); - List serviceNodeTemplates = sdcCsarHelper.getServiceNodeTemplates(); - System.out.println("getServiceNodeTemplates() - all node templates list of service is "+serviceNodeTemplates); - - serviceVfList.forEach(x -> { - String nodeTemplateCustomizationUuid = sdcCsarHelper.getNodeTemplateCustomizationUuid(x); - System.out.println("getNodeTemplateCustomizationUuid() - VF ID is "+nodeTemplateCustomizationUuid); - String typeOfNodeTemplate = sdcCsarHelper.getTypeOfNodeTemplate(x); - System.out.println("getTypeOfNodeTemplate() - VF tosca type is "+typeOfNodeTemplate); - List vfModulesByVf = sdcCsarHelper.getVfModulesByVf(nodeTemplateCustomizationUuid); - System.out.println("getVfModulesByVf() - VF modules list is "+vfModulesByVf); - vfModulesByVf.forEach(y -> { - List membersOfVfModule = sdcCsarHelper.getMembersOfVfModule(x, y); - System.out.println("getMembersOfVfModule() - members of VfModule are "+membersOfVfModule); - }); - List vfcListByVf = sdcCsarHelper.getVfcListByVf(nodeTemplateCustomizationUuid); - System.out.println("getVfcListByVf() - VFC list is "+vfcListByVf); - vfcListByVf.forEach(z -> { - List nodeTemplateBySdcType = sdcCsarHelper.getNodeTemplateBySdcType(z, SdcTypes.CP); - System.out.println("getNodeTemplateBySdcType() - CP children node templates of this VFC are "+nodeTemplateBySdcType); - Map> cpPropertiesFromVfcAsObject = sdcCsarHelper.getCpPropertiesFromVfcAsObject(z); - System.out.println("getCpPropertiesFromVfcAsObject() - consolidated CP properties for this VFC are "+cpPropertiesFromVfcAsObject); - boolean hasTopology = sdcCsarHelper.hasTopology(z); - System.out.println("hasTopology() - this VFC is "+(hasTopology ? "nested" : "not nested")); - }); - }); - - } - - private static void generateReport(String time, String name, String currentCsarDir, List criticalsReport, String type) - throws IOException { - FileWriter fw; - fw = new FileWriter(new File(currentCsarDir + "/" + criticalsReport.size() + "-"+type+"-" + name +"-"+time + ".txt")); - for (String exception : criticalsReport) { - fw.write(exception); - fw.write("\r\n"); - } - fw.close(); - } -} diff --git a/sdc-distribution-ci/src/main/java/org/openecomp/test/Decoder.java b/sdc-distribution-ci/src/main/java/org/openecomp/test/Decoder.java deleted file mode 100644 index 434952b..0000000 --- a/sdc-distribution-ci/src/main/java/org/openecomp/test/Decoder.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.test; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import org.apache.commons.codec.binary.Base64; - -public class Decoder { - - public static String encode(byte[] byteArrayToEncode) { - return new String(Base64.encodeBase64(byteArrayToEncode)); - } - - public static String decode(String strEncoded) { - return new String(Base64.decodeBase64(strEncoded)); - } - - public static String readFileToString(String file) throws IOException { - - try (FileReader fileReader = new FileReader(file); - BufferedReader reader = new BufferedReader(fileReader)) { - String line; - StringBuilder stringBuilder = new StringBuilder(); - String ls = System.getProperty("line.separator"); - - while ((line = reader.readLine()) != null) { - stringBuilder.append(line); - stringBuilder.append(ls); - } - - reader.close(); - fileReader.close(); - return stringBuilder.toString(); - } catch (IOException e) { - throw new IOException(e); - } - } -} diff --git a/sdc-distribution-ci/src/main/java/org/openecomp/test/NotificationCallback.java b/sdc-distribution-ci/src/main/java/org/openecomp/test/NotificationCallback.java deleted file mode 100644 index 3b2d772..0000000 --- a/sdc-distribution-ci/src/main/java/org/openecomp/test/NotificationCallback.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.test; - -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.notification.INotificationData; - -public class NotificationCallback extends SimpleCallback{ - INotificationData latestCallbackData; - public INotificationData getData() { - return latestCallbackData; - } - public NotificationCallback(IDistributionClient client) { - super(client); - } - - public void activateCallback(INotificationData data) { - this.latestCallbackData = data; - super.activateCallback(data); - } -} diff --git a/sdc-distribution-ci/src/main/java/org/openecomp/test/SimpleCallback.java b/sdc-distribution-ci/src/main/java/org/openecomp/test/SimpleCallback.java deleted file mode 100644 index 0c03bb0..0000000 --- a/sdc-distribution-ci/src/main/java/org/openecomp/test/SimpleCallback.java +++ /dev/null @@ -1,356 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.test; - -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.consumer.IDistributionStatusMessage; -import org.openecomp.sdc.api.consumer.INotificationCallback; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IResourceInstance; -import org.openecomp.sdc.api.notification.IVfModuleMetadata; -import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; -import org.openecomp.sdc.api.results.IDistributionClientResult; -import org.openecomp.sdc.utils.ArtifactTypeEnum; -import org.openecomp.sdc.utils.DistributionActionResultEnum; -import org.openecomp.sdc.utils.DistributionStatusEnum; - -/** - * - * @author tg851x - * This is class used in testing and run locally in the IDE - * logging not needed it is monitored through the IDE console. - */ -public class SimpleCallback implements INotificationCallback { - protected IDistributionClient client; - public List iArtifactInfo; - - public final Map simpleCallbackResults = new HashMap(); - - public Map getSimpleCallbackResults() { - return simpleCallbackResults; - } - - public List getIArtifactInfo(){ - return iArtifactInfo; - } - public SimpleCallback(IDistributionClient client) { - this.client = client; - } - - - - - - public void activateCallback(INotificationData data) { - - List artifacts = getArtifacts(data); - - - for (IArtifactInfo iArtifactInfo : artifacts) { - - IArtifactInfo artifactMetadataByUUID = data.getArtifactMetadataByUUID(iArtifactInfo.getArtifactUUID()); - assertEquals("check artifact checksum", iArtifactInfo.getArtifactChecksum(), artifactMetadataByUUID.getArtifactChecksum()); - System.out.println(artifactMetadataByUUID.getArtifactURL()); - if (artifactMetadataByUUID.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA)){ - IDistributionClientDownloadResult download = client.download(iArtifactInfo); - if (download.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS){ - List decodeVfModuleArtifact = client.decodeVfModuleArtifact(download.getArtifactPayload()); -// assertEquals("decoded not equal to actual group amount ", decodeVfModuleArtifact.size(), 2); - if (!decodeVfModuleArtifact.isEmpty()){ - for (IVfModuleMetadata moduleMetadata : decodeVfModuleArtifact) { - List moduleArtifacts = moduleMetadata.getArtifacts(); - if (moduleArtifacts != null) { - - for (String artifactId : moduleArtifacts) { - - IArtifactInfo artifactInfo = data.getArtifactMetadataByUUID(artifactId); - IDistributionClientDownloadResult downloadArt = client.download(artifactInfo); - assertEquals(downloadArt.getDistributionActionResult(), DistributionActionResultEnum.SUCCESS); - - } - - } - } - } - } - } - } - - - for (IArtifactInfo relevantArtifact : artifacts){ - // Download Artifact - IDistributionClientDownloadResult downloadResult = client.download(relevantArtifact); - - postDownloadLogic(downloadResult); - - - - simpleCallbackResults.put("downloadResult", downloadResult); - System.out.println("downloadResult: " + downloadResult.toString()); - System.out.println("<<<<<<<<<<< Artifact content >>>>>>>>>>"); - System.out.println(Decoder.encode(downloadResult.getArtifactPayload())); - - /////Print artifact content to console/////// - -// byte[] contentInBytes = BaseEncoding.base64().decode(Decoder.encode(downloadResult.getArtifactPayload())); -// try { -// System.out.println("Source content: " + new String(contentInBytes, "UTF-8")); -// } catch (UnsupportedEncodingException e1) { -// // TODO Auto-generated catch block -// e1.printStackTrace(); -// } - System.out.println("ArtInfo_timeout: "+ relevantArtifact.getArtifactTimeout()); - System.out.println("ArtInfo_Art_description: "+ relevantArtifact.getArtifactDescription()); - System.out.println("ArtInfo_Art_CheckSum: "+ relevantArtifact.getArtifactChecksum()); - System.out.println("ArtInfo_Art_Url: "+ relevantArtifact.getArtifactURL()); - System.out.println("ArtInfo_Art_Type: "+ relevantArtifact.getArtifactType()); - System.out.println("ArtInfo_Art_Name: "+ relevantArtifact.getArtifactName()); - System.out.println("ArtInfo_UUID: " + relevantArtifact.getArtifactUUID()); - System.out.println("ArtInfo_Version: " + relevantArtifact.getArtifactVersion()); - System.out.println("ArtInfo_RelatedArtifacts: "+ relevantArtifact.getRelatedArtifacts()); - - System.out.println("ArtInfo_Serv_description: " + data.getServiceDescription()); - System.out.println("ArtInfo_Serv_Name: " + data.getServiceName()); - System.out.println("Get_serviceVersion: " + data.getServiceVersion()); - System.out.println("Get_Service_UUID: " + data.getServiceUUID()); - System.out.println("ArtInfo_DistributionId: " + data.getDistributionID()); - System.out.println("ArtInfo_ServiceInvariantUUID: " + data.getServiceInvariantUUID()); - - - // assertTrue("response code is not 200, returned :" + downloadResult.getDistributionActionResult(), downloadResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS ); - - try { - String payload = new String(downloadResult.getArtifactPayload()); -// System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); -// System.out.println(payload); -// System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); - - } catch (Exception e) { - System.out.println("catch"); -// break; - // TODO: handle exception - } - - - - - if (downloadResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) { - handleSuccessfullDownload(data, relevantArtifact, downloadResult.getArtifactPayload()); - } else { - handleFailedDownload(data, relevantArtifact); - } - } -// if (data != null){ -// iArtifactInfo.addAll(artifacts); -// } - - } - - private List getArtifacts(INotificationData data) { - List ret = new ArrayList(); - List resources = data.getResources(); -// data.getArtifactMetadataByUUID(arg0) - List relevantArtifactTypes = client.getConfiguration().getRelevantArtifactTypes(); - - List collect = resources.stream().flatMap( e -> e.getArtifacts().stream()).filter(p -> relevantArtifactTypes.contains(p.getArtifactType() )).collect(Collectors.toList()); -// if( resources != null ){ -// for( IResourceInstance resourceInstance : resources){ -// if( resourceInstance.getArtifacts() != null ){ -// -// -// -// ret.addAll(resourceInstance.getArtifacts()); -// -// -// } -// } -// } - ret.addAll(collect); - - List servicesArt = data.getServiceArtifacts(); - if( servicesArt != null ){ - ret.addAll(servicesArt); - } - - System.out.println("I am here: " + ret.toString()); - return ret; - } - - - - private void handleFailedDownload(INotificationData data, - IArtifactInfo relevantArtifact) { - // Send Download Status - IDistributionClientResult sendDownloadStatus = client.sendDownloadStatus(buildStatusMessage(client, data, relevantArtifact, DistributionStatusEnum.DOWNLOAD_ERROR)); - postDownloadStatusSendLogic(sendDownloadStatus); - } - - private void handleSuccessfullDownload(INotificationData data, IArtifactInfo relevantArtifact, byte[] payload) { - // Send Download Status - IDistributionClientResult sendDownloadStatus = client.sendDownloadStatus(buildStatusMessage(client, data, relevantArtifact, DistributionStatusEnum.DOWNLOAD_OK)); - - simpleCallbackResults.put("sendDownloadStatus", sendDownloadStatus); -// assertTrue("response code is not 200, returned :" + sendDownloadStatus.getDistributionActionResult(), sendDownloadStatus.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS ); - - // Doing deployment ... - postDownloadStatusSendLogic(sendDownloadStatus); - boolean isDeployedSuccessfully = handleDeployment(data, relevantArtifact, payload); - IDistributionClientResult deploymentStatus; - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - if (isDeployedSuccessfully) { - deploymentStatus = client.sendDeploymentStatus(buildStatusMessage(client, data, relevantArtifact, DistributionStatusEnum.DEPLOY_OK)); - - simpleCallbackResults.put("sendDeploymentStatus", deploymentStatus); -// assertTrue("response code is not 200, returned :" + deploymentStatus.getDistributionActionResult(), deploymentStatus.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS ); - - } else { - deploymentStatus = handleFailedDeployment(data, relevantArtifact); - } - - postDeploymentStatusSendLogic(deploymentStatus); - } - - private IDistributionClientResult handleFailedDeployment(INotificationData data, IArtifactInfo relevantArtifact) { - IDistributionClientResult deploymentStatus; - boolean isAlreadyDeployed = checkIsDeployed(); - if (isAlreadyDeployed) { - deploymentStatus = client.sendDeploymentStatus(buildStatusMessage(client, data, relevantArtifact, DistributionStatusEnum.ALREADY_DEPLOYED)); - } else { - deploymentStatus = client.sendDeploymentStatus(buildStatusMessage(client, data, relevantArtifact, DistributionStatusEnum.DEPLOY_ERROR)); - } - return deploymentStatus; - } - - protected void postDownloadLogic(IDistributionClientDownloadResult downloadResult) { - // TODO Auto-generated method stub - - } - - private void postDownloadStatusSendLogic( - IDistributionClientResult sendDownloadStatus) { - // TODO Auto-generated method stub - - } - - private void postDeploymentStatusSendLogic( - IDistributionClientResult deploymentStatus) { - // TODO Auto-generated method stub - - } - - private boolean checkIsDeployed() { - return false; - } - - private boolean handleDeployment(INotificationData data, IArtifactInfo relevantArtifact, byte[] payload) { - if (relevantArtifact.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())) { - - try { - List serviceArtifacts = data.getServiceArtifacts(); - List resourcesArtifacts = data.getResources(); - - JSONArray jsonData = new JSONArray(new String(payload)); - boolean artifactIsFound = true; - for (int index = 0 ; index < jsonData.length(); index++) { - - JSONObject jsonObject = (JSONObject) jsonData.get(index); - JSONArray artifacts = (JSONArray) jsonObject.get("artifacts"); - for (int i = 0 ; i < artifacts.length(); i++) { - String artifact = artifacts.getString(i).toString(); - - Optional serviceArtifactFound = serviceArtifacts.stream().filter(x -> x.getArtifactUUID().equals(artifact)).findFirst(); - - boolean isResourceFound = false; - for (int j = 0 ; j < resourcesArtifacts.size(); j++) { - Optional resourceArtifactFound = resourcesArtifacts.get(j).getArtifacts().stream().filter(x -> x.getArtifactUUID().equals(artifact)).findFirst(); - isResourceFound = resourceArtifactFound.isPresent() || isResourceFound; - } - - if (!serviceArtifactFound.isPresent() && !isResourceFound) { - artifactIsFound = false; - System.out.println("################ Artifact: " + artifact + " NOT FOUND in Notification Data ################"); - } - } - } - return artifactIsFound; - - } catch (Exception e) { - System.out.println("################ Couldn't convert vf_modules_metadata.json to json : " + e.getMessage()); - return false; - } - } - else { - return true; - } - -// to return deploy_error use return false -// return false; - } - - public static IDistributionStatusMessage buildStatusMessage( - final IDistributionClient client, final INotificationData data, - final IArtifactInfo relevantArtifact, - final DistributionStatusEnum status) { - IDistributionStatusMessage statusMessage = new IDistributionStatusMessage() { - - public long getTimestamp() { - long currentTimeMillis = System.currentTimeMillis(); - return currentTimeMillis; - } - - public DistributionStatusEnum getStatus() { - return status; - } - - public String getDistributionID() { - return data.getDistributionID(); - } - - public String getConsumerID() { - return client.getConfiguration().getConsumerID(); - } - - public String getArtifactURL() { - return relevantArtifact.getArtifactURL(); - } - }; - return statusMessage; - } - - -} diff --git a/sdc-distribution-ci/src/main/java/org/openecomp/test/SimpleConfiguration.java b/sdc-distribution-ci/src/main/java/org/openecomp/test/SimpleConfiguration.java deleted file mode 100644 index 417f564..0000000 --- a/sdc-distribution-ci/src/main/java/org/openecomp/test/SimpleConfiguration.java +++ /dev/null @@ -1,204 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.api.consumer.IConfiguration; - -public class SimpleConfiguration implements IConfiguration{ - - /*public String getUser() - { - return System.getProperty("user"); - } - - public List getRelevantArtifactTypes() { - return ArtifactTypeEnum.getAllTypes(); - } - - public int getPollingTimeout() - { - return 20; - } - - public int getPollingInterval() - { - return 20; - } - - public String getPassword() - { - return System.getProperty("password"); - } - - public String getEnvironmentName() - { - return System.getProperty("env"); - } - - public String getConsumerID() - { - return System.getProperty("consumerID"); - } - - public String getConsumerGroup() - { - return System.getProperty("groupID"); - } - - public String getAsdcAddress() - { - return System.getProperty("beAddress"); - } - - public String getKeyStorePath() - { - return ""; - } - - public String getKeyStorePassword() - { - return "Aa123456"; - } - - public boolean activateServerTLSAuth() - { - return Boolean.parseBoolean(System.getProperty("auth")); -// res.add(ArtifactTypeEnum.HEAT_ARTIFACT); -// res.add(ArtifactTypeEnum.HEAT_ENV); -// res.add(ArtifactTypeEnum.MURANO_PKG); -// res.add(ArtifactTypeEnum.VF_LICENSE); -// res.add(ArtifactTypeEnum.APPC_CONFIG); -// res.add(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE); -// res.add(ArtifactTypeEnum.VNF_CATALOG); -// res.add(ArtifactTypeEnum.APPC_CONFIG); -// res.add(ArtifactTypeEnum.VF_MODULES_METADATA); -// return "PROD-Tedy-Only"; -// return "A-AI"; -// return "A-AI"; - } - - @Override - public boolean isFilterInEmptyResources() { - return false; - } - - public static String downloadPath() { - return "c:\\temp\\"; - } - - public static Boolean toDownload() { - return false; - }*/ - - public String getUser() { - return "ci"; - } - - public List getRelevantArtifactTypes() { - -// List res = new ArrayList(); -// for (ArtifactTypeEnum type : AssetTypeEnum.values()){ -// res.add(type.name()); -// } - return ArtifactTypeEnum.getAllTypes(); - } - - - public int getPollingTimeout() { - return 20; - } - - public int getPollingInterval() { - return 20; - } - - public String getPassword() { - return "123456"; - } - - public String getEnvironmentName() { - return "PROD"; - } - - public String getConsumerID() { - return "consumerVasya"; - } - - public String getConsumerGroup() { - return "groupVasya"; - - } - - public static Boolean toDownload() { - return true; - } - - public static String downloadPath() { - return "c:\\temp\\"; - } - - public String getAsdcAddress() { - return "127.0.0.1:8443"; - } - - @Override - public List getMsgBusAddress() { - return new ArrayList<>(); - } - - @Override - public String getKeyStorePath() { - return StringUtils.EMPTY; - } - - @Override - public String getKeyStorePassword() { - - return "Aa123456"; - } - - @Override - public boolean activateServerTLSAuth() { - - return false; - } - - @Override - public boolean isFilterInEmptyResources() { - return false; - } - - @Override - public Boolean isUseHttpsWithDmaap() { - return true; - } - - @Override - public boolean isConsumeProduceStatusTopic() { - return false; - } - -} diff --git a/sdc-distribution-ci/src/main/resources/ci/conf/attsdc-packages.yaml b/sdc-distribution-ci/src/main/resources/ci/conf/attsdc-packages.yaml index 34a78d9..65a38fa 100644 --- a/sdc-distribution-ci/src/main/resources/ci/conf/attsdc-packages.yaml +++ b/sdc-distribution-ci/src/main/resources/ci/conf/attsdc-packages.yaml @@ -1,10 +1,10 @@ packages: - - org.openecomp.sdc.ci.tests.execute.general - - org.openecomp.sdc.ci.tests.execute.user - - org.openecomp.sdc.ci.tests.execute.property - - org.openecomp.sdc.ci.tests.execute.lifecycle - - org.openecomp.sdc.ci.tests.execute.resource - - org.openecomp.sdc.ci.tests.execute.service - - org.openecomp.sdc.ci.tests.execute.artifacts - - org.openecomp.sdc.ci.tests.execute.imports - - org.openecomp.sdc.ci.tests.execute.category \ No newline at end of file + - org.onap.sdc.ci.tests.execute.general + - org.onap.sdc.ci.tests.execute.user + - org.onap.sdc.ci.tests.execute.property + - org.onap.sdc.ci.tests.execute.lifecycle + - org.onap.sdc.ci.tests.execute.resource + - org.onap.sdc.ci.tests.execute.service + - org.onap.sdc.ci.tests.execute.artifacts + - org.onap.sdc.ci.tests.execute.imports + - org.onap.sdc.ci.tests.execute.category \ No newline at end of file diff --git a/sdc-distribution-ci/src/main/resources/ci/conf/log4j.properties b/sdc-distribution-ci/src/main/resources/ci/conf/log4j.properties index 3e159ec..bef72a9 100644 --- a/sdc-distribution-ci/src/main/resources/ci/conf/log4j.properties +++ b/sdc-distribution-ci/src/main/resources/ci/conf/log4j.properties @@ -28,7 +28,7 @@ log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %10c: log4j.logger.org.apache.cassandra.service.StorageProxy=DEBUG log4j.logger.com.thinkaurelius.titan.diskstorage.cassandra.CassandraTransaction=INFO, FILE, stdout -log4j.logger.org.openecomp.sdc.ci.tests.utils=TRACE, FILE, stdout -log4j.additivity.org.openecomp.sdc.ci.tests.utils=false +log4j.logger.org.onap.sdc.ci.tests.utils=TRACE, FILE, stdout +log4j.additivity.org.onap.sdc.ci.tests.utils=false diff --git a/sdc-distribution-ci/src/main/resources/ci/scripts/startTest.sh b/sdc-distribution-ci/src/main/resources/ci/scripts/startTest.sh index 604903a..7fa5323 100644 --- a/sdc-distribution-ci/src/main/resources/ci/scripts/startTest.sh +++ b/sdc-distribution-ci/src/main/resources/ci/scripts/startTest.sh @@ -33,7 +33,7 @@ LOGS_PROP_FILE=file:${FULL_PATH}/conf/log4j.properties TARGET_DIR=${FULL_PATH}/target CONF_FILE=${FULL_PATH}/conf/attsdc.yaml DEBUG=true -MainClass=org.openecomp.sdc.ci.tests.run.StartTest +MainClass=org.onap.sdc.ci.tests.run.StartTest JAR_FILE=$1 diff --git a/sdc-distribution-ci/src/test/java/org/onap/sdc/ci/tests/execute/downloadArtifactUGN/ClientDownloadArtifact.java b/sdc-distribution-ci/src/test/java/org/onap/sdc/ci/tests/execute/downloadArtifactUGN/ClientDownloadArtifact.java new file mode 100644 index 0000000..22b1607 --- /dev/null +++ b/sdc-distribution-ci/src/test/java/org/onap/sdc/ci/tests/execute/downloadArtifactUGN/ClientDownloadArtifact.java @@ -0,0 +1,511 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.ci.tests.execute.downloadArtifactUGN; + +import org.junit.Test; + +/** + * + * @author al714h + * US510007 - Story : ASDC Distr Client - Download Artifact + * following test set partially cover the US451327 - Story : API to download the specific artifact, cover the audit message. + */ + +//public class ClientDownloadArtifact extends AttSdcTest{ + public class ClientDownloadArtifact { + +// Logger logger = null; +// +// DistributionUtils distributionUtils = new DistributionUtils(); +// DownloadArtifactDetails downloadArtifactDetails = new DownloadArtifactDetails(); +// Utils utils = new Utils(); +// DbUtils dbUtils = new DbUtils(); +// UserUtils userUtils = new UserUtils(); +// ResourceUtils resourceUtils = new ResourceUtils(); +// ServiceUtils serviceUtils = new ServiceUtils(); +// ArtifactUtils artifactUtils = new ArtifactUtils(); +// private JSONParser jsonParser = new JSONParser(); +// + String serviceBaseVersion = "0.1"; +// +// @Before +// public void before() throws Exception { +// +// distributionUtils.resetInit(); +// dbUtils.cleanAllAudits(); +// } +// @Rule +// public static TestName name = new TestName(); +// +// } +// +// @Rule +// public static TestName name = new TestName(); +// +//// public ClientDownloadArtifact() { +//// super(name, ClientDownloadArtifact.class.getName()); +//// } +// +// ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); +//// get default artifact info to upload +// ArtifactDefinition uploadedResourceArtifactInfo = artifactUtils.constructDefaultArtifactInfo(); +//// set artifact info for download +// downloadArtifactDetails.setArtifactName(uploadedResourceArtifactInfo.getArtifactName()); +// String artifactName = downloadArtifactDetails.getArtifactName(); +//// Andrey TODO String resourceArtifactUrl = String.format(Urls.DOWNLOAD_RESOURCE_ARTIFACT,); +// +// int numOfResourcArtifacts = 1; +// RestResponse createCertifiedResourceWithArtifacts = resourceUtils.createCertifiedResourceWithArtifacts(resourceDetails, uploadedResourceArtifactInfo, numOfResourcArtifacts); +// +// +// +// try{ +// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); +// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); +// distributionUtils.verifyDownloadedArtifact(downloadArtifactRestResponse, uploadedResourceArtifactInfo); +// +// // validate audit message server side +// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); +// String action = "ArtifactDownload"; +// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); +// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); +// }finally{ +//// delete created resource +// resourceUtils.deleteResource_allVersions(resourceDetails, UserUtils.getAdminDetails()); +// } + +// } + +// send all mandatory headers only + @Test + public void downloadServiceArtifactSuccess() throws Exception{ + +//// ServiceReqDetails serviceDetails = serviceUtils.createDefaultDetailsService(); +// ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); +// Service service = new Service(); +// try{ +//// get default artifact info to upload +// ArtifactDefinition uploadedResourceArtifactInfo = artifactUtils.constructDefaultArtifactInfo(); +// uploadedResourceArtifactInfo.setArtifactType(ArtifactTypeEnum.HEAT.getType()); +// ArtifactDefinition uploadedServiceArtifactInfo = artifactUtils.constructDefaultArtifactInfo(); +// uploadedServiceArtifactInfo.setArtifactType(ArtifactTypeEnum.MURANO_PKG.getType()); +// +//// set artifact info for download +// downloadArtifactDetails.setArtifactName(uploadedServiceArtifactInfo.getArtifactName()); +// downloadArtifactDetails.setArtifactType(ArtifactTypeEnum.MURANO_PKG.getType()); +// String artifactName = downloadArtifactDetails.getArtifactName(); +// +//// create default resource details +// ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); +// +// int numOfResourcArtifacts = 1; +// service = serviceUtils.createCertifiedServiceWithResourceInstanceAndArtifacts(serviceDetails, resourceDetails, uploadedResourceArtifactInfo, uploadedServiceArtifactInfo , numOfResourcArtifacts); +// logger.debug("service version = " + service.getVersion()); +// logger.debug("service distribution status = " + service.getDistributionStatus()); +// RestResponse changeDistributionStateToApprove = serviceUtils.changeDistributionStateToApprove(service, UserUtils.getGovernorDetails1()); +// +// int status = changeDistributionStateToApprove.getErrorCode(); +// assertTrue("response code is not 200, returned :" + status, status == 200); +// +// serviceDetails.setVersion(service.getVersion()); +// serviceDetails.setUniqueId(service.getUniqueId()); +// +// String responseString = changeDistributionStateToApprove.getResponse(); +// Gson gson = new Gson(); +// service = gson.fromJson(responseString, Service.class); +// ServiceMetadataDataDefinition serviceMetadataDataDefinition = gson.fromJson(responseString, ServiceMetadataDataDefinition.class); +// service.setDistributionStatus(DistributionStatusEnum.findState(serviceMetadataDataDefinition.getDistributionStatus())); +// DistributionStatusEnum distributionStatus = service.getDistributionStatus(); +// assertNotNull("distribution state is null",distributionStatus.name()); +// assertTrue("the default distribution state is invalid", DistributionStatusEnum.DISTRIBUTION_APPROVED.equals(distributionStatus)); +// +// String serviceArtifactUrl = String.format(Urls.DISTRIBUTION_DOWNLOAD_ARTIFACT,service.getName(), service.getVersion(), artifactName); +// logger.debug("download service artifact url: "+ serviceArtifactUrl+ " serviceName = " + service.getName() + " service version = " + service.getVersion() + "service artifact name = " + artifactName); +// +// +//// Log.debug("artifact detailes: "+ downloadArtifactDetails.toString()); +//// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); +//// distributionUtils.verifyDownloadedArtifact(downloadArtifactRestResponse, uploadedArtifactInfo); +//// +//// // validate audit message server side +//// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); +//// String action = "ArtifactDownload"; +//// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); +//// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); +// }finally{ +//// delete created service +// serviceUtils.deleteService_allVersions(serviceDetails, UserUtils.getAdminDetails()); +// } + +// @Test +// public void downloadServiceArtifactSuccess() throws Exception{ +// +//// ServiceReqDetails serviceDetails = serviceUtils.createDefaultDetailsService(); +// ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); +// Service service = new Service(); +// try{ +//// get default artifact info to upload +// ArtifactDefinition uploadedResourceArtifactInfo = artifactUtils.constructDefaultArtifactInfo(); +// uploadedResourceArtifactInfo.setArtifactType(ArtifactTypeEnum.HEAT.getType()); +// ArtifactDefinition uploadedServiceArtifactInfo = artifactUtils.constructDefaultArtifactInfo(); +// uploadedServiceArtifactInfo.setArtifactType(ArtifactTypeEnum.MURANO_PKG.getType()); +// +//// set artifact info for download +// downloadArtifactDetails.setArtifactName(uploadedServiceArtifactInfo.getArtifactName()); +// downloadArtifactDetails.setArtifactType(ArtifactTypeEnum.MURANO_PKG.getType()); +// String artifactName = downloadArtifactDetails.getArtifactName(); +// +//// create default resource details +// ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); +// +// int numOfResourcArtifacts = 1; +// service = serviceUtils.createCertifiedServiceWithResourceInstanceAndArtifacts(serviceDetails, resourceDetails, uploadedResourceArtifactInfo, uploadedServiceArtifactInfo , numOfResourcArtifacts); +// logger.debug("service version = " + service.getVersion()); +// logger.debug("service distribution status = " + service.getDistributionStatus()); +// RestResponse changeDistributionStateToApprove = serviceUtils.changeDistributionStateToApprove(service, UserUtils.getGovernorDetails1()); +// +// int status = changeDistributionStateToApprove.getErrorCode(); +// assertTrue("response code is not 200, returned :" + status, status == 200); +// +// serviceDetails.setVersion(service.getVersion()); +// serviceDetails.setUniqueId(service.getUniqueId()); +// +// String responseString = changeDistributionStateToApprove.getResponse(); +// Gson gson = new Gson(); +// service = gson.fromJson(responseString, Service.class); +// ServiceMetadataDataDefinition serviceMetadataDataDefinition = gson.fromJson(responseString, ServiceMetadataDataDefinition.class); +// service.setDistributionStatus(DistributionStatusEnum.findState(serviceMetadataDataDefinition.getDistributionStatus())); +// DistributionStatusEnum distributionStatus = service.getDistributionStatus(); +// assertNotNull("distribution state is null",distributionStatus.name()); +// assertTrue("the default distribution state is invalid", DistributionStatusEnum.DISTRIBUTION_APPROVED.equals(distributionStatus)); +// +// String serviceArtifactUrl = String.format(Urls.DISTRIBUTION_DOWNLOAD_ARTIFACT,service.getName(), service.getVersion(), artifactName); +// logger.debug("download service artifact url: "+ serviceArtifactUrl+ " serviceName = " + service.getName() + " service version = " + service.getVersion() + "service artifact name = " + artifactName); +// +// +//// Log.debug("artifact detailes: "+ downloadArtifactDetails.toString()); +//// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); +//// distributionUtils.verifyDownloadedArtifact(downloadArtifactRestResponse, uploadedArtifactInfo); +//// +//// // validate audit message server side +//// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); +//// String action = "ArtifactDownload"; +//// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); +//// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); +// }finally{ +//// delete created service +// serviceUtils.deleteService_allVersions(serviceDetails, UserUtils.getAdminDetails()); +// } +// +// } +// +//// Andrey not relevant, dev ci should cover, qa can't influence on sending headers +////// send all headers mandatory and not mandatory +//// @Test +//// public void downloadArtifactSuccessMandatoryAndNotMandatoryHeaders() throws Exception{ +//// +//// Log.debug("artifact detailes: "+ downloadArtifactDetails.toString()); +//// +//// Map headersMap = new HashMap(); +//// headersMap.put(HttpHeaderEnum.X_ECOMP_InstanceID.getValue(), "instar_name"); // mandatory +//// headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), "usernamePassword"); // mandatory +//// headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/octet-stream"); // not mandatory +//// headersMap.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(),downloadArtifactDetails.getResourceUUID());// not mandatory +//// Log.debug("headers detailes: "+ headersMap.toString()); +//// +//// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, headersMap); +//// distributionUtils.verifyDownloadedArtifact(downloadArtifactRestResponse); +//// +////// validate audit message server side +//// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); +//// String action = "ArtifactDownload"; +//// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); +//// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); +//// +//// } +// +// +////---------------------------------Failure scenario-------------------------------------------------------------------------------- +// +//// Andrey not relevant, dev ci should cover, qa can't influence on sending headers +////// missing InstanceID mandatory header +//// @Test +//// public void downloadArtifactMissingInstanceIdHeader() throws Exception, JSONException{ +//// +//// Log.debug("artifact detailes: "+ downloadArtifactDetails.toString()); +//// +//// Map headersMap = new HashMap(); +//// headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), "usernamePassword"); // mandatory +//// Log.debug("headers detailes: "+ headersMap.toString()); +//// +//// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, headersMap); +//// +//// ErrorInfo errorInfo = utils.parseYaml(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID.name()); +//// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); +//// +//// List variables = Arrays.asList(); +//// utils.checkBodyResponseOnError(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID.name(), variables, downloadArtifactRestResponse.getResponse())); +//// +//// } +// +//// Andrey not relevant, dev ci should cover, qa can't influence on sending headers +////// missing Authorization mandatory header +//// @Test +//// public void downloadArtifactMissingAuthorizationHeader() throws Exception, JSONException{ +//// +//// Log.debug("artifact detailes: "+ downloadArtifactDetails.toString()); +//// +//// Map headersMap = new HashMap(); +//// headersMap.put(HttpHeaderEnum.X_ECOMP_InstanceID.getValue(), "usernamePassword"); // mandatory +//// Log.debug("headers detailes: "+ headersMap.toString()); +//// +//// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, headersMap); +//// +//// ErrorInfo errorInfo = utils.parseYaml(ActionStatus.ECOMP_RESEND_WITH_BASIC_AUTHENTICATION_CREDENTIALS.name()); +//// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); +//// +//// List variables = Arrays.asList(); +//// utils.checkBodyResponseOnError(ActionStatus.ECOMP_RESEND_WITH_BASIC_AUTHENTICATION_CREDENTIALS.name(), variables, downloadArtifactRestResponse.getResponse())); +//// +//// } +// +// +//// artifact not found +// @Test +// public void downloadArtifactArtifactNotFound() throws Exception, JSONException{ +// +// downloadArtifactDetails.setArtifactName("artifactNotExist"); +// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); +// +// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); +// +// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND.name()); +// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); +// +// List variables = Arrays.asList(); +// utils.checkBodyResponseOnError(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse()); +// +//// validate audit message server side +// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); +// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString()); +// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found"; +// expectedArtifactDownloadAuditMessageInfo.setDesc(desc); +// +// String action = "ArtifactDownload"; +// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); +// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); +// +// } +// +//// service not found +// @Test +// public void downloadArtifactServiceNameNotFound() throws Exception, JSONException{ +// +// downloadArtifactDetails.setArtifactURL("/sdc/v1/services/serviceNotExist/0.1/artifacts/aaa.hh"); +// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); +// +// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); +// +// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.SERVICE_NOT_FOUND.name()); +// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); +// +// List variables = Arrays.asList(); +// utils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse()); +// +//// validate audit message server side +// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); +// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString()); +//// TODO Andrey, change desc message +// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found"; +// expectedArtifactDownloadAuditMessageInfo.setDesc(desc); +// +// String action = "ArtifactDownload"; +// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); +// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); +// +// } +// +// +//// service version not found +// @Test +// public void downloadArtifactServiceVersionNotFound() throws Exception, JSONException{ +// +// downloadArtifactDetails.setArtifactURL("/sdc/v1/services/serviceName/0.888/artifacts/aaa.hh"); +// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); +// +// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); +// +// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.COMPONENT_VERSION_NOT_FOUND.name()); +// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); +// +// List variables = Arrays.asList(); +// utils.checkBodyResponseOnError(ActionStatus.COMPONENT_VERSION_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse()); +// +//// validate audit message server side +// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); +// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString()); +//// TODO Andrey, change desc message +// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found"; +// expectedArtifactDownloadAuditMessageInfo.setDesc(desc); +// +// String action = "ArtifactDownload"; +// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); +// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); +// +// } +// +//// invalid HTTP method, PUT HTTP method +// @Test +// public void downloadArtifactByPutMethod() throws Exception, JSONException{ +// +// String method = "PUT"; +// +// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); +// +// RestResponse downloadArtifactRestResponse = distributionUtils.sendDownloadedArtifactByMethod(downloadArtifactDetails, null, method); +// +// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name()); +// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); +// +// List variables = Arrays.asList(); +// utils.checkBodyResponseOnError(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name(), variables, downloadArtifactRestResponse.getResponse()); +// +// } +// +//// invalid HTTP method, DELETE HTTP method +// @Test +// public void downloadArtifactByDeleteMethod() throws Exception, JSONException{ +// +// String method = "DELETE"; +// downloadArtifactDetails.setArtifactName("artifactNotExist"); +// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); +// +// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); +// +// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND.name()); +// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); +// +// List variables = Arrays.asList(); +// utils.checkBodyResponseOnError(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse()); +// +//// validate audit message server side +// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); +// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString()); +// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found"; +// expectedArtifactDownloadAuditMessageInfo.setDesc(desc); +// +// String action = "ArtifactDownload"; +// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); +// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); +// +// downloadArtifactDetails.setArtifactURL("/sdc/v1/services/serviceNotExist/0.1/artifacts/aaa.hh"); +// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); +// +// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); +// +// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.SERVICE_NOT_FOUND.name()); +// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); +// +// List variables = Arrays.asList(); +// utils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse()); +// +//// validate audit message server side +// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); +// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString()); +//// TODO Andrey, change desc message +// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found"; +// expectedArtifactDownloadAuditMessageInfo.setDesc(desc); +// +// String action = "ArtifactDownload"; +// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); +// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); +// downloadArtifactDetails.setArtifactURL("/sdc/v1/services/serviceName/0.888/artifacts/aaa.hh"); +// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); +// +// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); +// +// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.COMPONENT_VERSION_NOT_FOUND.name()); +// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); +// +// List variables = Arrays.asList(); +// utils.checkBodyResponseOnError(ActionStatus.COMPONENT_VERSION_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse()); +// +//// validate audit message server side +// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); +// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString()); +//// TODO Andrey, change desc message +// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found"; +// expectedArtifactDownloadAuditMessageInfo.setDesc(desc); +// +// String action = "ArtifactDownload"; +// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); +// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); +// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); +// +// RestResponse downloadArtifactRestResponse = distributionUtils.sendDownloadedArtifactByMethod(downloadArtifactDetails, null, method); +// +// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name()); +// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); +// +// List variables = Arrays.asList(); +// utils.checkBodyResponseOnError(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name(), variables, downloadArtifactRestResponse.getResponse()); +// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); +// +// RestResponse downloadArtifactRestResponse = distributionUtils.sendDownloadedArtifactByMethod(downloadArtifactDetails, null, method); +// +// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name()); +// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); +// +// List variables = Arrays.asList(); +// utils.checkBodyResponseOnError(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name(), variables, downloadArtifactRestResponse.getResponse()); +// downloadArtifactDetails.setArtifactChecksum("invalidChecksum"); +// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); +// +// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); +//// TODO +// +//// ErrorInfo errorInfo = utils.parseYaml(ActionStatus.SPECIFIED_SERVICE_RESOURCE_VERSION_NOT_FOUND.name()); +//// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); +//// +//// List variables = Arrays.asList(); +//// utils.checkBodyResponseOnError(ActionStatus.SPECIFIED_SERVICE_RESOURCE_VERSION_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse())); +// +// downloadArtifactDetails.setArtifactChecksum("invalidChecksum"); +// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); +// +// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); +//// TODO +// +//// ErrorInfo errorInfo = utils.parseYaml(ActionStatus.SPECIFIED_SERVICE_RESOURCE_VERSION_NOT_FOUND.name()); +//// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); +//// +//// List variables = Arrays.asList(); +//// utils.checkBodyResponseOnError(ActionStatus.SPECIFIED_SERVICE_RESOURCE_VERSION_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse())); +// +// } +// +// +// +// + + } + +} diff --git a/sdc-distribution-ci/src/test/java/org/openecomp/sdc/ci/tests/execute/downloadArtifactUGN/ClientDownloadArtifact.java b/sdc-distribution-ci/src/test/java/org/openecomp/sdc/ci/tests/execute/downloadArtifactUGN/ClientDownloadArtifact.java deleted file mode 100644 index e52223d..0000000 --- a/sdc-distribution-ci/src/test/java/org/openecomp/sdc/ci/tests/execute/downloadArtifactUGN/ClientDownloadArtifact.java +++ /dev/null @@ -1,511 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.ci.tests.execute.downloadArtifactUGN; - -import org.junit.Test; - -/** - * - * @author al714h - * US510007 - Story : ASDC Distr Client - Download Artifact - * following test set partially cover the US451327 - Story : API to download the specific artifact, cover the audit message. - */ - -//public class ClientDownloadArtifact extends AttSdcTest{ - public class ClientDownloadArtifact { - -// Logger logger = null; -// -// DistributionUtils distributionUtils = new DistributionUtils(); -// DownloadArtifactDetails downloadArtifactDetails = new DownloadArtifactDetails(); -// Utils utils = new Utils(); -// DbUtils dbUtils = new DbUtils(); -// UserUtils userUtils = new UserUtils(); -// ResourceUtils resourceUtils = new ResourceUtils(); -// ServiceUtils serviceUtils = new ServiceUtils(); -// ArtifactUtils artifactUtils = new ArtifactUtils(); -// private JSONParser jsonParser = new JSONParser(); -// - String serviceBaseVersion = "0.1"; -// -// @Before -// public void before() throws Exception { -// -// distributionUtils.resetInit(); -// dbUtils.cleanAllAudits(); -// } -// @Rule -// public static TestName name = new TestName(); -// -// } -// -// @Rule -// public static TestName name = new TestName(); -// -//// public ClientDownloadArtifact() { -//// super(name, ClientDownloadArtifact.class.getName()); -//// } -// -// ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); -//// get default artifact info to upload -// ArtifactDefinition uploadedResourceArtifactInfo = artifactUtils.constructDefaultArtifactInfo(); -//// set artifact info for download -// downloadArtifactDetails.setArtifactName(uploadedResourceArtifactInfo.getArtifactName()); -// String artifactName = downloadArtifactDetails.getArtifactName(); -//// Andrey TODO String resourceArtifactUrl = String.format(Urls.DOWNLOAD_RESOURCE_ARTIFACT,); -// -// int numOfResourcArtifacts = 1; -// RestResponse createCertifiedResourceWithArtifacts = resourceUtils.createCertifiedResourceWithArtifacts(resourceDetails, uploadedResourceArtifactInfo, numOfResourcArtifacts); -// -// -// -// try{ -// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); -// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); -// distributionUtils.verifyDownloadedArtifact(downloadArtifactRestResponse, uploadedResourceArtifactInfo); -// -// // validate audit message server side -// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); -// String action = "ArtifactDownload"; -// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); -// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); -// }finally{ -//// delete created resource -// resourceUtils.deleteResource_allVersions(resourceDetails, UserUtils.getAdminDetails()); -// } - -// } - -// send all mandatory headers only - @Test - public void downloadServiceArtifactSuccess() throws Exception{ - -//// ServiceReqDetails serviceDetails = serviceUtils.createDefaultDetailsService(); -// ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); -// Service service = new Service(); -// try{ -//// get default artifact info to upload -// ArtifactDefinition uploadedResourceArtifactInfo = artifactUtils.constructDefaultArtifactInfo(); -// uploadedResourceArtifactInfo.setArtifactType(ArtifactTypeEnum.HEAT.getType()); -// ArtifactDefinition uploadedServiceArtifactInfo = artifactUtils.constructDefaultArtifactInfo(); -// uploadedServiceArtifactInfo.setArtifactType(ArtifactTypeEnum.MURANO_PKG.getType()); -// -//// set artifact info for download -// downloadArtifactDetails.setArtifactName(uploadedServiceArtifactInfo.getArtifactName()); -// downloadArtifactDetails.setArtifactType(ArtifactTypeEnum.MURANO_PKG.getType()); -// String artifactName = downloadArtifactDetails.getArtifactName(); -// -//// create default resource details -// ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); -// -// int numOfResourcArtifacts = 1; -// service = serviceUtils.createCertifiedServiceWithResourceInstanceAndArtifacts(serviceDetails, resourceDetails, uploadedResourceArtifactInfo, uploadedServiceArtifactInfo , numOfResourcArtifacts); -// logger.debug("service version = " + service.getVersion()); -// logger.debug("service distribution status = " + service.getDistributionStatus()); -// RestResponse changeDistributionStateToApprove = serviceUtils.changeDistributionStateToApprove(service, UserUtils.getGovernorDetails1()); -// -// int status = changeDistributionStateToApprove.getErrorCode(); -// assertTrue("response code is not 200, returned :" + status, status == 200); -// -// serviceDetails.setVersion(service.getVersion()); -// serviceDetails.setUniqueId(service.getUniqueId()); -// -// String responseString = changeDistributionStateToApprove.getResponse(); -// Gson gson = new Gson(); -// service = gson.fromJson(responseString, Service.class); -// ServiceMetadataDataDefinition serviceMetadataDataDefinition = gson.fromJson(responseString, ServiceMetadataDataDefinition.class); -// service.setDistributionStatus(DistributionStatusEnum.findState(serviceMetadataDataDefinition.getDistributionStatus())); -// DistributionStatusEnum distributionStatus = service.getDistributionStatus(); -// assertNotNull("distribution state is null",distributionStatus.name()); -// assertTrue("the default distribution state is invalid", DistributionStatusEnum.DISTRIBUTION_APPROVED.equals(distributionStatus)); -// -// String serviceArtifactUrl = String.format(Urls.DISTRIBUTION_DOWNLOAD_ARTIFACT,service.getName(), service.getVersion(), artifactName); -// logger.debug("download service artifact url: "+ serviceArtifactUrl+ " serviceName = " + service.getName() + " service version = " + service.getVersion() + "service artifact name = " + artifactName); -// -// -//// Log.debug("artifact detailes: "+ downloadArtifactDetails.toString()); -//// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); -//// distributionUtils.verifyDownloadedArtifact(downloadArtifactRestResponse, uploadedArtifactInfo); -//// -//// // validate audit message server side -//// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); -//// String action = "ArtifactDownload"; -//// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); -//// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); -// }finally{ -//// delete created service -// serviceUtils.deleteService_allVersions(serviceDetails, UserUtils.getAdminDetails()); -// } - -// @Test -// public void downloadServiceArtifactSuccess() throws Exception{ -// -//// ServiceReqDetails serviceDetails = serviceUtils.createDefaultDetailsService(); -// ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); -// Service service = new Service(); -// try{ -//// get default artifact info to upload -// ArtifactDefinition uploadedResourceArtifactInfo = artifactUtils.constructDefaultArtifactInfo(); -// uploadedResourceArtifactInfo.setArtifactType(ArtifactTypeEnum.HEAT.getType()); -// ArtifactDefinition uploadedServiceArtifactInfo = artifactUtils.constructDefaultArtifactInfo(); -// uploadedServiceArtifactInfo.setArtifactType(ArtifactTypeEnum.MURANO_PKG.getType()); -// -//// set artifact info for download -// downloadArtifactDetails.setArtifactName(uploadedServiceArtifactInfo.getArtifactName()); -// downloadArtifactDetails.setArtifactType(ArtifactTypeEnum.MURANO_PKG.getType()); -// String artifactName = downloadArtifactDetails.getArtifactName(); -// -//// create default resource details -// ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); -// -// int numOfResourcArtifacts = 1; -// service = serviceUtils.createCertifiedServiceWithResourceInstanceAndArtifacts(serviceDetails, resourceDetails, uploadedResourceArtifactInfo, uploadedServiceArtifactInfo , numOfResourcArtifacts); -// logger.debug("service version = " + service.getVersion()); -// logger.debug("service distribution status = " + service.getDistributionStatus()); -// RestResponse changeDistributionStateToApprove = serviceUtils.changeDistributionStateToApprove(service, UserUtils.getGovernorDetails1()); -// -// int status = changeDistributionStateToApprove.getErrorCode(); -// assertTrue("response code is not 200, returned :" + status, status == 200); -// -// serviceDetails.setVersion(service.getVersion()); -// serviceDetails.setUniqueId(service.getUniqueId()); -// -// String responseString = changeDistributionStateToApprove.getResponse(); -// Gson gson = new Gson(); -// service = gson.fromJson(responseString, Service.class); -// ServiceMetadataDataDefinition serviceMetadataDataDefinition = gson.fromJson(responseString, ServiceMetadataDataDefinition.class); -// service.setDistributionStatus(DistributionStatusEnum.findState(serviceMetadataDataDefinition.getDistributionStatus())); -// DistributionStatusEnum distributionStatus = service.getDistributionStatus(); -// assertNotNull("distribution state is null",distributionStatus.name()); -// assertTrue("the default distribution state is invalid", DistributionStatusEnum.DISTRIBUTION_APPROVED.equals(distributionStatus)); -// -// String serviceArtifactUrl = String.format(Urls.DISTRIBUTION_DOWNLOAD_ARTIFACT,service.getName(), service.getVersion(), artifactName); -// logger.debug("download service artifact url: "+ serviceArtifactUrl+ " serviceName = " + service.getName() + " service version = " + service.getVersion() + "service artifact name = " + artifactName); -// -// -//// Log.debug("artifact detailes: "+ downloadArtifactDetails.toString()); -//// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); -//// distributionUtils.verifyDownloadedArtifact(downloadArtifactRestResponse, uploadedArtifactInfo); -//// -//// // validate audit message server side -//// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); -//// String action = "ArtifactDownload"; -//// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); -//// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); -// }finally{ -//// delete created service -// serviceUtils.deleteService_allVersions(serviceDetails, UserUtils.getAdminDetails()); -// } -// -// } -// -//// Andrey not relevant, dev ci should cover, qa can't influence on sending headers -////// send all headers mandatory and not mandatory -//// @Test -//// public void downloadArtifactSuccessMandatoryAndNotMandatoryHeaders() throws Exception{ -//// -//// Log.debug("artifact detailes: "+ downloadArtifactDetails.toString()); -//// -//// Map headersMap = new HashMap(); -//// headersMap.put(HttpHeaderEnum.X_ECOMP_InstanceID.getValue(), "instar_name"); // mandatory -//// headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), "usernamePassword"); // mandatory -//// headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/octet-stream"); // not mandatory -//// headersMap.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(),downloadArtifactDetails.getResourceUUID());// not mandatory -//// Log.debug("headers detailes: "+ headersMap.toString()); -//// -//// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, headersMap); -//// distributionUtils.verifyDownloadedArtifact(downloadArtifactRestResponse); -//// -////// validate audit message server side -//// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); -//// String action = "ArtifactDownload"; -//// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); -//// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); -//// -//// } -// -// -////---------------------------------Failure scenario-------------------------------------------------------------------------------- -// -//// Andrey not relevant, dev ci should cover, qa can't influence on sending headers -////// missing InstanceID mandatory header -//// @Test -//// public void downloadArtifactMissingInstanceIdHeader() throws Exception, JSONException{ -//// -//// Log.debug("artifact detailes: "+ downloadArtifactDetails.toString()); -//// -//// Map headersMap = new HashMap(); -//// headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), "usernamePassword"); // mandatory -//// Log.debug("headers detailes: "+ headersMap.toString()); -//// -//// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, headersMap); -//// -//// ErrorInfo errorInfo = utils.parseYaml(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID.name()); -//// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); -//// -//// List variables = Arrays.asList(); -//// utils.checkBodyResponseOnError(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID.name(), variables, downloadArtifactRestResponse.getResponse())); -//// -//// } -// -//// Andrey not relevant, dev ci should cover, qa can't influence on sending headers -////// missing Authorization mandatory header -//// @Test -//// public void downloadArtifactMissingAuthorizationHeader() throws Exception, JSONException{ -//// -//// Log.debug("artifact detailes: "+ downloadArtifactDetails.toString()); -//// -//// Map headersMap = new HashMap(); -//// headersMap.put(HttpHeaderEnum.X_ECOMP_InstanceID.getValue(), "usernamePassword"); // mandatory -//// Log.debug("headers detailes: "+ headersMap.toString()); -//// -//// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, headersMap); -//// -//// ErrorInfo errorInfo = utils.parseYaml(ActionStatus.ECOMP_RESEND_WITH_BASIC_AUTHENTICATION_CREDENTIALS.name()); -//// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); -//// -//// List variables = Arrays.asList(); -//// utils.checkBodyResponseOnError(ActionStatus.ECOMP_RESEND_WITH_BASIC_AUTHENTICATION_CREDENTIALS.name(), variables, downloadArtifactRestResponse.getResponse())); -//// -//// } -// -// -//// artifact not found -// @Test -// public void downloadArtifactArtifactNotFound() throws Exception, JSONException{ -// -// downloadArtifactDetails.setArtifactName("artifactNotExist"); -// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); -// -// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); -// -// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND.name()); -// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); -// -// List variables = Arrays.asList(); -// utils.checkBodyResponseOnError(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse()); -// -//// validate audit message server side -// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); -// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString()); -// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found"; -// expectedArtifactDownloadAuditMessageInfo.setDesc(desc); -// -// String action = "ArtifactDownload"; -// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); -// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); -// -// } -// -//// service not found -// @Test -// public void downloadArtifactServiceNameNotFound() throws Exception, JSONException{ -// -// downloadArtifactDetails.setArtifactURL("/sdc/v1/services/serviceNotExist/0.1/artifacts/aaa.hh"); -// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); -// -// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); -// -// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.SERVICE_NOT_FOUND.name()); -// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); -// -// List variables = Arrays.asList(); -// utils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse()); -// -//// validate audit message server side -// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); -// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString()); -//// TODO Andrey, change desc message -// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found"; -// expectedArtifactDownloadAuditMessageInfo.setDesc(desc); -// -// String action = "ArtifactDownload"; -// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); -// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); -// -// } -// -// -//// service version not found -// @Test -// public void downloadArtifactServiceVersionNotFound() throws Exception, JSONException{ -// -// downloadArtifactDetails.setArtifactURL("/sdc/v1/services/serviceName/0.888/artifacts/aaa.hh"); -// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); -// -// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); -// -// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.COMPONENT_VERSION_NOT_FOUND.name()); -// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); -// -// List variables = Arrays.asList(); -// utils.checkBodyResponseOnError(ActionStatus.COMPONENT_VERSION_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse()); -// -//// validate audit message server side -// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); -// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString()); -//// TODO Andrey, change desc message -// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found"; -// expectedArtifactDownloadAuditMessageInfo.setDesc(desc); -// -// String action = "ArtifactDownload"; -// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); -// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); -// -// } -// -//// invalid HTTP method, PUT HTTP method -// @Test -// public void downloadArtifactByPutMethod() throws Exception, JSONException{ -// -// String method = "PUT"; -// -// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); -// -// RestResponse downloadArtifactRestResponse = distributionUtils.sendDownloadedArtifactByMethod(downloadArtifactDetails, null, method); -// -// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name()); -// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); -// -// List variables = Arrays.asList(); -// utils.checkBodyResponseOnError(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name(), variables, downloadArtifactRestResponse.getResponse()); -// -// } -// -//// invalid HTTP method, DELETE HTTP method -// @Test -// public void downloadArtifactByDeleteMethod() throws Exception, JSONException{ -// -// String method = "DELETE"; -// downloadArtifactDetails.setArtifactName("artifactNotExist"); -// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); -// -// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); -// -// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND.name()); -// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); -// -// List variables = Arrays.asList(); -// utils.checkBodyResponseOnError(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse()); -// -//// validate audit message server side -// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); -// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString()); -// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found"; -// expectedArtifactDownloadAuditMessageInfo.setDesc(desc); -// -// String action = "ArtifactDownload"; -// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); -// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); -// -// downloadArtifactDetails.setArtifactURL("/sdc/v1/services/serviceNotExist/0.1/artifacts/aaa.hh"); -// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); -// -// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); -// -// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.SERVICE_NOT_FOUND.name()); -// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); -// -// List variables = Arrays.asList(); -// utils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse()); -// -//// validate audit message server side -// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); -// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString()); -//// TODO Andrey, change desc message -// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found"; -// expectedArtifactDownloadAuditMessageInfo.setDesc(desc); -// -// String action = "ArtifactDownload"; -// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); -// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); -// downloadArtifactDetails.setArtifactURL("/sdc/v1/services/serviceName/0.888/artifacts/aaa.hh"); -// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); -// -// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); -// -// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.COMPONENT_VERSION_NOT_FOUND.name()); -// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); -// -// List variables = Arrays.asList(); -// utils.checkBodyResponseOnError(ActionStatus.COMPONENT_VERSION_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse()); -// -//// validate audit message server side -// ArtifactDownloadAuditMessageInfo expectedArtifactDownloadAuditMessageInfo = distributionUtils.constructDefaultArtifactDownloadAuditMessageInfo(); -// expectedArtifactDownloadAuditMessageInfo.setStatus(errorInfo.getCode().toString()); -//// TODO Andrey, change desc message -// String desc = "Error: Artifact " + downloadArtifactDetails.getArtifactName() + " was not found"; -// expectedArtifactDownloadAuditMessageInfo.setDesc(desc); -// -// String action = "ArtifactDownload"; -// ArtifactDownloadAuditMessageInfo actualArtifactDownloadAuditMessageInfo = userUtils.parseDestributionAuditRespByAction(action); -// distributionUtils.validateArtifactDownloadAuditMessage(actualArtifactDownloadAuditMessageInfo, expectedArtifactDownloadAuditMessageInfo); -// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); -// -// RestResponse downloadArtifactRestResponse = distributionUtils.sendDownloadedArtifactByMethod(downloadArtifactDetails, null, method); -// -// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name()); -// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); -// -// List variables = Arrays.asList(); -// utils.checkBodyResponseOnError(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name(), variables, downloadArtifactRestResponse.getResponse()); -// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); -// -// RestResponse downloadArtifactRestResponse = distributionUtils.sendDownloadedArtifactByMethod(downloadArtifactDetails, null, method); -// -// ErrorInfo errorInfo = utils.parseErrorConfigYaml(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name()); -// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); -// -// List variables = Arrays.asList(); -// utils.checkBodyResponseOnError(ActionStatus.METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT.name(), variables, downloadArtifactRestResponse.getResponse()); -// downloadArtifactDetails.setArtifactChecksum("invalidChecksum"); -// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); -// -// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); -//// TODO -// -//// ErrorInfo errorInfo = utils.parseYaml(ActionStatus.SPECIFIED_SERVICE_RESOURCE_VERSION_NOT_FOUND.name()); -//// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); -//// -//// List variables = Arrays.asList(); -//// utils.checkBodyResponseOnError(ActionStatus.SPECIFIED_SERVICE_RESOURCE_VERSION_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse())); -// -// downloadArtifactDetails.setArtifactChecksum("invalidChecksum"); -// logger.debug("artifact detailes: "+ downloadArtifactDetails.toString()); -// -// RestResponse downloadArtifactRestResponse = distributionUtils.sendGetDownloadedArtifact(downloadArtifactDetails, null); -//// TODO -// -//// ErrorInfo errorInfo = utils.parseYaml(ActionStatus.SPECIFIED_SERVICE_RESOURCE_VERSION_NOT_FOUND.name()); -//// assertEquals("Check response code after artifact download request", errorInfo.getCode(), downloadArtifactRestResponse.getErrorCode()); -//// -//// List variables = Arrays.asList(); -//// utils.checkBodyResponseOnError(ActionStatus.SPECIFIED_SERVICE_RESOURCE_VERSION_NOT_FOUND.name(), variables, downloadArtifactRestResponse.getResponse())); -// -// } -// -// -// -// - - } - -} diff --git a/sdc-distribution-client/pom.xml b/sdc-distribution-client/pom.xml index d39e24f..4833175 100644 --- a/sdc-distribution-client/pom.xml +++ b/sdc-distribution-client/pom.xml @@ -4,9 +4,9 @@ 4.0.0 - org.openecomp.sdc.sdc-distribution-client + org.onap.sdc.sdc-distribution-client sdc-main-distribution-client - 1.2.3-SNAPSHOT + 1.3.0-SNAPSHOT sdc-distribution-client diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/IDistributionClient.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/IDistributionClient.java new file mode 100644 index 0000000..d3a8188 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/IDistributionClient.java @@ -0,0 +1,210 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.api; + +import java.util.List; + +import org.onap.sdc.api.consumer.*; +import org.onap.sdc.api.results.IDistributionClientDownloadResult; +import org.onap.sdc.api.results.IDistributionClientResult; +import org.onap.sdc.api.consumer.*; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.IVfModuleMetadata; + +public interface IDistributionClient { + + /** + * Update the configuration of the distribution client
+ * Updatable configuration parameters are: pollingInterval, pollingTimeout, + * consumerGroup and relevantArtifactTypes + * + * @param newConf + * - contains updated configuration + * + * @return IDistributionClientResult + */ + IDistributionClientResult updateConfiguration(IConfiguration newConf); + + /** + * Retrieve the configuration of the distribution client
+ * + * @return IConfiguration + */ + IConfiguration getConfiguration(); + + /** + * Start distribution client
+ * - start polling notification topic
+ * + * @return IDistributionClientResult + */ + IDistributionClientResult start(); + + /** + * Stop distribution client
+ * - stop polling notification topic
+ * - unregister topics (via ASDC)
+ * - delete keys from UEB + * + * @return IDistributionClientResult + */ + IDistributionClientResult stop(); + + /** + * Downloads an artifact from ASDC Catalog
+ * + * @param artifactInfo + * @return IDistributionClientDownloadResult + */ + IDistributionClientDownloadResult download(IArtifactInfo artifactInfo); + + /** + * Initialize the distribution client
+ * - fetch the UEB server list from ASDC
+ * - create keys in UEB
+ * - register for topics (via ASDC)
+ * - set the notification callback
+ * + * Note: all configuration fields are mandatory.
+ * Password must be in clear text and not encrypted
+ * ONAP-Component MUST store password as SHA-2 (256) hashed with + * dynamically generated salt value
+ * + * @param conf + * @param callback + * @return IDistributionClientResult + */ + IDistributionClientResult init(IConfiguration conf, INotificationCallback callback); + + /** + * Initialize the distribution client
+ * - fetch the UEB server list from ASDC
+ * - create keys in UEB
+ * - register for topics (via ASDC)
+ * - set the notification callback
+ * + * Note: all configuration fields are mandatory.
+ * Password must be in clear text and not encrypted
+ * ONAP-Component MUST store password as SHA-2 (256) hashed with + * dynamically generated salt value
+ * + * @param conf + * @param notificationCallback + * @param statusCallback + * @return IDistributionClientResult + */ + IDistributionClientResult init(IConfiguration conf, INotificationCallback notificationCallback, + IStatusCallback statusCallback); + + /** + * Build and publish Distribution Download Status event to Distribution + * Status Topic + * + * @param statusMessage + * @return IDistributionClientResult + */ + IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage statusMessage); + + /** + * Build and publish Distribution Download Status event to Distribution + * Status Topic With Error Reason. + * + * @param statusMessage + * @param errorReason + * @return IDistributionClientResult + */ + IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage statusMessage, String errorReason); + + /** + * Build and publish Distribution Deployment Status event to Distribution + * Status Topic + * + * @param statusMessage + * @return IDistributionClientResult + */ + IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage statusMessage); + + /** + * Build and publish Distribution Deployment Status event to Distribution + * Status Topic With Error Reason. + * + * @param statusMessage + * @param errorReason + * @return IDistributionClientResult + */ + IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage statusMessage, String errorReason); + + /** + * Build and publish Distribution Component Status event to Distribution + * Status Topic + * + * @param statusMessage + * @return IDistributionClientResult + */ + IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage); + + /** + * Build and publish Distribution Component Status event to Distribution + * Status Topic With Error Reason. + * + * @param statusMessage + * @param errorReason + * @return IDistributionClientResult + */ + IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage, String errorReason); + + + /** + * Build and publish Distribution Final Status event to Distribution + * Status Topic + * + * @param statusMessage + * @return IDistributionClientResult + */ + IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage); + + + /** + * Build and publish Distribution Final Status event to Distribution + * Status Topic With Error Reason. + * + * @param statusMessage + * @param errorReason + * @return IDistributionClientResult + */ + IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage, String errorReason); + + + /** + * This method parses artifact of type VF_MODULES_METADATA payload data + * .
+ * Method is deprecated due to VF Module changes. Only backward + * compatibility is supported.
+ * + * @param artifactPayload + * @return IVfModuleMetadata list + */ + @Deprecated + List decodeVfModuleArtifact(byte[] artifactPayload); + + + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/IDistributionStatusMessageJsonBuilder.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/IDistributionStatusMessageJsonBuilder.java new file mode 100644 index 0000000..6db00fa --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/IDistributionStatusMessageJsonBuilder.java @@ -0,0 +1,25 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.api; + +public interface IDistributionStatusMessageJsonBuilder { + String build(); +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/RegistrationRequest.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/RegistrationRequest.java new file mode 100644 index 0000000..6e64396 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/RegistrationRequest.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.api.asdc; + +import java.util.List; + +public class RegistrationRequest { + + String apiPublicKey; + String distrEnvName; + Boolean isConsumerToSdcDistrStatusTopic; + List distEnvEndPoints; + + public RegistrationRequest(String apiPublicKey, String distrEnvName, boolean isConsumerToSdcDistrStatusTopic, List distEnvEndPoints) { + this.apiPublicKey = apiPublicKey; + this.distrEnvName = distrEnvName; + this.isConsumerToSdcDistrStatusTopic = isConsumerToSdcDistrStatusTopic; + this.distEnvEndPoints = distEnvEndPoints; + } + + public String getApiPublicKey() { + return apiPublicKey; + } + + public String getDistrEnvName() { + return distrEnvName; + } + + public Boolean getIsConsumerToSdcDistrStatusTopic() { + return isConsumerToSdcDistrStatusTopic; + } + + public List getDistEnvEndPoints() { + return distEnvEndPoints; + } + + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/ServerListResponse.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/ServerListResponse.java new file mode 100644 index 0000000..8d3b823 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/ServerListResponse.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.api.asdc; + +import java.util.List; + +public class ServerListResponse { + + private List uebServerList; + + public List getUebServerList() { + return uebServerList; + } + + public void setUebServerList(List uebServerList) { + this.uebServerList = uebServerList; + } +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IComponentDoneStatusMessage.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IComponentDoneStatusMessage.java new file mode 100644 index 0000000..e9b4359 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IComponentDoneStatusMessage.java @@ -0,0 +1,7 @@ +package org.onap.sdc.api.consumer; + +public interface IComponentDoneStatusMessage extends IDistributionStatusMessageBasic { + String getComponentName(); + default String getArtifactURL(){return "";} + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IConfiguration.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IConfiguration.java new file mode 100644 index 0000000..c5a1857 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IConfiguration.java @@ -0,0 +1,157 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.api.consumer; + +import java.util.List; +import org.onap.sdc.api.notification.INotificationData; + +public interface IConfiguration { + /** + * SDC Distribution Engine address. Value can be either hostname (with or + * without port), IP:port or FQDN (Fully Qualified Domain Name). * @return + * SDC Distribution Engine address. + */ + String getAsdcAddress(); + + /**SDC Distribution Addresses from ONAP Component + * Values need to be set from impl + */ + List getMsgBusAddress(); + + /** + * User Name for SDC distribution consumer authentication. + * + * @return User Name. + */ + String getUser(); + + /** + * User Password for SDC distribution consumer authentication. + * + * @return User Password. + */ + String getPassword(); + + /** + * Distribution Client Polling Interval towards UEB in seconds. Can Be + * reconfigured in runtime. + * + * @return Distribution Client Polling Interval. + */ + int getPollingInterval(); + + /** + * Distribution Client Timeout in seconds waiting to UEB server response in + * each fetch interval. Can Be reconfigured in runtime. + * + * @return Distribution Client Timeout in seconds. + */ + int getPollingTimeout(); + + /** + * List of artifact types.
+ * If the service contains any of the artifacts in the list, the callback + * will be activated. Can Be reconfigured in runtime. + * + * @return List of artifact types. + */ + List getRelevantArtifactTypes(); + + /** + * Returns the consumer group defined for this ECOMP component, if no + * consumer group is defined return null. + * + * @return Consumer group. + */ + String getConsumerGroup(); + + /** + * Returns the environment name (testing, production etc...). Can Be + * reconfigured in runtime. + * + * @return + */ + String getEnvironmentName(); + + /** + * Unique ID of ECOMP component instance (e.x INSTAR name). + * + * @return + */ + String getConsumerID(); + + /** + * Return full path to Client's Key Store that contains either CA + * certificate or the ASDC's public key (e.g /etc/keystore/asdc-client.jks) + * file will be deployed with sdc-distribution jar. + * + * @return + */ + String getKeyStorePath(); + + /** + * @return Returns client's Key Store password + */ + String getKeyStorePassword(); + + /** + * Sets whether SDC server TLS authentication is activated. If set to false, + * Key Store path and password are not needed to be set. + * + * @return + */ + boolean activateServerTLSAuth(); + + /** + * If set to true the method {@link INotificationData#getResources()} will + * return all found resources.
+ * That means that metadata of resources that do not contain relevant + * artifacts types (artifacts that are defined in + * {@link #getRelevantArtifactTypes()} will be returned.
+ * Setting the method to false will activate the legacy behavior, in which + * empty resources are not part of the notification.
+ * + * @return + */ + boolean isFilterInEmptyResources(); + + /** + * By default, Distribution Client will use HTTPS (TLS 1.2) when connecting + * to DMAAP. This param can be null, then default (HTTPS) behavior will be + * applied. If set to false, distribution client will use HTTP when + * connecting to DMAAP. + * + * @return + */ + Boolean isUseHttpsWithDmaap(); + + /** + * By default, (false value) Distribution Client will trigger the regular registration + * towards SDC (register component as consumer to the SDC-DISTR-NOTIF-TOPIC-[ENV] topic and register component as producer to the SDC-DISTR-STATUS-TOPIC-[ENV]).
+ * If set to true, distribution client trigger Register to SDC indicating + * that this component request to be consumer and producer of the + * SDC-DISTR-STATUS-TOPIC-[ENV] topic.
+ * @return + */ + default boolean isConsumeProduceStatusTopic() { + return false; + } +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IDistributionStatusMessage.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IDistributionStatusMessage.java new file mode 100644 index 0000000..fd73bac --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IDistributionStatusMessage.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.api.consumer; + +public interface IDistributionStatusMessage extends IDistributionStatusMessageBasic{ + + /**Resource URL of the downloaded/deployed artifact - URL specified in the distribution notification message*/ + String getArtifactURL(); + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IDistributionStatusMessageBasic.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IDistributionStatusMessageBasic.java new file mode 100644 index 0000000..59dcc57 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IDistributionStatusMessageBasic.java @@ -0,0 +1,28 @@ +package org.onap.sdc.api.consumer; + +import org.onap.sdc.utils.DistributionStatusEnum; + +public interface IDistributionStatusMessageBasic { + /** + * Distribution ID published in the distribution notification.
+ * Should be used to link the distribution status reports to the appropriate + * distribution activation.
+ * Global Distribution Identifier: UUID generated by SDC per each + * distribution activation.
+ * Generated UUID is compliant with RFC 4122. It is a 128-bit value + * formatted into blocks of hexadecimal digits separated by a hyphen ("-"). + * Ex.: AA97B177-9383-4934-8543-0F91A7A02836 + */ + String getDistributionID(); + + /**Unique ID of ONAP component instance (e.x INSTAR name)*/ + String getConsumerID(); + + /** + * Timestamp of the distribution status report creation.
+ * The number of seconds that have elapsed since January 1, 1970. + */ + long getTimestamp(); + /**Download/Deployment status*/ + DistributionStatusEnum getStatus(); +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IFinalDistrStatusMessage.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IFinalDistrStatusMessage.java new file mode 100644 index 0000000..0869a67 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IFinalDistrStatusMessage.java @@ -0,0 +1,9 @@ +package org.onap.sdc.api.consumer; + + + +public interface IFinalDistrStatusMessage extends IDistributionStatusMessageBasic{ + + default String getConsumerID(){return "";} + default String getComponentName(){return "";} +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/INotificationCallback.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/INotificationCallback.java new file mode 100644 index 0000000..5121407 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/INotificationCallback.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.api.consumer; + +import org.onap.sdc.api.notification.INotificationData; +/**When a relevant notification will be found activateCallback method will be activated with the notification data.
+ * Please implement it according to your desired callback logic.*/ +public interface INotificationCallback { + void activateCallback(INotificationData data); +} + diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IStatusCallback.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IStatusCallback.java new file mode 100644 index 0000000..5bcc4a2 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IStatusCallback.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.api.consumer; + +import org.onap.sdc.api.notification.IStatusData; + +/** + * When a relevant status will be found activateCallback method will be + * activated with the status data.
+ * Please implement it according to your desired callback logic. + */ +@FunctionalInterface +public interface IStatusCallback { + void activateCallback(IStatusData data); + + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IArtifactInfo.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IArtifactInfo.java new file mode 100644 index 0000000..8c34185 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IArtifactInfo.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.api.notification; + +import java.util.List; + + +public interface IArtifactInfo { + + /** + * @return String of the Artifact File Name. + */ + String getArtifactName(); + + /** + * Artifact Type.
+ * Following are valid values : HEAT , DG_XML.
+ * List of values will be extended in post-1510 releases. + * + * @return String of the artifact type. + */ + String getArtifactType(); + + /** + * Relative artifact's URL. Should be used in REST GET API to download the artifact's payload.
+ * The full artifact URL will be in the following format :
+ * https://{serverBaseURL}/{resourcePath}
+ * serverBaseURL - Hostname ( SDC LB FQDN) + optional port
+ * resourcePath - "artifactURL"
+ * Ex : https://sdc.com/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml + * + * @return String of the Relative artifact's URL. + */ + String getArtifactURL(); + + /** + * Base-64 encoded MD5 checksum of the artifact's payload.
+ * Should be used for data integrity validation when an artifact's payload is downloaded.
+ * + * @return String of the checksum of the artifact's payload. + */ + String getArtifactChecksum(); + + /** + * Installation timeout in minutes.
+ * Used by the Orchestrator to determine how much time to wait for a heat (or other deployment artifact)
+ * This field is only relevant for artifacts of ArtifactTypeEnum HEAT, for other artifacts it will be null.
+ * deployment process to finish.
+ * + * @return String of the Installation timeout in minutes. + */ + Integer getArtifactTimeout(); + + /** + * Artifact description + * @return + */ + String getArtifactDescription(); + + /** + * Artifact Version + * @return + */ + String getArtifactVersion(); + + /** + * Artifact Unique ID + * @return + */ + String getArtifactUUID(); + + + /** + * Returns the artifact it is generated from (relevant for heat_env), or null if there is no such artifact. + * @return + */ + IArtifactInfo getGeneratedArtifact(); + + /** + * Returns the list of related artifacts (relevant for HEAT_NESTED or HEAT_ARTIFACT), or null if there is no such artifacts. + * @return + */ + List getRelatedArtifacts(); + + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/INotificationData.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/INotificationData.java new file mode 100644 index 0000000..ecc4a5b --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/INotificationData.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.api.notification; + +import java.util.List; + + + + + +public interface INotificationData { + /** Global Distribution Identifier: UUID generated by ASDC per each distribution activation.
+ * Generated UUID is compliant with RFC 4122.
+ * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").
+ Ex.: AA97B177-9383-4934-8543-0F91A7A02836 */ + String getDistributionID(); + + /**Logical Service Name.*/ + String getServiceName(); + + /** Service Version.
+ * Two dot (".") separated digit blocks.
+ Ex. : "2.0"*/ + String getServiceVersion(); + + /**Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.
+ It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").
+ Ex. : AA97B177-9383-4934-8543-0F91A7A02836*/ + String getServiceUUID(); + + /** + * Service description + */ + String getServiceDescription(); + + /** List of the resource instances */ + List getResources(); + + /** List of Artifacts On Service Level */ + List getServiceArtifacts(); + + /**This method allows getting details of the artifact by its uuid.*/ + IArtifactInfo getArtifactMetadataByUUID(String artifactUUID); + + /** + * Invariant UUID + */ + String getServiceInvariantUUID(); + + String getWorkloadContext(); + + void setWorkloadContext(String workloadContext); +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IResourceInstance.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IResourceInstance.java new file mode 100644 index 0000000..0cc3ca4 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IResourceInstance.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.api.notification; + +import java.util.List; + +public interface IResourceInstance { + /**Logical Resource Instance Name.
+ * Unique Identifier of the instance of the specific resource in the service context.**/ + String getResourceInstanceName(); + + /**resource name */ + String getResourceName(); + + /**resource version */ + String getResourceVersion(); + + /**Resource Type (For Example: VF (Virtual Function) - A subsystem in a service, it can include one or more VFCs. This is what NFV spec refers as VNF.)**/ + String getResourceType(); + + /**Global UUID of the resource that specific artifact belongs to.
+ It is generated by SDC per each resource version.
+ Generated UUID is compliant with RFC 4122. It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").
+ Ex.: AA97B177-9383-4934-8543-0F91A7A02836**/ + String getResourceUUID(); + + /**List of resource instance deployment artifacts.**/ + List getArtifacts(); + + /**Invariant (constant) resource UUID generated on resource creation.**/ + String getResourceInvariantUUID(); + + /**This UUID is unique in the context of the service.
+ It is regenerated whenever a designer makes changes to the resource instance.
+ A change may be updating HEAT value, updating property value or name of the resource instance.
+ It is also regenerated when an artifact is uploaded to the resource instance.**/ + String getResourceCustomizationUUID(); + + /**The category of the resource model.
+ E.g. "Application L4+".**/ + String getCategory(); + + /**The subcategory of the resource model.
+ E.g. "Call Control"**/ + String getSubcategory(); + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IStatusData.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IStatusData.java new file mode 100644 index 0000000..734c200 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IStatusData.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.api.notification; + +import org.onap.sdc.utils.DistributionStatusEnum; + +public interface IStatusData { + /** + * Global Distribution Identifier: UUID generated by SDC per each + * distribution activation.
+ * Generated UUID is compliant with RFC 4122.
+ * It is a 128-bit value formatted into blocks of hexadecimal digits + * separated by a hyphen ("-").
+ * Ex.: AA97B177-9383-4934-8543-0F91A7A02836 + */ + String getDistributionID(); + + /** Unique ID of ONAP component instance (e.x INSTAR name). */ + String getConsumerID(); + + /** The predefined ONAP component name configured on the component. */ + String getComponentName(); + + /** + * Timestamp of the distribution status report creation. The number of + * seconds that have elapsed since January 1, 1970 + */ + Long getTimestamp(); + /** + * Resource URL of the downloaded/deployed artifact - URL specified in the + * distribution notification message. + */ + String getArtifactURL(); + /** + * Status Event type + */ + DistributionStatusEnum getStatus(); + /** + * Error Reason describing the Status Event. + */ + String getErrorReason(); + + + + + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IVfModuleMetadata.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IVfModuleMetadata.java new file mode 100644 index 0000000..3613c94 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IVfModuleMetadata.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.api.notification; + +import java.util.List; +/**VF Module in the resource (VF) context*/ +public interface IVfModuleMetadata { + /**Logical VF Module Name. Unique Identifier of VF Module in the resource (VF) context.
+ Ex. : "PCRF-module-0" + */ + String getVfModuleModelName(); + + /**Invariant VF Module UUID generated on VF Module creation according to RFC 4122
+ It is generated on service creation and stays invariant even if service name /version are updated. + */ + String getVfModuleModelInvariantUUID(); + + /** + Resource Version . Ex. : "1" + */ + String getVfModuleModelVersion(); + + /**Global UUID of the VF Module.
+ It is generated by ASDC per each new VF module version. Generated UUID is compliant with RFC 4122. It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").
+ Ex.: AA97B177-9383-4934-8543-0F91A7A02836 + */ + String getVfModuleModelUUID(); + + + /** + * VF Module textual description. Can be empty. + */ + String getVfModuleModelDescription(); + + + /** + * Is this VF module is the base module of the VF. + * */ + boolean isBase(); + + /** + * Array of VF Module deployment artifacts UUID. + * */ + List getArtifacts(); +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/results/IDistributionClientDownloadResult.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/results/IDistributionClientDownloadResult.java new file mode 100644 index 0000000..47fe023 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/results/IDistributionClientDownloadResult.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.api.results; + +/**Distribution Client Result For Download API*/ +public interface IDistributionClientDownloadResult extends IDistributionClientResult{ + + + byte[] getArtifactPayload(); + + + /** + * @deprecated + * This method is deprecated and will be removed in 1710. + * It returns attachment; filename="filename" rather than "filename". + * Please use {@link #getArtifactFilename()}. + * @return + */ + @Deprecated + String getArtifactName(); + + /** + * Returns the filename of the artifact. + * @return the filename of the artifact. + */ + String getArtifactFilename(); +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/results/IDistributionClientResult.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/results/IDistributionClientResult.java new file mode 100644 index 0000000..4f33555 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/results/IDistributionClientResult.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.api.results; + +import org.onap.sdc.utils.DistributionActionResultEnum; +/**General Distribution Client Result*/ +public interface IDistributionClientResult { + DistributionActionResultEnum getDistributionActionResult(); + String getDistributionMessageResult(); +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/http/AsdcUrls.java b/sdc-distribution-client/src/main/java/org/onap/sdc/http/AsdcUrls.java new file mode 100644 index 0000000..72a51d3 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/http/AsdcUrls.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.http; + +public class AsdcUrls { + + public static final String GET_CLUSTER_SERVER_LIST = "/sdc/v1/distributionUebCluster"; + public static final String GET_VALID_ARTIFACT_TYPES = "/sdc/v1/artifactTypes"; + public static final String POST_FOR_TOPIC_REGISTRATION = "/sdc/v1/registerForDistribution"; + public static final String POST_FOR_UNREGISTER = "/sdc/v1/unRegisterForDistribution"; + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/http/HttpAsdcClient.java b/sdc-distribution-client/src/main/java/org/onap/sdc/http/HttpAsdcClient.java new file mode 100644 index 0000000..c241bec --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/http/HttpAsdcClient.java @@ -0,0 +1,351 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.http; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.ConnectException; +import java.net.UnknownHostException; +import java.security.KeyStore; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +import org.apache.commons.codec.binary.Base64; +import org.apache.http.Header; +import org.apache.http.HttpEntity; +import org.apache.http.HttpStatus; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.ssl.TrustStrategy; +import org.onap.sdc.api.consumer.IConfiguration; +import org.onap.sdc.utils.Pair; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HttpAsdcClient implements IHttpAsdcClient { + + private static final String TLS = "TLSv1.2"; + private static final String AUTHORIZATION_HEADER = "Authorization"; + private static final String HTTPS = "https://"; + private static Logger log = LoggerFactory.getLogger(HttpAsdcClient.class.getName()); + private CloseableHttpClient httpClient = null; + private String serverFqdn = null; + private String authHeaderValue = ""; + + public HttpAsdcClient(IConfiguration configuraion) { + this.serverFqdn = configuraion.getAsdcAddress(); + + String username = configuraion.getUser(); + String password = configuraion.getPassword(); + initSSL(username, password, configuraion.getKeyStorePath(), configuraion.getKeyStorePassword(), configuraion.activateServerTLSAuth()); + + String userNameAndPassword = username + ":" + password; + this.authHeaderValue = "Basic " + Base64.encodeBase64String(userNameAndPassword.getBytes()); + } + + // @SuppressWarnings("deprecation") + private void initSSL(String username, String password, String keyStorePath, String keyStoePass, boolean isSupportSSLVerification) { + + try { + HostnameVerifier hostnameVerifier = new HostnameVerifier() { + + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + + // SSLContextBuilder is not thread safe + // @SuppressWarnings("deprecation") + CredentialsProvider credsProvider = new BasicCredentialsProvider(); + credsProvider.setCredentials(new AuthScope("localhost", 443), new UsernamePasswordCredentials(username, password)); + SSLContext sslContext; + sslContext = SSLContext.getInstance(TLS); + TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + KeyStore trustStore = null; + tmf.init(trustStore); + TrustManager[] tms = tmf.getTrustManagers(); + if (isSupportSSLVerification) { + + if (keyStorePath != null && !keyStorePath.isEmpty()) { + // trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + // trustStore.load(new FileInputStream(keyStorePath), keyStoePass.toCharArray()); + + // Using null here initialises the TMF with the default trust store. + + // Get hold of the default trust manager + X509TrustManager defaultTm = null; + for (TrustManager tm : tmf.getTrustManagers()) { + if (tm instanceof X509TrustManager) { + defaultTm = (X509TrustManager) tm; + break; + } + } + + // Do the same with your trust store this time + // Adapt how you load the keystore to your needs + trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(new FileInputStream(keyStorePath), keyStoePass.toCharArray()); + + tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(trustStore); + + // Get hold of the default trust manager + X509TrustManager myTm = null; + for (TrustManager tm : tmf.getTrustManagers()) { + if (tm instanceof X509TrustManager) { + myTm = (X509TrustManager) tm; + break; + } + } + + // Wrap it in your own class. + final X509TrustManager finalDefaultTm = defaultTm; + final X509TrustManager finalMyTm = myTm; + X509TrustManager customTm = new X509TrustManager() { + @Override + public X509Certificate[] getAcceptedIssuers() { + // If you're planning to use client-cert auth, + // merge results from "defaultTm" and "myTm". + return finalDefaultTm.getAcceptedIssuers(); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + try { + finalMyTm.checkServerTrusted(chain, authType); + } catch (CertificateException e) { + // This will throw another CertificateException if this fails too. + finalDefaultTm.checkServerTrusted(chain, authType); + } + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + // If you're planning to use client-cert auth, + // do the same as checking the server. + finalDefaultTm.checkClientTrusted(chain, authType); + } + }; + + tms = new TrustManager[] { customTm }; + + } + + sslContext.init(null, tms, null); + SSLContext.setDefault(sslContext); + + + + } else { + + SSLContextBuilder builder = new SSLContextBuilder(); + + builder.loadTrustMaterial(null, new TrustStrategy() { + public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { + return true; + } + }); + + sslContext = builder.build(); + } + + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" }, null, hostnameVerifier); + httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).setSSLSocketFactory(sslsf).build(); + + } catch (Exception e) { + log.error("Failed to create https client", e); + + } + + return; + } + + public HttpAsdcResponse postRequest(String requestUrl, HttpEntity entity, Map headersMap) { + return postRequest(requestUrl, entity, headersMap, true).getFirst(); + } + + public Pair postRequest(String requestUrl, HttpEntity entity, Map headersMap, boolean closeTheRequest) { + Pair ret; + CloseableHttpResponse httpResponse = null; + HttpAsdcResponse response = null; + HttpPost httpPost = new HttpPost(HTTPS + serverFqdn + requestUrl); + List
headers = addHeadersToHttpRequest(headersMap); + for (Header header : headers) { + httpPost.addHeader(header); + } + + httpPost.setHeader(AUTHORIZATION_HEADER, this.authHeaderValue); + + httpPost.setEntity(entity); + try { + httpResponse = httpClient.execute(httpPost); + response = new HttpAsdcResponse(httpResponse.getStatusLine().getStatusCode(), httpResponse.getEntity()); + + } catch (IOException e) { + log.error("failed to send request to url: " + requestUrl); + StringEntity errorEntity = null; + try { + errorEntity = new StringEntity("failed to send request"); + } catch (UnsupportedEncodingException e1) { + } + + response = new HttpAsdcResponse(500, errorEntity); + + } finally { + if (closeTheRequest) { + if (httpResponse != null) { + try { + httpResponse.close(); + + } catch (IOException e) { + log.error("failed to close http response"); + } + } + ret = new Pair<>(response, null); + } else { + ret = new Pair<>(response, httpResponse); + } + } + + return ret; + } + + public HttpAsdcResponse getRequest(String requestUrl, Map headersMap) { + + return getRequest(requestUrl, headersMap, true).getFirst(); + + } + + public Pair getRequest(String requestUrl, Map headersMap, boolean closeTheRequest) { + Pair ret; + CloseableHttpResponse httpResponse = null; + String url = HTTPS + serverFqdn + requestUrl; + log.debug("url to send {}", url); + HttpGet httpGet = new HttpGet(url); + List
headers = addHeadersToHttpRequest(headersMap); + for (Header header : headers) { + httpGet.addHeader(header); + } + + httpGet.setHeader(AUTHORIZATION_HEADER, this.authHeaderValue); + + HttpAsdcResponse response = null; + try { + httpResponse = httpClient.execute(httpGet); + + log.debug("GET Response Status {}", httpResponse.getStatusLine().getStatusCode()); + Header[] headersRes = httpResponse.getAllHeaders(); + Map headersResMap = new HashMap<>(); + for (Header header : headersRes) { + headersResMap.put(header.getName(), header.getValue()); + } + response = new HttpAsdcResponse(httpResponse.getStatusLine().getStatusCode(), httpResponse.getEntity(), headersResMap); + + } catch (UnknownHostException | ConnectException e) { + log.error("failed to connect to url: {}", requestUrl, e); + StringEntity errorEntity = null; + try { + errorEntity = new StringEntity("failed to connect"); + } catch (UnsupportedEncodingException e1) { + } + + response = new HttpAsdcResponse(HttpStatus.SC_BAD_GATEWAY, errorEntity); + + } catch (IOException e) { + log.error("failed to send request to url: " + requestUrl + " error " + e.getMessage()); + StringEntity errorEntity = null; + try { + errorEntity = new StringEntity("failed to send request " + e.getMessage()); + } catch (UnsupportedEncodingException e1) { + } + + response = new HttpAsdcResponse(HttpStatus.SC_BAD_GATEWAY, errorEntity); + + } finally { + + if (closeTheRequest) { + if (httpResponse != null) { + try { + httpResponse.close(); + + } catch (IOException e) { + log.error("failed to close http response"); + } + } + ret = new Pair(response, null); + } else { + ret = new Pair(response, httpResponse); + } + } + + return ret; + + } + + public void closeHttpClient() { + try { + httpClient.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + log.error("failed to close http client"); + } + + } + + private List
addHeadersToHttpRequest(Map headersMap) { + + List
requestHeaders = new ArrayList
(); + + Set headersKyes = headersMap.keySet(); + for (String key : headersKyes) { + Header requestHeader = new BasicHeader(key, headersMap.get(key)); + requestHeaders.add(requestHeader); + } + + return requestHeaders; + } + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/http/HttpAsdcResponse.java b/sdc-distribution-client/src/main/java/org/onap/sdc/http/HttpAsdcResponse.java new file mode 100644 index 0000000..9734a32 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/http/HttpAsdcResponse.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.http; + +import java.util.Map; + +import org.apache.http.HttpEntity; + +public class HttpAsdcResponse { + + int status; + HttpEntity message; + Map headersMap; + + public HttpAsdcResponse(int status, HttpEntity message) { + super(); + this.status = status; + this.message = message; + } + + public HttpAsdcResponse(int status, HttpEntity message, Map headersMap) { + super(); + this.status = status; + this.message = message; + this.headersMap = headersMap; + } + + public Map getHeadersMap() { + return headersMap; + } + + public void setHeadersMap(Map headersMap) { + this.headersMap = headersMap; + } + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + public HttpEntity getMessage() { + return message; + } + + public void setMessage(HttpEntity message) { + this.message = message; + } + + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/http/IHttpAsdcClient.java b/sdc-distribution-client/src/main/java/org/onap/sdc/http/IHttpAsdcClient.java new file mode 100644 index 0000000..a3cc5e5 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/http/IHttpAsdcClient.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.http; + +import java.util.Map; + +import org.apache.http.HttpEntity; + +public interface IHttpAsdcClient { + + HttpAsdcResponse postRequest(String requestUrl, HttpEntity entity, Map headersMap); + HttpAsdcResponse getRequest(String requestUrl, Map headersMap); + void closeHttpClient(); + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/http/SdcConnectorClient.java b/sdc-distribution-client/src/main/java/org/onap/sdc/http/SdcConnectorClient.java new file mode 100644 index 0000000..41d78ba --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/http/SdcConnectorClient.java @@ -0,0 +1,398 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.http; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.results.IDistributionClientResult; +import org.onap.sdc.impl.DistributionClientResultImpl; +import org.onap.sdc.utils.DistributionActionResultEnum; +import org.onap.sdc.utils.GeneralUtils; +import org.onap.sdc.api.asdc.RegistrationRequest; +import org.onap.sdc.api.asdc.ServerListResponse; +import org.onap.sdc.api.consumer.IConfiguration; +import org.onap.sdc.impl.DistributionClientDownloadResultImpl; +import org.onap.sdc.utils.DistributionClientConstants; +import org.onap.sdc.utils.Pair; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; + +import fj.data.Either; + +public class SdcConnectorClient { + String contentDispositionHeader = "Content-Disposition"; + private static Logger log = LoggerFactory.getLogger(SdcConnectorClient.class.getName()); + private IConfiguration configuration; + private HttpAsdcClient httpClient = null; + + public void init(IConfiguration configuraion) { + this.configuration = configuraion; + httpClient = new HttpAsdcClient(configuration); + } + + public void close() { + if (httpClient != null) { + httpClient.closeHttpClient(); + } + } + + public IConfiguration getConfiguration() { + return configuration; + } + + public void setConfiguration(IConfiguration configuration) { + this.configuration = configuration; + } + + public HttpAsdcClient getHttpClient() { + return httpClient; + } + + public void setHttpClient(HttpAsdcClient httpClient) { + this.httpClient = httpClient; + } + + + public Either, IDistributionClientResult> getValidArtifactTypesList() { + Pair getServersResponsePair = performAsdcServerRequest(AsdcUrls.GET_VALID_ARTIFACT_TYPES); + HttpAsdcResponse getArtifactTypeResponse = getServersResponsePair.getFirst(); + + Either, IDistributionClientResult> response; + if (getArtifactTypeResponse.getStatus() == HttpStatus.SC_OK) { + response = parseGetValidArtifactTypesResponse(getArtifactTypeResponse); + } else { + IDistributionClientResult asdcError = handleAsdcError(getArtifactTypeResponse); + response = Either.right(asdcError); + + } + handeAsdcConnectionClose(getServersResponsePair); + return response; + + } + + private void handeAsdcConnectionClose(Pair getServersResponsePair) { + if (getServersResponsePair.getSecond() != null) { + try { + getServersResponsePair.getSecond().close(); + + } catch (IOException e) { + log.error("failed to close http response"); + } + + } + } + + private Pair performAsdcServerRequest(final String url) { + String requestId = UUID.randomUUID().toString(); + Map requestHeaders = addHeadersToHttpRequest(requestId); + log.debug("about to perform getServerList. requestId= {} url= {}", requestId, url); + Pair getServersResponsePair = httpClient.getRequest(url, requestHeaders, false); + return getServersResponsePair; + } + + public Either registerAsdcTopics(ApiCredential credential) { + + Either response = null; + + String requestId = UUID.randomUUID().toString(); + Map requestHeaders = addHeadersToHttpRequest(requestId); + + RegistrationRequest registrationRequest = new RegistrationRequest(credential.getApiKey(), configuration.getEnvironmentName(), configuration.isConsumeProduceStatusTopic(), configuration.getMsgBusAddress()); + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String jsonRequest = gson.toJson(registrationRequest); + StringEntity body = new StringEntity(jsonRequest, ContentType.APPLICATION_JSON); + + log.debug("about to perform registerAsdcTopics. requestId= " + requestId + " url= " + AsdcUrls.POST_FOR_TOPIC_REGISTRATION); + Pair registerResponsePair = httpClient.postRequest(AsdcUrls.POST_FOR_TOPIC_REGISTRATION, body, requestHeaders, false); + HttpAsdcResponse registerResponse = registerResponsePair.getFirst(); + int status = registerResponse.getStatus(); + + if (status == HttpStatus.SC_OK) { + response = parseRegistrationResponse(registerResponse); + + } else { + DistributionClientResultImpl asdcError = handleAsdcError(registerResponse); + return Either.right(asdcError); + } + handeAsdcConnectionClose(registerResponsePair); + + log.debug("registerAsdcTopics response= " + status + ". requestId= " + requestId + " url= " + AsdcUrls.POST_FOR_TOPIC_REGISTRATION); + return response; + + } + + public IDistributionClientResult unregisterTopics(ApiCredential credential) { + + DistributionClientResultImpl response = null; + + String requestId = UUID.randomUUID().toString(); + HttpAsdcClient httpClient = new HttpAsdcClient(configuration); + Map requestHeaders = addHeadersToHttpRequest(requestId); + + RegistrationRequest registrationRequest = new RegistrationRequest(credential.getApiKey(), configuration.getEnvironmentName(), configuration.isConsumeProduceStatusTopic(), configuration.getMsgBusAddress()); + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String jsonRequest = gson.toJson(registrationRequest); + StringEntity body = new StringEntity(jsonRequest, ContentType.APPLICATION_JSON); + + log.debug("about to perform unregisterTopics. requestId= " + requestId + " url= " + AsdcUrls.POST_FOR_UNREGISTER); + Pair unRegisterResponsePair = httpClient.postRequest(AsdcUrls.POST_FOR_UNREGISTER, body, requestHeaders, false); + HttpAsdcResponse unRegisterResponse = unRegisterResponsePair.getFirst(); + int status = unRegisterResponse.getStatus(); + if (status == HttpStatus.SC_NO_CONTENT || status == HttpStatus.SC_OK) { + response = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "unregistration successful"); + + } else { + response = handleAsdcError(unRegisterResponse); + } + + handeAsdcConnectionClose(unRegisterResponsePair); + + log.debug("unregisterTopics response = " + status + ". requestId= " + requestId + " url= " + AsdcUrls.POST_FOR_UNREGISTER); + + return response; + + } + + public DistributionClientDownloadResultImpl dowloadArtifact(IArtifactInfo artifactInfo) { + DistributionClientDownloadResultImpl response = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "failed to download artifact from ASDC"); + + String requestId = UUID.randomUUID().toString(); + Map requestHeaders = new HashMap(); + requestHeaders.put(DistributionClientConstants.HEADER_REQUEST_ID, requestId); + requestHeaders.put(DistributionClientConstants.HEADER_INSTANCE_ID, configuration.getConsumerID()); + requestHeaders.put(HttpHeaders.ACCEPT, ContentType.APPLICATION_OCTET_STREAM.toString()); + String requestUrl = artifactInfo.getArtifactURL(); + Pair downloadPair = httpClient.getRequest(requestUrl, requestHeaders, false); + HttpAsdcResponse downloadResponse = downloadPair.getFirst(); + + int status = downloadResponse.getStatus(); + if (status == 200) { + + response = parseDownloadArtifactResponse(artifactInfo, downloadResponse); + } else { + response = handleAsdcDownloadArtifactError(downloadResponse); + + } + handeAsdcConnectionClose(downloadPair); + return response; + } + + /* **************************** private methods ********************************************/ + + private Either, IDistributionClientResult> parseGetServersResponse(HttpAsdcResponse getServersResponse) { + Either, IDistributionClientResult> result; + try { + String jsonMessage = IOUtils.toString(getServersResponse.getMessage().getContent()); + + Gson gson = new GsonBuilder().create(); + ServerListResponse serverListResponse = gson.fromJson(jsonMessage, ServerListResponse.class); + List serverList = serverListResponse.getUebServerList(); + result = Either.left(serverList); + + } catch (UnsupportedOperationException | IOException e) { + result = handleParsingError(e); + } + + return result; + } + + private Either, IDistributionClientResult> parseGetValidArtifactTypesResponse(HttpAsdcResponse getArtifactTypesResponse) { + Either, IDistributionClientResult> result; + try { + String jsonMessage = IOUtils.toString(getArtifactTypesResponse.getMessage().getContent()); + Type listType = new TypeToken>() { + }.getType(); + Gson gson = new GsonBuilder().create(); + List artifactTypesList = gson.fromJson(jsonMessage, listType); + result = Either.left(artifactTypesList); + + } catch (UnsupportedOperationException | IOException e) { + result = handleParsingError(e); + } + + return result; + } + + private Either, IDistributionClientResult> handleParsingError(Exception e) { + Either, IDistributionClientResult> result; + log.error("failed to parse response from ASDC. error: " + e.getMessage()); + IDistributionClientResult response = new DistributionClientResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "failed to parse response from ASDC"); + result = Either.right(response); + return result; + } + + Either parseRegistrationResponse(HttpAsdcResponse registerResponse) { + + String jsonMessage; + try { + jsonMessage = IOUtils.toString(registerResponse.getMessage().getContent()); + + Gson gson = new GsonBuilder().create(); + TopicRegistrationResponse registrationResponse = gson.fromJson(jsonMessage, TopicRegistrationResponse.class); + + if (registrationResponse.getDistrNotificationTopicName() == null) { + DistributionClientResultImpl response = new DistributionClientResultImpl(DistributionActionResultEnum.FAIL, "failed to receive notification topic from ASDC"); + return Either.right(response); + } + + if (registrationResponse.getDistrStatusTopicName() == null) { + DistributionClientResultImpl response = new DistributionClientResultImpl(DistributionActionResultEnum.FAIL, "failed to receive status topic from ASDC"); + return Either.right(response); + } + return Either.left(registrationResponse); + + } catch (UnsupportedOperationException | IOException e) { + log.error("failed to pars response from ASDC. error: " + e.getMessage()); + DistributionClientResultImpl response = new DistributionClientResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "failed to parse response from ASDC"); + return Either.right(response); + } + } + + protected Map addHeadersToHttpRequest(String requestId) { + Map requestHeaders = new HashMap<>(); + requestHeaders.put(DistributionClientConstants.HEADER_REQUEST_ID, requestId); + requestHeaders.put(DistributionClientConstants.HEADER_INSTANCE_ID, configuration.getConsumerID()); + requestHeaders.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); + + return requestHeaders; + } + + private DistributionClientResultImpl handleAsdcError(HttpAsdcResponse registerResponse) { + int status = registerResponse.getStatus(); + DistributionClientResultImpl errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "failed to send request to ASDC"); + if (status == HttpStatus.SC_UNAUTHORIZED) { + errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_AUTHENTICATION_FAILED, "authentication to ASDC failed for user " + configuration.getUser()); + } else if (status == HttpStatus.SC_FORBIDDEN) { + errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_AUTHORIZATION_FAILED, "authorization failure for user " + configuration.getUser()); + } else if (status == HttpStatus.SC_BAD_REQUEST) { + errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.BAD_REQUEST, "ASDC call failed due to missing information"); + } else if (status == HttpStatus.SC_NOT_FOUND) { + errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_NOT_FOUND, "ASDC not found"); + } else if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) { + errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_SERVER_PROBLEM, "ASDC server problem"); + } else if (status == HttpStatus.SC_BAD_GATEWAY) { + errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, "ASDC server problem"); + } else if (status == HttpStatus.SC_GATEWAY_TIMEOUT) { + errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_SERVER_TIMEOUT, "ASDC server problem"); + } + log.error("status from ASDC is " + registerResponse); + log.error(errorResponse.toString()); + try { + String errorString = IOUtils.toString(registerResponse.getMessage().getContent()); + log.debug("error from ASDC is: " + errorString); + } catch (UnsupportedOperationException | IOException e) { + } + return errorResponse; + + } + + private DistributionClientDownloadResultImpl handleAsdcDownloadArtifactError(HttpAsdcResponse registerResponse) { + int status = registerResponse.getStatus(); + DistributionClientDownloadResultImpl errorResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "failed to send request to ASDC"); + if (status == HttpStatus.SC_UNAUTHORIZED) { + errorResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.ASDC_AUTHENTICATION_FAILED, "authentication to ASDC failed for user " + configuration.getUser()); + } else if (status == HttpStatus.SC_FORBIDDEN) { + errorResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.ASDC_AUTHORIZATION_FAILED, "authorization failure for user " + configuration.getUser()); + } else if (status == HttpStatus.SC_BAD_REQUEST || status == HttpStatus.SC_NOT_FOUND) { + errorResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.ARTIFACT_NOT_FOUND, "Specified artifact is not found"); + // } else if (status == 404){ + // errorResponse = new DistributionClientDownloadResultImpl( + // DistributionActionResultEnum.ASDC_NOT_FOUND, + // "ASDC not found"); + } else if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) { + errorResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.ASDC_SERVER_PROBLEM, "ASDC server problem"); + } + log.error("status from ASDC is " + registerResponse); + log.error(errorResponse.toString()); + try { + String errorString = IOUtils.toString(registerResponse.getMessage().getContent()); + log.debug("error from ASDC is: " + errorString); + } catch (UnsupportedOperationException | IOException e) { + } + return errorResponse; + + } + + private DistributionClientDownloadResultImpl parseDownloadArtifactResponse(IArtifactInfo artifactInfo, HttpAsdcResponse getServersResponse) { + HttpEntity entity = getServersResponse.getMessage(); + InputStream is; + try { + is = entity.getContent(); + String artifactName = ""; + if (getServersResponse.getHeadersMap().containsKey(contentDispositionHeader)) + artifactName = getServersResponse.getHeadersMap().get(contentDispositionHeader); + + byte[] payload = IOUtils.toByteArray(is); + if (artifactInfo.getArtifactChecksum() == null || artifactInfo.getArtifactChecksum().isEmpty()) { + return new DistributionClientDownloadResultImpl(DistributionActionResultEnum.DATA_INTEGRITY_PROBLEM, "failed to get artifact from ASDC. Empty checksum"); + } + + DistributionClientDownloadResultImpl resResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS, "success", artifactName, payload); + return resResponse; + + //Validate checksum removed as fix to bug 293657 + /*if (validateChecksum(artifactInfo, payload)) { + DistributionClientDownloadResultImpl resResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS, "success", artifactName, payload); + return resResponse; + + } else { + + return new DistributionClientDownloadResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "Invalid checksum. ArtifactInfo checksum "); + }*/ + + } catch (UnsupportedOperationException | IOException e) { + log.error("failed to get artifact from response "); + return new DistributionClientDownloadResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "UnsupportedOperationException "); + } + + } + + private boolean validateChecksum(IArtifactInfo artifactInfo, byte[] payload) { + boolean bRes = false; + String calculatedMD5 = GeneralUtils.calculateMD5(payload); + if (artifactInfo.getArtifactChecksum().equals(calculatedMD5)) { + bRes = true; + } + + return bRes; + } + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/http/TopicRegistrationResponse.java b/sdc-distribution-client/src/main/java/org/onap/sdc/http/TopicRegistrationResponse.java new file mode 100644 index 0000000..e8d0545 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/http/TopicRegistrationResponse.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.http; + +public class TopicRegistrationResponse { + String distrNotificationTopicName; + String distrStatusTopicName; + + + public void setDistrNotificationTopicName(String distrNotificationTopicName) { + this.distrNotificationTopicName = distrNotificationTopicName; + } + public void setDistrStatusTopicName(String distrStatusTopicName) { + this.distrStatusTopicName = distrStatusTopicName; + } + + public String getDistrNotificationTopicName() { + return distrNotificationTopicName; + } + public String getDistrStatusTopicName() { + return distrStatusTopicName; + } +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/ArtifactInfoImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/ArtifactInfoImpl.java new file mode 100644 index 0000000..6a3da83 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/ArtifactInfoImpl.java @@ -0,0 +1,192 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.sdc.api.notification.IArtifactInfo; + +class ArtifactInfoImpl implements IArtifactInfo { + + private String artifactName; + private String artifactType; + private String artifactURL; + private String artifactChecksum; + private String artifactDescription; + private Integer artifactTimeout; + private String artifactVersion; + private String artifactUUID; + private String generatedFromUUID; + private IArtifactInfo generatedArtifact; + private List relatedArtifacts; + private List relatedArtifactsInfo; + ArtifactInfoImpl(){} + + private ArtifactInfoImpl(IArtifactInfo iArtifactInfo){ + artifactName = iArtifactInfo.getArtifactName(); + artifactType = iArtifactInfo.getArtifactType(); + artifactURL = iArtifactInfo.getArtifactURL(); + artifactChecksum = iArtifactInfo.getArtifactChecksum(); + artifactDescription = iArtifactInfo.getArtifactDescription(); + artifactTimeout = iArtifactInfo.getArtifactTimeout(); + artifactVersion = iArtifactInfo.getArtifactVersion(); + artifactUUID = iArtifactInfo.getArtifactUUID(); + generatedArtifact = iArtifactInfo.getGeneratedArtifact(); + relatedArtifactsInfo = iArtifactInfo.getRelatedArtifacts(); + relatedArtifacts = fillRelatedArtifactsUUID(relatedArtifactsInfo); + + } + + + private List fillRelatedArtifactsUUID(List relatedArtifactsInfo) { + List relatedArtifactsUUID = null; + if( relatedArtifactsInfo != null && !relatedArtifactsInfo.isEmpty()){ + relatedArtifactsUUID = new ArrayList<>(); + for(IArtifactInfo curr: relatedArtifactsInfo){ + relatedArtifactsUUID.add(curr.getArtifactUUID()); + } + } + return relatedArtifactsUUID; + } + + public static List convertToArtifactInfoImpl(List list){ + List ret = new ArrayList(); + if( list != null ){ + for(IArtifactInfo artifactInfo : list ){ + ret.add(new ArtifactInfoImpl(artifactInfo)); + } + } + return ret; + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactURL() { + return artifactURL; + } + + public void setArtifactURL(String artifactURL) { + this.artifactURL = artifactURL; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public void setArtifactChecksum(String artifactChecksum) { + this.artifactChecksum = artifactChecksum; + } + + public String getArtifactDescription() { + return artifactDescription; + } + + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public Integer getArtifactTimeout() { + return artifactTimeout; + } + + public void setArtifactTimeout(Integer artifactTimeout) { + this.artifactTimeout = artifactTimeout; + } + + @Override + public String toString() { + return "BaseArtifactInfoImpl [artifactName=" + artifactName + + ", artifactType=" + artifactType + ", artifactURL=" + + artifactURL + ", artifactChecksum=" + artifactChecksum + + ", artifactDescription=" + artifactDescription + + ", artifactVersion=" + artifactVersion + + ", artifactUUID=" + artifactUUID + + ", artifactTimeout=" + artifactTimeout + "]"; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } + + public String getGeneratedFromUUID() { + return generatedFromUUID; + } + + public void setGeneratedFromUUID(String generatedFromUUID) { + this.generatedFromUUID = generatedFromUUID; + } + + public IArtifactInfo getGeneratedArtifact() { + return generatedArtifact; + } + + public void setGeneratedArtifact(IArtifactInfo generatedArtifact) { + this.generatedArtifact = generatedArtifact; + } + + public List getRelatedArtifacts(){ + List temp = new ArrayList(); + if( relatedArtifactsInfo != null ){ + temp.addAll(relatedArtifactsInfo); + } + return temp; + } + + public void setRelatedArtifacts(List relatedArtifacts) { + this.relatedArtifacts = relatedArtifacts; + } + + public void setRelatedArtifactsInfo(List relatedArtifactsInfo) { + this.relatedArtifactsInfo = relatedArtifactsInfo; + } + + public List getRelatedArtifactsUUID(){ + return relatedArtifacts; + } + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/Configuration.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/Configuration.java new file mode 100644 index 0000000..a33f911 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/Configuration.java @@ -0,0 +1,225 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl; + +import java.util.List; + +import org.onap.sdc.utils.DistributionClientConstants; +import org.onap.sdc.api.consumer.IConfiguration; + +public class Configuration implements IConfiguration { + + private List msgBusAddressList; + private String asdcAddress; + private String user; + private String password; + private int pollingInterval = DistributionClientConstants.MIN_POLLING_INTERVAL_SEC; + private int pollingTimeout = DistributionClientConstants.POLLING_TIMEOUT_SEC; + private List relevantArtifactTypes; + private String consumerGroup; + private String environmentName; + private String comsumerID; + private String keyStorePath; + private String keyStorePassword; + private boolean activateServerTLSAuth; + private boolean filterInEmptyResources; + private Boolean useHttpsWithDmaap; + private boolean consumeProduceStatusTopic; + + public Configuration(IConfiguration other) { + this.asdcAddress = other.getAsdcAddress(); + this.msgBusAddressList = other.getMsgBusAddress(); + this.comsumerID = other.getConsumerID(); + this.consumerGroup = other.getConsumerGroup(); + this.environmentName = other.getEnvironmentName(); + this.password = other.getPassword(); + this.pollingInterval = other.getPollingInterval(); + this.pollingTimeout = other.getPollingTimeout(); + this.relevantArtifactTypes = other.getRelevantArtifactTypes(); + this.user = other.getUser(); + this.keyStorePath = other.getKeyStorePath(); + this.keyStorePassword = other.getKeyStorePassword(); + this.activateServerTLSAuth = other.activateServerTLSAuth(); + this.filterInEmptyResources = other.isFilterInEmptyResources(); + this.useHttpsWithDmaap = other.isUseHttpsWithDmaap(); + this.consumeProduceStatusTopic = other.isConsumeProduceStatusTopic(); + } + + @Override + public String getAsdcAddress() { + return asdcAddress; + } + + @Override + public List getMsgBusAddress() { + return msgBusAddressList; + } + + @Override + public String getUser() { + return user; + } + + @Override + public String getPassword() { + return password; + } + + @Override + public int getPollingInterval() { + return pollingInterval; + } + + @Override + public int getPollingTimeout() { + return pollingTimeout; + } + + @Override + public List getRelevantArtifactTypes() { + return relevantArtifactTypes; + } + + @Override + public String getConsumerGroup() { + return consumerGroup; + } + + @Override + public String getEnvironmentName() { + return environmentName; + } + + @Override + public String getConsumerID() { + return comsumerID; + } + + @Override + public String getKeyStorePath() { + return keyStorePath; + } + + @Override + public String getKeyStorePassword() { + return keyStorePassword; + } + + public String getComsumerID() { + return comsumerID; + } + + public void setComsumerID(String comsumerID) { + this.comsumerID = comsumerID; + } + + public void setAsdcAddress(String asdcAddress) { + this.asdcAddress = asdcAddress; + } + + public void setUser(String user) { + this.user = user; + } + + public void setPassword(String password) { + this.password = password; + } + + public void setPollingInterval(int pollingInterval) { + this.pollingInterval = pollingInterval; + } + + public void setPollingTimeout(int pollingTimeout) { + this.pollingTimeout = pollingTimeout; + } + + public void setRelevantArtifactTypes(List relevantArtifactTypes) { + this.relevantArtifactTypes = relevantArtifactTypes; + } + + public void setConsumerGroup(String consumerGroup) { + this.consumerGroup = consumerGroup; + } + + public void setEnvironmentName(String environmentName) { + this.environmentName = environmentName; + } + + public void setKeyStorePath(String keyStorePath) { + this.keyStorePath = keyStorePath; + } + + public void setKeyStorePassword(String keyStorePassword) { + this.keyStorePassword = keyStorePassword; + } + + public void setactivateServerTLSAuth(boolean activateServerTLSAuth) { + this.activateServerTLSAuth = activateServerTLSAuth; + } + + @Override + public boolean activateServerTLSAuth() { + return this.activateServerTLSAuth; + } + + @Override + public boolean isFilterInEmptyResources() { + return this.filterInEmptyResources; + } + + @Override + public Boolean isUseHttpsWithDmaap() { + return this.useHttpsWithDmaap; + } + + public void setUseHttpsWithDmaap(boolean useHttpsWithDmaap) { + this.useHttpsWithDmaap = useHttpsWithDmaap; + } + + @Override + public boolean isConsumeProduceStatusTopic() { + return this.consumeProduceStatusTopic; + } + + @Override + public String toString() { + //@formatter:off + return "Configuration ["+ + "asdcAddress=" + asdcAddress + + ", user=" + user + + ", password=" + password + + ", pollingInterval=" + pollingInterval + + ", pollingTimeout=" + pollingTimeout + + ", relevantArtifactTypes=" + relevantArtifactTypes + + ", consumerGroup=" + consumerGroup + + ", environmentName=" + environmentName + + ", comsumerID=" + comsumerID + + ", keyStorePath=" + keyStorePath + + ", keyStorePassword=" + keyStorePassword + + ", activateServerTLSAuth=" + activateServerTLSAuth + + ", filterInEmptyResources=" + filterInEmptyResources + + ", useHttpsWithDmaap=" + useHttpsWithDmaap + + ", consumeProduceStatusTopic=" + consumeProduceStatusTopic + + "]"; + //@formatter:on + } + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientDownloadResultImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientDownloadResultImpl.java new file mode 100644 index 0000000..6323113 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientDownloadResultImpl.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl; + +import org.onap.sdc.api.results.IDistributionClientDownloadResult; +import org.onap.sdc.utils.DistributionActionResultEnum; + +public class DistributionClientDownloadResultImpl extends DistributionClientResultImpl implements IDistributionClientDownloadResult { + byte[] artifactPayload; + String artifactName; + + + public DistributionClientDownloadResultImpl( + DistributionActionResultEnum responseStatus, String responseMessage) { + super(responseStatus, responseMessage); + + } + + public DistributionClientDownloadResultImpl( + DistributionActionResultEnum responseStatus, + String responseMessage, String artifactName, byte[] artifactPayload) { + super(responseStatus, responseMessage); + this.artifactPayload = artifactPayload; + this.artifactName = artifactName; + } + + + public void setArtifactPayload(byte[] payload) { + this.artifactPayload = payload; + } + + + public byte[] getArtifactPayload() { + + return artifactPayload; + } + + public String getArtifactName(){ + return artifactName; + } + + public void setArtifactName(String artifactName){ + this.artifactName = artifactName; + } + + @Override + public String getArtifactFilename() { + //Fix of bug 292443 in TDP + if (artifactName == null || !artifactName.matches("attachment;\\s*filename=\".*?\"")){ + return artifactName; + } + String fileName = "filename=\""; + return artifactName.substring(artifactName.indexOf(fileName)+fileName.length(), artifactName.lastIndexOf("\"")); + } + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientFactory.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientFactory.java new file mode 100644 index 0000000..96aabc2 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientFactory.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl; + +import org.onap.sdc.api.IDistributionClient; +import org.onap.sdc.impl.mock.DistributionClientStubImpl; + +public class DistributionClientFactory { + public static IDistributionClient createDistributionClient(){ + return new DistributionClientImpl(); + } + + public static IDistributionClient createMockDistributionClient(){ + return new DistributionClientStubImpl(); + } +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientImpl.java new file mode 100644 index 0000000..5d15046 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientImpl.java @@ -0,0 +1,779 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl; + +import static java.util.Objects.isNull; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.net.MalformedURLException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; + +import org.onap.sdc.api.IDistributionClient; +import org.onap.sdc.api.IDistributionStatusMessageJsonBuilder; +import org.onap.sdc.api.consumer.*; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.results.IDistributionClientDownloadResult; +import org.onap.sdc.api.results.IDistributionClientResult; +import org.onap.sdc.http.SdcConnectorClient; +import org.onap.sdc.http.TopicRegistrationResponse; +import org.onap.sdc.utils.DistributionActionResultEnum; +import org.onap.sdc.utils.DistributionClientConstants; +import org.onap.sdc.utils.GeneralUtils; +import org.onap.sdc.utils.Wrapper; +import org.onap.sdc.api.consumer.*; +import org.onap.sdc.api.notification.IVfModuleMetadata; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.cambria.client.CambriaBatchingPublisher; +import com.att.nsa.cambria.client.CambriaClient.CambriaApiException; +import com.att.nsa.cambria.client.CambriaClientBuilders.AbstractAuthenticatedManagerBuilder; +import com.att.nsa.cambria.client.CambriaClientBuilders.ConsumerBuilder; +import com.att.nsa.cambria.client.CambriaClientBuilders.IdentityManagerBuilder; +import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder; +import com.att.nsa.cambria.client.CambriaConsumer; +import com.att.nsa.cambria.client.CambriaIdentityManager; +import com.att.nsa.cambria.client.CambriaPublisher.message; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; + +import fj.data.Either; + +public class DistributionClientImpl implements IDistributionClient { + + private static Logger log = LoggerFactory.getLogger(DistributionClientImpl.class.getName()); + + protected SdcConnectorClient asdcConnector = new SdcConnectorClient(); + private ScheduledExecutorService executorPool = null; + protected CambriaIdentityManager cambriaIdentityManager = null; + private List brokerServers; + protected ApiCredential credential; + protected Configuration configuration; + private INotificationCallback callback; + private IStatusCallback statusCallback; + private String notificationTopic; + private String statusTopic; + private boolean isConsumerGroupGenerated = false; + + private boolean isInitialized, isStarted, isTerminated; + + @Override + public IConfiguration getConfiguration() { + return configuration; + } + + @Override + /* see javadoc */ + public synchronized IDistributionClientResult updateConfiguration(IConfiguration conf) { + + log.info("update DistributionClient configuration"); + Wrapper errorWrapper = new Wrapper<>(); + validateRunReady(errorWrapper); + + if (!errorWrapper.isEmpty()) { + return errorWrapper.getInnerElement(); + } + + IDistributionClientResult updateResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "configuration updated successfuly"); + + boolean needToUpdateCambriaConsumer = false; + + if (conf.getRelevantArtifactTypes() != null && !conf.getRelevantArtifactTypes().isEmpty()) { + configuration.setRelevantArtifactTypes(conf.getRelevantArtifactTypes()); + needToUpdateCambriaConsumer = true; + } + if (isPollingIntervalValid(conf.getPollingInterval())) { + configuration.setPollingInterval(conf.getPollingInterval()); + needToUpdateCambriaConsumer = true; + } + if (isPollingTimeoutValid(conf.getPollingTimeout())) { + configuration.setPollingTimeout(conf.getPollingTimeout()); + needToUpdateCambriaConsumer = true; + } + if (conf.getConsumerGroup() != null) { + configuration.setConsumerGroup(conf.getConsumerGroup()); + isConsumerGroupGenerated = false; + needToUpdateCambriaConsumer = true; + } else if (!isConsumerGroupGenerated) { + generateConsumerGroup(); + } + + if (needToUpdateCambriaConsumer) { + updateResult = restartConsumer(); + } + + return updateResult; + } + + @Override + /** + * Start polling the Notification topic + */ + public synchronized IDistributionClientResult start() { + + log.info("start DistributionClient"); + IDistributionClientResult startResult; + CambriaConsumer cambriaNotificationConsumer = null; + Wrapper errorWrapper = new Wrapper<>(); + validateRunReady(errorWrapper); + if (errorWrapper.isEmpty()) { + validateNotStarted(errorWrapper); + } + if (errorWrapper.isEmpty()) { + try { + cambriaNotificationConsumer = new ConsumerBuilder().authenticatedBy(credential.getApiKey(), credential.getApiSecret()).knownAs(configuration.getConsumerGroup(), configuration.getConsumerID()).onTopic(notificationTopic).usingHttps(configuration.isUseHttpsWithDmaap()).usingHosts(brokerServers) + .withSocketTimeout(configuration.getPollingTimeout() * 1000).build(); + + } catch (MalformedURLException | GeneralSecurityException e) { + handleCambriaInitFailure(errorWrapper, e); + } + } + if (errorWrapper.isEmpty()) { + + List relevantArtifactTypes = configuration.getRelevantArtifactTypes(); + // Remove nulls from list - workaround for how configuration is built + while (relevantArtifactTypes.remove(null)); + + NotificationConsumer consumer = new NotificationConsumer(cambriaNotificationConsumer, callback, relevantArtifactTypes, this); + executorPool = Executors.newScheduledThreadPool(DistributionClientConstants.POOL_SIZE); + executorPool.scheduleAtFixedRate(consumer, 0, configuration.getPollingInterval(), TimeUnit.SECONDS); + + handleStatusConsumer(errorWrapper, executorPool); + } + if (!errorWrapper.isEmpty()) { + startResult = errorWrapper.getInnerElement(); + } + else{ + startResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "distribution client started successfuly"); + isStarted = true; + } + return startResult; + } + + private void handleStatusConsumer(Wrapper errorWrapper, ScheduledExecutorService executorPool) { + if( configuration.isConsumeProduceStatusTopic()){ + CambriaConsumer cambriaStatusConsumer = null; + try { + cambriaStatusConsumer = new ConsumerBuilder().authenticatedBy(credential.getApiKey(), credential.getApiSecret()).knownAs(configuration.getConsumerGroup(), configuration.getConsumerID()).onTopic(statusTopic).usingHttps(configuration.isUseHttpsWithDmaap()).usingHosts(brokerServers) + .withSocketTimeout(configuration.getPollingTimeout() * 1000).build(); + StatusConsumer statusConsumer = new StatusConsumer(cambriaStatusConsumer, statusCallback); + executorPool.scheduleAtFixedRate(statusConsumer, 0, configuration.getPollingInterval(), TimeUnit.SECONDS); + } catch (MalformedURLException | GeneralSecurityException e) { + handleCambriaInitFailure(errorWrapper, e); + } + } + } + + @Override + /* see javadoc */ + public synchronized IDistributionClientResult stop() { + + log.info("stop DistributionClient"); + Wrapper errorWrapper = new Wrapper<>(); + validateRunReady(errorWrapper); + if (!errorWrapper.isEmpty()) { + return errorWrapper.getInnerElement(); + } + // 1. stop polling notification topic + shutdownExecutor(); + + // 2. send to ASDC unregister to topic + IDistributionClientResult unregisterResult = asdcConnector.unregisterTopics(credential); + if (unregisterResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) { + log.info("client failed to unregister from topics"); + } else { + log.info("client unregistered from topics successfully"); + } + asdcConnector.close(); + + try { + cambriaIdentityManager.deleteCurrentApiKey(); + } catch (HttpException | IOException e) { + log.debug("failed to delete cambria keys", e); + } + cambriaIdentityManager.close(); + + isInitialized = false; + isTerminated = true; + + DistributionClientResultImpl stopResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "distribution client stopped successfuly"); + return stopResult; + } + + @Override + public IDistributionClientDownloadResult download(IArtifactInfo artifactInfo) { + log.info("DistributionClient - download"); + Wrapper errorWrapper = new Wrapper<>(); + validateRunReady(errorWrapper); + if (!errorWrapper.isEmpty()) { + IDistributionClientResult result = errorWrapper.getInnerElement(); + IDistributionClientDownloadResult downloadResult = new DistributionClientDownloadResultImpl(result.getDistributionActionResult(), result.getDistributionMessageResult()); + return downloadResult; + } + return asdcConnector.dowloadArtifact(artifactInfo); + } + @Override + public synchronized IDistributionClientResult init(IConfiguration conf, INotificationCallback notificationCallback, + IStatusCallback statusCallback) { + IDistributionClientResult initResult; + if( !conf.isConsumeProduceStatusTopic() ){ + initResult = new DistributionClientResultImpl(DistributionActionResultEnum.CONF_INVALID_CONSUME_PRODUCE_STATUS_TOPIC_FALG, "configuration is invalid: isConsumeProduceStatusTopic() should be set to 'true'" ); + + } + else if( isNull(statusCallback) ){ + initResult = new DistributionClientResultImpl(DistributionActionResultEnum.CONF_INVALID_CONSUME_PRODUCE_STATUS_TOPIC_FALG, "configuration is invalid: statusCallback is not defined" ); + } + else{ + this.statusCallback = statusCallback; + initResult = init(conf, notificationCallback); + } + return initResult; + } + + @Override + /* + * see javadoc + */ + public synchronized IDistributionClientResult init(IConfiguration conf, INotificationCallback callback) { + + log.info("DistributionClient - init"); + + Wrapper errorWrapper = new Wrapper<>(); + validateNotInitilized(errorWrapper); + if (errorWrapper.isEmpty()) { + validateNotTerminated(errorWrapper); + } + if (errorWrapper.isEmpty()) { + validateAndInitConfiguration(errorWrapper, conf); + } + // 1. get ueb server list from configuration + if (errorWrapper.isEmpty()) { + initUebServerList(errorWrapper); + } + // 2.validate artifact types against asdc server + if (errorWrapper.isEmpty()) { + validateArtifactTypesWithAsdcServer(conf, errorWrapper); + } + // 3. create keys + if (errorWrapper.isEmpty()) { + this.callback = callback; + createUebKeys(errorWrapper); + } + // 4. register for topics + if (errorWrapper.isEmpty()) { + registerForTopics(errorWrapper); + } + + IDistributionClientResult result; + if (errorWrapper.isEmpty()) { + isInitialized = true; + result = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "distribution client initialized successfuly"); + } else { + result = errorWrapper.getInnerElement(); + } + + return result; + } + + private void registerForTopics(Wrapper errorWrapper) { + Either registerAsdcTopics = asdcConnector.registerAsdcTopics(credential); + if (registerAsdcTopics.isRight()) { + + try { + cambriaIdentityManager.deleteCurrentApiKey(); + } catch (HttpException | IOException e) { + log.debug("failed to delete cambria keys", e); + } + errorWrapper.setInnerElement(registerAsdcTopics.right().value()); + } else { + TopicRegistrationResponse topics = registerAsdcTopics.left().value(); + notificationTopic = topics.getDistrNotificationTopicName(); + statusTopic = topics.getDistrStatusTopicName(); + } + + } + + private void createUebKeys(Wrapper errorWrapper) { + initCambriaClient(errorWrapper); + if (errorWrapper.isEmpty()) { + log.debug("create keys"); + DistributionClientResultImpl createKeysResponse = createUebKeys(); + if (createKeysResponse.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) { + errorWrapper.setInnerElement(createKeysResponse); + } + } + } + + private void validateArtifactTypesWithAsdcServer(IConfiguration conf, Wrapper errorWrapper) { + asdcConnector.init(configuration); + Either, IDistributionClientResult> eitherValidArtifactTypesList = asdcConnector.getValidArtifactTypesList(); + if (eitherValidArtifactTypesList.isRight()) { + DistributionActionResultEnum errorType = eitherValidArtifactTypesList.right().value().getDistributionActionResult(); + // Support the case of a new client and older ASDC Server which does not have the API + if (errorType != DistributionActionResultEnum.ASDC_NOT_FOUND) { + errorWrapper.setInnerElement(eitherValidArtifactTypesList.right().value()); + } + } else { + final List artifactTypesFromAsdc = eitherValidArtifactTypesList.left().value(); + boolean isArtifactTypesValid = artifactTypesFromAsdc.containsAll(conf.getRelevantArtifactTypes()); + if (!isArtifactTypesValid) { + List invalidArtifactTypes = new ArrayList<>(); + invalidArtifactTypes.addAll(conf.getRelevantArtifactTypes()); + invalidArtifactTypes.removeAll(artifactTypesFromAsdc); + DistributionClientResultImpl errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.CONF_CONTAINS_INVALID_ARTIFACT_TYPES, + "configuration contains invalid artifact types:" + invalidArtifactTypes + " valid types are:" + artifactTypesFromAsdc); + errorWrapper.setInnerElement(errorResponse); + } else { + log.debug("Artifact types: {} were validated with ASDC server", conf.getRelevantArtifactTypes()); + } + } + } + + private void initUebServerList(Wrapper errorWrapper) { + log.debug("get ueb cluster server list from component(configuration file)"); + + Either, IDistributionClientResult> serverListResponse = getUEBServerList(); + if (serverListResponse.isRight()) { + errorWrapper.setInnerElement(serverListResponse.right().value()); + } else { + + brokerServers = serverListResponse.left().value(); + } + + } + + private void validateNotInitilized(Wrapper errorWrapper) { + if (isInitialized) { + log.warn("distribution client already initialized"); + DistributionClientResultImpl alreadyInitResponse = new DistributionClientResultImpl(DistributionActionResultEnum.DISTRIBUTION_CLIENT_ALREADY_INITIALIZED, "distribution client already initialized"); + errorWrapper.setInnerElement(alreadyInitResponse); + } + } + + @Override + public IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage statusMessage) { + log.info("DistributionClient - sendDownloadStatus"); + Wrapper errorWrapper = new Wrapper<>(); + validateRunReady(errorWrapper); + if (!errorWrapper.isEmpty()) { + return errorWrapper.getInnerElement(); + } + + return sendStatus(DistributionStatusMessageJsonBuilderFactory.getSimpleBuilder(statusMessage)); + } + + private IDistributionClientResult sendStatus(IDistributionStatusMessageJsonBuilder builder) { + DistributionClientResultImpl statusResult = new DistributionClientResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "Failed to send status"); + log.info("DistributionClient - sendStatus"); + Either eitherPublisher = getCambriaPublisher(); + if (eitherPublisher.isRight()) { + return eitherPublisher.right().value(); + } + CambriaBatchingPublisher pub = eitherPublisher.left().value(); + + log.debug("after create publisher server list " + brokerServers.toString()); + String jsonRequest = builder.build(); + + log.debug("try to send status " + jsonRequest); + + try { + pub.send("MyPartitionKey", jsonRequest); + Thread.sleep(1000L); + } catch (IOException e) { + log.debug("DistributionClient - sendDownloadStatus. Failed to send download status"); + } catch (InterruptedException e) { + log.debug("DistributionClient - sendDownloadStatus. thread was interrupted"); + } + + finally { + + try { + List stuck = pub.close(10L, TimeUnit.SECONDS); + + if (!stuck.isEmpty()) { + log.debug("DistributionClient - sendDownloadStatus. " + stuck.size() + " messages unsent"); + } else { + statusResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "messages successfully sent"); + } + } catch (IOException | InterruptedException e) { + log.debug("DistributionClient - sendDownloadStatus. failed to send messages and close publisher "); + } + + } + return statusResult; + } + + private Either getCambriaPublisher() { + CambriaBatchingPublisher cambriaPublisher = null; + try { + cambriaPublisher = new PublisherBuilder().onTopic(statusTopic).usingHttps(configuration.isUseHttpsWithDmaap()).usingHosts(brokerServers).build(); + cambriaPublisher.setApiCredentials(credential.getApiKey(), credential.getApiSecret()); + } catch (MalformedURLException | GeneralSecurityException e) { + Wrapper errorWrapper = new Wrapper<>(); + handleCambriaInitFailure(errorWrapper, e); + return Either.right(errorWrapper.getInnerElement()); + } + return Either.left(cambriaPublisher); + } + + @Override + public IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage statusMessage) { + log.info("DistributionClient - sendDeploymentStatus"); + Wrapper errorWrapper = new Wrapper<>(); + validateRunReady(errorWrapper); + if (!errorWrapper.isEmpty()) { + return errorWrapper.getInnerElement(); + } + return sendStatus(DistributionStatusMessageJsonBuilderFactory.getSimpleBuilder(statusMessage)); + } + + IDistributionClientResult sendNotificationStatus(long currentTimeMillis, String distributionId, ArtifactInfoImpl artifactInfo, boolean isNotified) { + log.info("DistributionClient - sendNotificationStatus"); + Wrapper errorWrapper = new Wrapper<>(); + validateRunReady(errorWrapper); + if (!errorWrapper.isEmpty()) { + return errorWrapper.getInnerElement(); + } + return sendStatus(DistributionStatusMessageJsonBuilderFactory.prepareBuilderForNotificationStatus(getConfiguration().getConsumerID(), currentTimeMillis, distributionId, artifactInfo, isNotified)); + } + + /* *************************** Private Methods *************************************************** */ + + protected DistributionClientResultImpl createUebKeys() { + DistributionClientResultImpl response = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "keys created successfuly"); + try { + String description = String.format(DistributionClientConstants.CLIENT_DESCRIPTION, configuration.getConsumerID()); + credential = cambriaIdentityManager.createApiKey(DistributionClientConstants.EMAIL, description); + cambriaIdentityManager.setApiCredentials(credential.getApiKey(), credential.getApiSecret()); + + } catch (HttpException | CambriaApiException | IOException e) { + response = new DistributionClientResultImpl(DistributionActionResultEnum.UEB_KEYS_CREATION_FAILED, "failed to create keys: " + e.getMessage()); + log.error(response.toString()); + } + return response; + } + + private IDistributionClientResult restartConsumer() { + shutdownExecutor(); + return start(); + } + + protected DistributionActionResultEnum validateAndInitConfiguration(Wrapper errorWrapper, IConfiguration conf) { + DistributionActionResultEnum result = DistributionActionResultEnum.SUCCESS; + + if (conf == null) { + result = DistributionActionResultEnum.CONFIGURATION_IS_MISSING; + } else if (conf.getConsumerID() == null || conf.getConsumerID().isEmpty()) { + result = DistributionActionResultEnum.CONF_MISSING_CONSUMER_ID; + } else if (conf.getUser() == null || conf.getUser().isEmpty()) { + result = DistributionActionResultEnum.CONF_MISSING_USERNAME; + } else if (conf.getPassword() == null || conf.getPassword().isEmpty()) { + result = DistributionActionResultEnum.CONF_MISSING_PASSWORD; + } else if (conf.getMsgBusAddress() == null || conf.getMsgBusAddress().isEmpty()) { + result = DistributionActionResultEnum.CONF_MISSING_MSG_BUS_ADDRESS; + } else if (conf.getAsdcAddress() == null || conf.getAsdcAddress().isEmpty()) { + result = DistributionActionResultEnum.CONF_MISSING_ASDC_FQDN; + } else if (!isValidFqdn(conf.getAsdcAddress())) { + result = DistributionActionResultEnum.CONF_INVALID_ASDC_FQDN; + } else if (!isValidFqdns(conf.getMsgBusAddress())){ + result = DistributionActionResultEnum.CONF_INVALID_MSG_BUS_ADDRESS; + } else if (conf.getEnvironmentName() == null || conf.getEnvironmentName().isEmpty()) { + result = DistributionActionResultEnum.CONF_MISSING_ENVIRONMENT_NAME; + } else if (conf.getRelevantArtifactTypes() == null || conf.getRelevantArtifactTypes().isEmpty()) { + result = DistributionActionResultEnum.CONF_MISSING_ARTIFACT_TYPES; + } + else if( conf.isConsumeProduceStatusTopic() && Objects.isNull(statusCallback) ){ + result = DistributionActionResultEnum.CONF_INVALID_CONSUME_PRODUCE_STATUS_TOPIC_FALG; + } + // DistributionActionResultEnum.SUCCESS + else { + handleValidConf(conf); + } + + if (result != DistributionActionResultEnum.SUCCESS) { + + DistributionClientResultImpl initResult = new DistributionClientResultImpl(result, "configuration is invalid: " + result.name()); + + log.error(initResult.toString()); + errorWrapper.setInnerElement(initResult); + } + return result; + } + + private void handleValidConf(IConfiguration conf) { + this.configuration = new Configuration(conf); + if (!isPollingIntervalValid(conf.getPollingInterval())) { + configuration.setPollingInterval(DistributionClientConstants.MIN_POLLING_INTERVAL_SEC); + } + if (!isPollingTimeoutValid(conf.getPollingTimeout())) { + configuration.setPollingTimeout(DistributionClientConstants.POLLING_TIMEOUT_SEC); + } + if (conf.getConsumerGroup() == null) { + generateConsumerGroup(); + } + + //Default use HTTPS with DMAAP + if (conf.isUseHttpsWithDmaap() == null){ + configuration.setUseHttpsWithDmaap(true); + } + } + + private void generateConsumerGroup() { + String generatedConsumerGroup = UUID.randomUUID().toString(); + configuration.setConsumerGroup(generatedConsumerGroup); + isConsumerGroupGenerated = true; + } + + protected boolean isValidFqdn(String fqdn) { + try { + Matcher matcher = DistributionClientConstants.FQDN_PATTERN.matcher(fqdn); + return matcher.matches(); + } catch (Exception e) { + } + return false; + } + protected boolean isValidFqdns(List fqdns) { + if (fqdns != null && !fqdns.isEmpty()) { + for (String fqdn : fqdns) { + if (isValidFqdn(fqdn)) { + continue; + } else { + return false; + } + } + return true; + } + return false; + } + + private void shutdownExecutor() { + if (executorPool == null) + return; + + executorPool.shutdown(); // Disable new tasks from being submitted + try { + // Wait a while for existing tasks to terminate + if (!executorPool.awaitTermination(60, TimeUnit.SECONDS)) { + executorPool.shutdownNow(); // Cancel currently executing tasks + // Wait a while for tasks to respond to being cancelled + if (!executorPool.awaitTermination(60, TimeUnit.SECONDS)) + log.error("Pool did not terminate"); + } + } catch (InterruptedException ie) { + // (Re-)Cancel if current thread also interrupted + executorPool.shutdownNow(); + // Preserve interrupt status + Thread.currentThread().interrupt(); + } finally { + isStarted = false; + } + } + + private void validateRunReady(Wrapper errorWrapper) { + if (errorWrapper.isEmpty()) { + validateInitilized(errorWrapper); + } + if (errorWrapper.isEmpty()) { + validateNotTerminated(errorWrapper); + } + + } + + private void validateInitilized(Wrapper errorWrapper) { + if (!isInitialized) { + log.debug("client was not initialized"); + IDistributionClientResult result = new DistributionClientResultImpl(DistributionActionResultEnum.DISTRIBUTION_CLIENT_NOT_INITIALIZED, "distribution client was not initialized"); + errorWrapper.setInnerElement(result); + } + } + + private void validateNotStarted(Wrapper errorWrapper) { + if (isStarted) { + log.debug("client already started"); + IDistributionClientResult result = new DistributionClientResultImpl(DistributionActionResultEnum.DISTRIBUTION_CLIENT_ALREADY_STARTED, "distribution client already started"); + errorWrapper.setInnerElement(result); + } + } + + private void validateNotTerminated(Wrapper errorWrapper) { + if (isTerminated) { + log.debug("client was terminated"); + IDistributionClientResult result = new DistributionClientResultImpl(DistributionActionResultEnum.DISTRIBUTION_CLIENT_IS_TERMINATED, "distribution client was terminated"); + errorWrapper.setInnerElement(result); + } + } + + private boolean isPollingTimeoutValid(int timeout) { + boolean isValid = (timeout >= DistributionClientConstants.POLLING_TIMEOUT_SEC); + if (!isValid) { + log.warn("polling interval is out of range. value should be greater than or equals to " + DistributionClientConstants.POLLING_TIMEOUT_SEC); + log.warn("setting polling interval to default: " + DistributionClientConstants.POLLING_TIMEOUT_SEC); + } + return isValid; + } + + private boolean isPollingIntervalValid(int pollingInt) { + boolean isValid = (pollingInt >= DistributionClientConstants.MIN_POLLING_INTERVAL_SEC); + if (!isValid) { + log.warn("polling interval is out of range. value should be greater than or equals to " + DistributionClientConstants.MIN_POLLING_INTERVAL_SEC); + log.warn("setting polling interval to default: " + DistributionClientConstants.MIN_POLLING_INTERVAL_SEC); + } + return isValid; + } + + private synchronized void initCambriaClient(Wrapper errorWrapper) { + if (cambriaIdentityManager == null) { + try { + AbstractAuthenticatedManagerBuilder managerBuilder = new IdentityManagerBuilder().usingHosts(brokerServers); + if (configuration.isUseHttpsWithDmaap()){ + managerBuilder = managerBuilder.usingHttps(); + } + cambriaIdentityManager = managerBuilder.build(); + } catch (MalformedURLException | GeneralSecurityException e) { + handleCambriaInitFailure(errorWrapper, e); + } + } + } + + private void handleCambriaInitFailure(Wrapper errorWrapper, Exception e) { + final String errorMessage = "Failed initilizing cambria component:" + e.getMessage(); + IDistributionClientResult errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.CAMBRIA_INIT_FAILED, errorMessage); + errorWrapper.setInnerElement(errorResponse); + log.error(errorMessage); + log.debug(errorMessage, e); + } + + @Override + public IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage statusMessage, String errorReason) { + log.info("DistributionClient - sendDownloadStatus with errorReason"); + Wrapper errorWrapper = new Wrapper<>(); + validateRunReady(errorWrapper); + if (!errorWrapper.isEmpty()) { + return errorWrapper.getInnerElement(); + } + + return sendStatus(DistributionStatusMessageJsonBuilderFactory.getErrorReasonBuilder(statusMessage, errorReason)); + + } + + @Override + public IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage statusMessage, String errorReason) { + log.info("DistributionClient - sendDeploymentStatus with errorReason"); + Wrapper errorWrapper = new Wrapper<>(); + validateRunReady(errorWrapper); + if (!errorWrapper.isEmpty()) { + return errorWrapper.getInnerElement(); + } + return sendStatus(DistributionStatusMessageJsonBuilderFactory.getErrorReasonBuilder(statusMessage, errorReason)); + + } + + @Override + public IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage) { + log.info("DistributionClient - sendComponentDone status"); + Wrapper errorWrapper = new Wrapper<>(); + validateRunReady(errorWrapper); + if (!errorWrapper.isEmpty()) { + return errorWrapper.getInnerElement(); + } + return sendStatus(DistributionStatusMessageJsonBuilderFactory.getSimpleBuilder(statusMessage)); + + } + + @Override + public IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage, + String errorReason) { + log.info("DistributionClient - sendComponentDone status with errorReason"); + Wrapper errorWrapper = new Wrapper<>(); + validateRunReady(errorWrapper); + if (!errorWrapper.isEmpty()) { + return errorWrapper.getInnerElement(); + } + return sendStatus(DistributionStatusMessageJsonBuilderFactory.getErrorReasonBuilder(statusMessage, errorReason)); + } + + + @Override + public List decodeVfModuleArtifact(byte[] artifactPayload) { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String vfModuleJsonString = new String(artifactPayload, StandardCharsets.UTF_8); + final Type type = new TypeToken>() { + }.getType(); + List vfModules = gson.fromJson(vfModuleJsonString, type); + return vfModules; + } + + + public IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage) { + log.info("DistributionClient - sendFinalDistributionStatus status"); + Wrapper errorWrapper = new Wrapper<>(); + validateRunReady(errorWrapper); + if (!errorWrapper.isEmpty()) { + return errorWrapper.getInnerElement(); + } + return sendStatus(DistributionStatusMessageJsonBuilderFactory.getSimpleBuilder(statusMessage)); + + } + + + @Override + public IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage, + String errorReason) { + log.info("DistributionClient - sendFinalDistributionStatus status with errorReason"); + Wrapper errorWrapper = new Wrapper<>(); + validateRunReady(errorWrapper); + if (!errorWrapper.isEmpty()) { + return errorWrapper.getInnerElement(); + } + return sendStatus(DistributionStatusMessageJsonBuilderFactory.getErrorReasonBuilder(statusMessage, errorReason)); + + + } + + public Either,IDistributionClientResult> getUEBServerList() { + List msgBusAddresses = configuration.getMsgBusAddress(); + if(msgBusAddresses.isEmpty()){ + return Either.right(new DistributionClientResultImpl(DistributionActionResultEnum.CONF_MISSING_MSG_BUS_ADDRESS, "Message bus address was not found in the config file")); + } + else{ + return GeneralUtils.convertToValidHostName(msgBusAddresses); + } + } + + + + + + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientResultImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientResultImpl.java new file mode 100644 index 0000000..0df0b7b --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientResultImpl.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl; + +import org.onap.sdc.api.results.IDistributionClientResult; +import org.onap.sdc.utils.DistributionActionResultEnum; + +public class DistributionClientResultImpl implements IDistributionClientResult { + + DistributionActionResultEnum responseStatus; + String responseMessage; + + public DistributionClientResultImpl(DistributionActionResultEnum responseStatus, String responseMessage) { + this.responseStatus = responseStatus; + this.responseMessage = responseMessage; + } + + @Override + public DistributionActionResultEnum getDistributionActionResult() { + return responseStatus; + } + + @Override + public String getDistributionMessageResult() { + return responseMessage; + } + + @Override + public String toString() { + return "DistributionClientResultImpl [responseStatus=" + responseStatus + ", responseMessage=" + responseMessage + "]"; + } +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionStatusMessageImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionStatusMessageImpl.java new file mode 100644 index 0000000..d5bc4ce --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionStatusMessageImpl.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl; + +import org.onap.sdc.api.consumer.IComponentDoneStatusMessage; +import org.onap.sdc.api.consumer.IDistributionStatusMessage; +import org.onap.sdc.api.consumer.IFinalDistrStatusMessage; +import org.onap.sdc.utils.DistributionStatusEnum; + +class DistributionStatusMessageImpl implements IDistributionStatusMessage { + + String distributionID; + String consumerID; + long timestamp; + String artifactURL; + DistributionStatusEnum status; + String errorReason; + private String componentName; + + public DistributionStatusMessageImpl(IDistributionStatusMessage message) { + super(); + distributionID = message.getDistributionID(); + consumerID = message.getConsumerID(); + timestamp = message.getTimestamp(); + artifactURL = message.getArtifactURL(); + status = message.getStatus(); + + } + + public DistributionStatusMessageImpl(IComponentDoneStatusMessage message) { + super(); + distributionID = message.getDistributionID(); + consumerID = message.getConsumerID(); + timestamp = message.getTimestamp(); + artifactURL = message.getArtifactURL(); + status = message.getStatus(); + componentName = message.getComponentName(); + } + + public DistributionStatusMessageImpl(IFinalDistrStatusMessage message) { + super(); + distributionID = message.getDistributionID(); + consumerID = message.getConsumerID(); + timestamp = message.getTimestamp(); + + artifactURL = ""; + status = message.getStatus(); + componentName = message.getComponentName(); + } + + @Override + public String getDistributionID() { + + return distributionID; + } + + @Override + public String getConsumerID() { + + return consumerID; + } + + @Override + public long getTimestamp() { + + return timestamp; + } + + @Override + public String getArtifactURL() { + + return artifactURL; + } + + @Override + public DistributionStatusEnum getStatus() { + + return status; + } + + public String getErrorReason() { + return errorReason; + } + + public void setErrorReason(String errorReason) { + this.errorReason = errorReason; + } + + public String getComponentName() { + return componentName; + } + + + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionStatusMessageJsonBuilderFactory.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionStatusMessageJsonBuilderFactory.java new file mode 100644 index 0000000..d8c722d --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionStatusMessageJsonBuilderFactory.java @@ -0,0 +1,148 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl; + +import org.onap.sdc.api.IDistributionStatusMessageJsonBuilder; +import org.onap.sdc.api.consumer.IComponentDoneStatusMessage; +import org.onap.sdc.api.consumer.IDistributionStatusMessage; +import org.onap.sdc.api.consumer.IFinalDistrStatusMessage; +import org.onap.sdc.utils.DistributionStatusEnum; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class DistributionStatusMessageJsonBuilderFactory { + static Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + public static IDistributionStatusMessageJsonBuilder getSimpleBuilder(IDistributionStatusMessage statusMessage){ + DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage); + + return prepareBuilderFromImpl(message); + } + + public static IDistributionStatusMessageJsonBuilder getSimpleBuilder(IComponentDoneStatusMessage statusMessage){ + DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage); + + return prepareBuilderFromImpl(message); + } + + public static IDistributionStatusMessageJsonBuilder getSimpleBuilder(IFinalDistrStatusMessage statusMessage){ + DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage); + + return prepareBuilderFromImpl(message); + } + + public static IDistributionStatusMessageJsonBuilder getErrorReasonBuilder(IDistributionStatusMessage statusMessage, String errorReason){ + DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage); + message.setErrorReason(errorReason); + + return prepareBuilderFromImpl(message); + } + + public static IDistributionStatusMessageJsonBuilder getErrorReasonBuilder(IComponentDoneStatusMessage statusMessage, + String errorReason) { + DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage); + message.setErrorReason(errorReason); + return prepareBuilderFromImpl(message); + } + + public static IDistributionStatusMessageJsonBuilder getErrorReasonBuilder(IFinalDistrStatusMessage statusMessage, + String errorReason) { + DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage); + message.setErrorReason(errorReason); + return prepareBuilderFromImpl(message); + } + + static IDistributionStatusMessageJsonBuilder prepareBuilderForNotificationStatus(final String consumerId, final long currentTimeMillis, final String distributionId, + final ArtifactInfoImpl artifactInfo, boolean isNotified){ + + final DistributionStatusEnum fakeStatusToReplace = DistributionStatusEnum.DOWNLOAD_OK; + final String jsonRequest = buildDistributionStatusJson(consumerId, currentTimeMillis, distributionId, artifactInfo, fakeStatusToReplace); + + DistributionStatusNotificationEnum notificationStatus = isNotified ? DistributionStatusNotificationEnum.NOTIFIED : DistributionStatusNotificationEnum.NOT_NOTIFIED; + final String changedRequest = jsonRequest.replace(fakeStatusToReplace.name(), notificationStatus.name()); + IDistributionStatusMessageJsonBuilder builder = new IDistributionStatusMessageJsonBuilder() { + @Override + public String build() { + return changedRequest; + } + }; + return builder; + + } + + private static String buildDistributionStatusJson(final String consumerId, + final long currentTimeMillis, final String distributionId, + final ArtifactInfoImpl artifactInfo, + final DistributionStatusEnum fakeStatusToBeReplaced) { + IDistributionStatusMessage statusMessage = new IDistributionStatusMessage() { + @Override + public long getTimestamp() { + return currentTimeMillis; + } + + @Override + public DistributionStatusEnum getStatus() { + + return fakeStatusToBeReplaced; + } + + @Override + public String getDistributionID() { + return distributionId; + } + + @Override + public String getConsumerID() { + return consumerId; + } + + @Override + public String getArtifactURL() { + return artifactInfo.getArtifactURL(); + } + }; + + DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage); + final String jsonRequest = gson.toJson(message); + return jsonRequest; + } + + private static IDistributionStatusMessageJsonBuilder prepareBuilderFromImpl( DistributionStatusMessageImpl message) { + final String jsonRequest = gson.toJson(message); + IDistributionStatusMessageJsonBuilder builder = new IDistributionStatusMessageJsonBuilder() { + @Override + public String build() { + return jsonRequest; + } + }; + return builder; + } + + private enum DistributionStatusNotificationEnum { + NOTIFIED, NOT_NOTIFIED + } + + + + + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/JsonContainerResourceInstance.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/JsonContainerResourceInstance.java new file mode 100644 index 0000000..92dad7b --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/JsonContainerResourceInstance.java @@ -0,0 +1,158 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.IResourceInstance; + +class JsonContainerResourceInstance implements IResourceInstance { + JsonContainerResourceInstance (){} + private String resourceInstanceName; + private String resourceCustomizationUUID; + private String resourceName; + private String resourceVersion; + private String resoucreType; + private String resourceUUID; + private String resourceInvariantUUID; + private String category; + private String subcategory; + private List artifacts; + + private JsonContainerResourceInstance(IResourceInstance resourceInstance){ + resourceInstanceName = resourceInstance.getResourceInstanceName(); + resourceCustomizationUUID = resourceInstance.getResourceCustomizationUUID(); + resourceName = resourceInstance.getResourceName(); + resourceVersion = resourceInstance.getResourceVersion(); + resoucreType = resourceInstance.getResourceType(); + resourceUUID = resourceInstance.getResourceUUID(); + resourceInvariantUUID = resourceInstance.getResourceInvariantUUID(); + category = resourceInstance.getCategory(); + subcategory = resourceInstance.getSubcategory(); + artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(resourceInstance.getArtifacts()); + } + + public static List convertToJsonContainer(List resources){ + List buildResources = new ArrayList(); + if( resources != null ){ + for( IResourceInstance resourceInstance : resources ){ + buildResources.add(new JsonContainerResourceInstance(resourceInstance)); + } + } + return buildResources; + } + + @Override + public String getResourceInstanceName() { + return resourceInstanceName; + } + + public void setResourceInstanceName(String resourceInstanceName) { + this.resourceInstanceName = resourceInstanceName; + } + + @Override + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + @Override + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + @Override + public String getResourceType() { + return resoucreType; + } + + public void setResoucreType(String resoucreType) { + this.resoucreType = resoucreType; + } + + @Override + public String getResourceUUID() { + return resourceUUID; + } + + public void setResourceUUID(String resourceUUID) { + this.resourceUUID = resourceUUID; + } + + @Override + public List getArtifacts() { + List temp = new ArrayList(); + if( artifacts != null ){ + temp.addAll(artifacts); + } + return temp; + } + + public void setArtifacts(List artifacts) { + this.artifacts = artifacts; + } + + public List getArtifactsImpl(){ + return artifacts; + } + + @Override + public String getResourceInvariantUUID() { + return resourceInvariantUUID; + } + + public void setResourceInvariantUUID(String resourceInvariantUUID) { + this.resourceInvariantUUID = resourceInvariantUUID; + } + public String getResourceCustomizationUUID() { + return resourceCustomizationUUID; + } + + public void setResourceCustomizationUUID(String resourceCustomizationUUID) { + this.resourceCustomizationUUID = resourceCustomizationUUID; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getSubcategory() { + return subcategory; + } + + public void setSubcategory(String subcategory) { + this.subcategory = subcategory; + } +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/NotificationConsumer.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/NotificationConsumer.java new file mode 100644 index 0000000..aab1e29 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/NotificationConsumer.java @@ -0,0 +1,181 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.IResourceInstance; +import org.onap.sdc.api.results.IDistributionClientResult; +import org.onap.sdc.utils.DistributionActionResultEnum; +import org.onap.sdc.api.consumer.INotificationCallback; +import org.onap.sdc.api.notification.INotificationData; +import org.onap.sdc.utils.ArtifactTypeEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.nsa.cambria.client.CambriaConsumer; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +class NotificationConsumer implements Runnable { + + private static Logger log = LoggerFactory.getLogger(NotificationConsumer.class.getName()); + + private CambriaConsumer cambriaConsumer; + private INotificationCallback clientCallback; + private List artifactsTypes; + private DistributionClientImpl distributionClient; + + public NotificationConsumer(CambriaConsumer cambriaConsumer, INotificationCallback clientCallback, List artifactsTypes, DistributionClientImpl distributionClient) { + this.cambriaConsumer = cambriaConsumer; + this.clientCallback = clientCallback; + this.artifactsTypes = artifactsTypes; + this.distributionClient = distributionClient; + } + + @Override + public void run() { + + try { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + long currentTimeMillis = System.currentTimeMillis(); + for (String notificationMsg : cambriaConsumer.fetch()) { + log.debug("received message from topic"); + log.debug("recieved notification from broker: {}", notificationMsg); + + final NotificationDataImpl notificationFromUEB = gson.fromJson(notificationMsg, NotificationDataImpl.class); + NotificationDataImpl notificationForCallback = buildCallbackNotificationLogic(currentTimeMillis, notificationFromUEB); + if (isActivateCallback(notificationForCallback)) { + String stringNotificationForCallback = gson.toJson(notificationForCallback); + log.debug("sending notification to client: {}", stringNotificationForCallback); + clientCallback.activateCallback(notificationForCallback); + } + } + + } catch (Exception e) { + log.error("Error exception occured when fetching with Cambria Client:{}", e.getMessage()); + log.debug("Error exception occured when fetching with Cambria Client:{}", e.getMessage(), e); + } + } + + private boolean isActivateCallback(NotificationDataImpl notificationForCallback) { + boolean hasRelevantArtifactsInResourceInstance = notificationForCallback.getResources() != null && !notificationForCallback.getResources().isEmpty(); + boolean hasRelevantArtifactsInService = notificationForCallback.getServiceArtifacts() != null && !notificationForCallback.getServiceArtifacts().isEmpty(); + + return hasRelevantArtifactsInResourceInstance || hasRelevantArtifactsInService; + } + + protected NotificationDataImpl buildCallbackNotificationLogic(long currentTimeMillis, final NotificationDataImpl notificationFromUEB) { + List relevantResourceInstances = buildResourceInstancesLogic(notificationFromUEB, currentTimeMillis); + List relevantServiceArtifacts = handleRelevantArtifacts(notificationFromUEB, currentTimeMillis, notificationFromUEB.getServiceArtifactsImpl()); + notificationFromUEB.setResources(relevantResourceInstances); + notificationFromUEB.setServiceArtifacts(relevantServiceArtifacts); + return notificationFromUEB; + } + + private List buildResourceInstancesLogic(NotificationDataImpl notificationFromUEB, long currentTimeMillis) { + + List relevantResourceInstances = new ArrayList<>(); + + for (JsonContainerResourceInstance resourceInstance : notificationFromUEB.getResourcesImpl()) { + final List artifactsImplList = resourceInstance.getArtifactsImpl(); + List foundRelevantArtifacts = handleRelevantArtifacts(notificationFromUEB, currentTimeMillis, artifactsImplList); + if (!foundRelevantArtifacts.isEmpty() || distributionClient.getConfiguration().isFilterInEmptyResources()) { + resourceInstance.setArtifacts(foundRelevantArtifacts); + relevantResourceInstances.add(resourceInstance); + } + } + return relevantResourceInstances; + + } + + private List handleRelevantArtifacts(NotificationDataImpl notificationFromUEB, long currentTimeMillis, final List artifactsImplList) { + List relevantArtifacts = new ArrayList<>(); + if (artifactsImplList != null) { + for (ArtifactInfoImpl artifactInfo : artifactsImplList) { + handleRelevantArtifact(notificationFromUEB, currentTimeMillis, artifactsImplList, relevantArtifacts, artifactInfo); + } + } + return relevantArtifacts; + } + + private void handleRelevantArtifact(NotificationDataImpl notificationFromUEB, long currentTimeMillis, final List artifactsImplList, List relevantArtifacts, ArtifactInfoImpl artifactInfo) { + boolean isArtifactRelevant = artifactsTypes.contains(artifactInfo.getArtifactType()); + String artifactType = artifactInfo.getArtifactType(); + if (artifactInfo.getGeneratedFromUUID() != null && !artifactInfo.getGeneratedFromUUID().isEmpty()) { + IArtifactInfo generatedFromArtInfo = findGeneratedFromArtifact(artifactInfo.getGeneratedFromUUID(), artifactsImplList); + if (generatedFromArtInfo != null) + isArtifactRelevant = isArtifactRelevant && artifactsTypes.contains(generatedFromArtInfo.getArtifactType()); + else + isArtifactRelevant = false; + } + if (isArtifactRelevant) { + setRelatedArtifacts(artifactInfo, notificationFromUEB); + if (artifactType.equals(ArtifactTypeEnum.HEAT.name()) || artifactType.equals(ArtifactTypeEnum.HEAT_VOL.name()) || artifactType.equals(ArtifactTypeEnum.HEAT_NET.name())) { + setGeneratedArtifact(artifactsImplList, artifactInfo); + } + relevantArtifacts.add(artifactInfo); + + } + IDistributionClientResult notificationStatus = distributionClient.sendNotificationStatus(currentTimeMillis, notificationFromUEB.getDistributionID(), artifactInfo, isArtifactRelevant); + if (notificationStatus.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) { + log.error("Error failed to send notification status to UEB failed status:{}, error message:{}", notificationStatus.getDistributionActionResult().name(), notificationStatus.getDistributionMessageResult()); + } + } + + private void setRelatedArtifacts(ArtifactInfoImpl artifact, INotificationData notificationData) { + if (artifact.getRelatedArtifactsUUID() != null) { + List relatedArtifacts = new ArrayList<>(); + for (String relatedArtifactUUID : artifact.getRelatedArtifactsUUID()) { + relatedArtifacts.add(notificationData.getArtifactMetadataByUUID(relatedArtifactUUID)); + } + artifact.setRelatedArtifactsInfo(relatedArtifacts); + } + + } + + private void setGeneratedArtifact(final List artifactsImplList, ArtifactInfoImpl artifactInfo) { + IArtifactInfo found = null; + String artifactUUID = artifactInfo.getArtifactUUID(); + for (ArtifactInfoImpl generatedArtifactInfo : artifactsImplList) { + if (generatedArtifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.name()) && artifactUUID.equals(generatedArtifactInfo.getGeneratedFromUUID())) { + found = generatedArtifactInfo; + break; + } + } + + artifactInfo.setGeneratedArtifact(found); + } + + private IArtifactInfo findGeneratedFromArtifact(String getGeneratedFromUUID, List list) { + IArtifactInfo found = null; + for (ArtifactInfoImpl artifactInfo : list) { + if (getGeneratedFromUUID.equals(artifactInfo.getArtifactUUID())) { + found = artifactInfo; + break; + } + } + return found; + } + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/NotificationDataImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/NotificationDataImpl.java new file mode 100644 index 0000000..7b7b532 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/NotificationDataImpl.java @@ -0,0 +1,179 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.sdc.api.notification.IResourceInstance; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.INotificationData; + + +class NotificationDataImpl implements INotificationData { + + private String distributionID; + private String serviceName; + private String serviceVersion; + private String serviceUUID; + private String serviceDescription; + private String serviceInvariantUUID; + private List resources; + private List serviceArtifacts; + private String workloadContext; + + @Override + public String getDistributionID() { + return distributionID; + } + + @Override + public String getServiceName() { + return serviceName; + } + + @Override + public String getServiceVersion() { + return serviceVersion; + } + + @Override + public String getServiceUUID() { + return serviceUUID; + } + + public void setDistributionID(String distributionID) { + this.distributionID = distributionID; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public void setServiceVersion(String serviceVersion) { + this.serviceVersion = serviceVersion; + } + + public void setServiceUUID(String serviceUUID) { + this.serviceUUID = serviceUUID; + } + + + + public String getServiceDescription() { + return serviceDescription; + } + + public void setServiceDescription(String serviceDescription) { + this.serviceDescription = serviceDescription; + } + + @Override + public String getWorkloadContext() { + return workloadContext; + } + + @Override + public void setWorkloadContext(String workloadContext) { + this.workloadContext = workloadContext; + } + + @Override + public String toString() { + return "NotificationDataImpl [distributionID=" + distributionID + ", serviceName=" + serviceName + + ", serviceVersion=" + serviceVersion + ", serviceUUID=" + serviceUUID + ", serviceDescription=" + + serviceDescription + ", serviceInvariantUUID=" + serviceInvariantUUID + ", resources=" + resources + + ", serviceArtifacts=" + serviceArtifacts + ", workloadContext=" + workloadContext + "]"; + } + + @Override + public List getResources() { + List ret = new ArrayList(); + if( resources != null ){ + ret.addAll(resources); + } + return ret; + } + + public void setResources(List resources){ + this.resources = JsonContainerResourceInstance.convertToJsonContainer(resources); + } + + public List getResourcesImpl(){ + return resources; + } + + List getServiceArtifactsImpl(){ + return serviceArtifacts; + } + + @Override + public List getServiceArtifacts() { + + List temp = new ArrayList(); + if( serviceArtifacts != null ){ + temp.addAll(serviceArtifacts); + } + return temp; + } + + void setServiceArtifacts(List relevantServiceArtifacts) { + serviceArtifacts = relevantServiceArtifacts; + + } + + @Override + public String getServiceInvariantUUID() { + return serviceInvariantUUID; + } + + + public void setServiceInvariantUUID(String serviceInvariantUUID) { + this.serviceInvariantUUID = serviceInvariantUUID; + } + @Override + public IArtifactInfo getArtifactMetadataByUUID(String artifactUUID){ + IArtifactInfo ret = findArtifactInfoByUUID(artifactUUID, serviceArtifacts); + if( ret == null && resources != null ){ + for( JsonContainerResourceInstance currResourceInstance : resources ){ + ret = findArtifactInfoByUUID(artifactUUID, currResourceInstance.getArtifactsImpl()); + if( ret != null ){ + break; + } + } + } + return ret; + + } + + private IArtifactInfo findArtifactInfoByUUID(String artifactUUID, List listToCheck) { + IArtifactInfo ret = null; + if( listToCheck != null ){ + for(IArtifactInfo curr: listToCheck ){ + if(curr.getArtifactUUID().equals(artifactUUID) ){ + ret = curr; + break; + } + } + } + return ret; + } +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusConsumer.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusConsumer.java new file mode 100644 index 0000000..49ba428 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusConsumer.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl; + +import org.onap.sdc.api.consumer.IStatusCallback; +import org.onap.sdc.api.notification.IStatusData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.nsa.cambria.client.CambriaConsumer; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +class StatusConsumer implements Runnable { + + private static Logger log = LoggerFactory.getLogger(StatusConsumer.class.getName()); + + private CambriaConsumer cambriaConsumer; + private IStatusCallback clientCallback; + + public StatusConsumer(CambriaConsumer cambriaConsumer, IStatusCallback clientCallback) { + this.cambriaConsumer = cambriaConsumer; + this.clientCallback = clientCallback; + } + + @Override + public void run() { + + try { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + for (String statusMsg : cambriaConsumer.fetch()) { + log.debug("received message from topic"); + log.debug("recieved notification from broker: {}", statusMsg); + IStatusData statusData = gson.fromJson(statusMsg, StatusDataImpl.class); + clientCallback.activateCallback(statusData); + + + } + + } catch (Exception e) { + log.error("Error exception occured when fetching with Cambria Client:{}", e.getMessage()); + log.debug("Error exception occured when fetching with Cambria Client:{}", e.getMessage(), e); + } + } + + + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusDataImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusDataImpl.java new file mode 100644 index 0000000..70513fe --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusDataImpl.java @@ -0,0 +1,95 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl; + +import org.onap.sdc.api.notification.IStatusData; +import org.onap.sdc.utils.DistributionStatusEnum; + +public class StatusDataImpl implements IStatusData { + + String distributionID; + String consumerID; + long timestamp; + String artifactURL; + DistributionStatusEnum status; + String componentName; + String errorReason; + + @Override + public String getDistributionID() { + return distributionID; + } + + public void setDistributionID(String distributionId) { + this.distributionID = distributionId; + } + @Override + public String getConsumerID() { + return consumerID; + } + + public void setConsumerID(String consumerId) { + this.consumerID = consumerId; + } + @Override + public Long getTimestamp() { + return timestamp; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + @Override + public String getArtifactURL() { + return artifactURL; + } + + public void setArtifactURL(String artifactURL) { + this.artifactURL = artifactURL; + } + @Override + public DistributionStatusEnum getStatus() { + return status; + } + + public void setStatus(DistributionStatusEnum status) { + this.status = status; + } + + + @Override + public String toString() { + return "StatusDataImpl [distributionId=" + distributionID + ", consumerId=" + consumerID + ", timestamp=" + timestamp + ", artifactURL=" + artifactURL + ", status=" + status +", errorReason=" + errorReason+ "]"; + } + @Override + public String getComponentName() { + return componentName; + } + + @Override + public String getErrorReason() { + return errorReason; + } + + + + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/VfModuleMetadata.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/VfModuleMetadata.java new file mode 100644 index 0000000..fb745f3 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/VfModuleMetadata.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl; + +import java.util.List; + +import org.onap.sdc.api.notification.IVfModuleMetadata; + +final class VfModuleMetadata implements IVfModuleMetadata { + private VfModuleMetadata(){ + //This Class is only built by parsing Json + } + + private String vfModuleModelName; + private String vfModuleModelInvariantUUID; + private String vfModuleModelVersion; + private String vfModuleModelUUID; + private String vfModuleModelDescription; + private boolean isBase; + private List artifacts; + + public String getVfModuleModelName() { + return vfModuleModelName; + } + public String getVfModuleModelInvariantUUID() { + return vfModuleModelInvariantUUID; + } + public String getVfModuleModelVersion() { + return vfModuleModelVersion; + } + public String getVfModuleModelUUID() { + return vfModuleModelUUID; + } + public String getVfModuleModelDescription() { + return vfModuleModelDescription; + } + public boolean isBase() { + return isBase; + } + public List getArtifacts() { + return artifacts; + } +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientDownloadResultStubImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientDownloadResultStubImpl.java new file mode 100644 index 0000000..e0cd56e --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientDownloadResultStubImpl.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl.mock; + +import org.onap.sdc.api.results.IDistributionClientDownloadResult; + +/** Mock Implementation */ +public class DistributionClientDownloadResultStubImpl extends DistributionClientResultStubImpl implements IDistributionClientDownloadResult { + + @Override + public byte[] getArtifactPayload() { + String mockPayload = "heat_template_version: 2013-05-23\r\n" + + "\r\n" + + "description: >\r\n" + + " HOT template that creates one COR network (direct).\r\n" + + "\r\n" + + "parameters:\r\n" + + " cor_direct_net_name:\r\n" + + " type: string\r\n" + + " description: Name of COR direct network\r\n" + + " cor_direct_net_cidr:\r\n" + + " type: string\r\n" + + " description: Direct network address (CIDR notation)\r\n" + + " cor_direct_net_gateway:\r\n" + + " type: string\r\n" + + " description: Direct network gateway address\r\n" + + " cor_direct_net_RT:\r\n" + + " type: string\r\n" + + " description: Direct network route-target (RT)\r\n" + + "\r\n" + + "resources:\r\n" + + " cor_direct_net:\r\n" + + " type: OS::Contrail::VirtualNetwork\r\n" + + " properties:\r\n" + + " name: { get_param: cor_direct_net_name }\r\n" + + " route_targets: [ get_param: cor_direct_net_RT ]\r\n" + + "\r\n" + + " cor_direct_ip_subnet:\r\n" + + " type: OS::Neutron::Subnet\r\n" + + " properties:\r\n" + + " network_id: { get_resource: cor_direct_net }\r\n" + + " cidr: {get_param: cor_direct_net_cidr}\r\n" + + " gateway_ip: { get_param: cor_direct_net_gateway }\r\n"; + + return mockPayload.getBytes(); + } + + @Override + public String getArtifactName() { + // TODO Auto-generated method stub + return "MackArtifactName"; + } + + @Override + public String getArtifactFilename() { + // TODO Auto-generated method stub + return "MackArtifactName"; + } + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientResultStubImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientResultStubImpl.java new file mode 100644 index 0000000..cf0466b --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientResultStubImpl.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl.mock; + +import org.onap.sdc.api.results.IDistributionClientResult; +import org.onap.sdc.utils.DistributionActionResultEnum; +/** Mock Implementation */ +public class DistributionClientResultStubImpl implements IDistributionClientResult { + @Override + public DistributionActionResultEnum getDistributionActionResult() { + return DistributionActionResultEnum.SUCCESS; + } + + @Override + public String getDistributionMessageResult() { + return "Stub Result, method not implemented!"; + } + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientStubImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientStubImpl.java new file mode 100644 index 0000000..9049215 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientStubImpl.java @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl.mock; + +import java.util.List; + +import org.onap.sdc.api.IDistributionClient; +import org.onap.sdc.api.consumer.*; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.IVfModuleMetadata; +import org.onap.sdc.api.results.IDistributionClientDownloadResult; +import org.onap.sdc.api.results.IDistributionClientResult; +import org.onap.sdc.api.consumer.*; + +/** Mock Implementation */ +public class DistributionClientStubImpl implements IDistributionClient { + + + public IDistributionClientResult updateConfiguration(IConfiguration newConf) { + return new DistributionClientResultStubImpl(); + } + + public IDistributionClientResult start() { + return new DistributionClientResultStubImpl(); + } + + public IDistributionClientResult stop() { + return new DistributionClientResultStubImpl(); + } + + public IDistributionClientResult sendDownloadStatus( IDistributionStatusMessage statusMessage) { + return new DistributionClientResultStubImpl(); + } + + public IDistributionClientResult sendDeploymentStatus( IDistributionStatusMessage statusMessage) { + return new DistributionClientResultStubImpl(); + } + + @Override + public IDistributionClientDownloadResult download(IArtifactInfo artifactInfo) { + return new DistributionClientDownloadResultStubImpl(); + } + + @Override + public IDistributionClientResult init(IConfiguration conf, INotificationCallback callback) { + return new DistributionClientResultStubImpl(); + } + + @Override + public IDistributionClientResult init(IConfiguration conf, INotificationCallback notificationCallback, + IStatusCallback statusCallback) { + return new DistributionClientResultStubImpl(); + } + + @Override + public IConfiguration getConfiguration() { + // TODO Auto-generated method stub + return null; + } + + @Override + public IDistributionClientResult sendDownloadStatus( + IDistributionStatusMessage statusMessage, String errorReason) { + // TODO Auto-generated method stub + return null; + } + + @Override + public IDistributionClientResult sendDeploymentStatus( + IDistributionStatusMessage statusMessage, String errorReason) { + // TODO Auto-generated method stub + return null; + } + + @Override + public IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage) { + return null; + } + + @Override + public IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage) { + return null; + } + + @Override + public List decodeVfModuleArtifact(byte[] artifactPayload) { + // TODO Auto-generated method stub + return null; + } + + @Override + public IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage, + String errorReason) { + // TODO Auto-generated method stub + return null; + } + + @Override + public IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage, String errorReason) { + // TODO Auto-generated method stub + return null; + } + + + + + + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/ArtifactTypeEnum.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/ArtifactTypeEnum.java new file mode 100644 index 0000000..8df257e --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/ArtifactTypeEnum.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.utils; + +public enum ArtifactTypeEnum { + HEAT, + HEAT_VOL, + HEAT_NET, + MURANO_PKG, + HEAT_ENV, + YANG_XML, + OTHER, + VF_LICENSE, + VENDOR_LICENSE, + MODEL_INVENTORY_PROFILE, + MODEL_QUERY_SPEC, + APPC_CONFIG, + VNF_CATALOG, + HEAT_NESTED, + HEAT_ARTIFACT, + VF_MODULES_METADATA, + //DCAE Artifacts + DCAE_TOSCA, DCAE_JSON, DCAE_POLICY, DCAE_DOC, + DCAE_EVENT, DCAE_INVENTORY_TOSCA, DCAE_INVENTORY_JSON, + DCAE_INVENTORY_POLICY, DCAE_INVENTORY_DOC, + DCAE_INVENTORY_BLUEPRINT, DCAE_INVENTORY_EVENT; + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionActionResultEnum.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionActionResultEnum.java new file mode 100644 index 0000000..fe871f8 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionActionResultEnum.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.utils; + +public enum DistributionActionResultEnum { + SUCCESS, + FAIL, + GENERAL_ERROR, + BAD_REQUEST, + DISTRIBUTION_CLIENT_NOT_INITIALIZED, + DISTRIBUTION_CLIENT_IS_TERMINATED, + DISTRIBUTION_CLIENT_ALREADY_INITIALIZED, + DISTRIBUTION_CLIENT_ALREADY_STARTED, + + DATA_INTEGRITY_PROBLEM, + ARTIFACT_NOT_FOUND, + + CONFIGURATION_IS_MISSING, + CONF_MISSING_USERNAME, + CONF_MISSING_PASSWORD, + CONF_MISSING_ASDC_FQDN, + CONF_MISSING_ARTIFACT_TYPES, + CONF_CONTAINS_INVALID_ARTIFACT_TYPES, + CONF_MISSING_CONSUMER_ID, + CONF_MISSING_ENVIRONMENT_NAME, + CONF_MISSING_CONSUMER_GROUP, + CONF_INVALID_ASDC_FQDN, + CONF_INVALID_CONSUME_PRODUCE_STATUS_TOPIC_FALG, + CONF_MISSING_MSG_BUS_ADDRESS, + CONF_INVALID_MSG_BUS_ADDRESS, + ASDC_AUTHENTICATION_FAILED, + ASDC_AUTHORIZATION_FAILED, + ASDC_NOT_FOUND, + ASDC_SERVER_PROBLEM, + ASDC_CONNECTION_FAILED, + ASDC_SERVER_TIMEOUT, + + CAMBRIA_INIT_FAILED, + UEB_KEYS_CREATION_FAILED +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionClientConstants.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionClientConstants.java new file mode 100644 index 0000000..1dcbca3 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionClientConstants.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.utils; + +import java.util.regex.Pattern; + +/** + * Constants Used By Distribution Client + * @author mshitrit + * + */ +public final class DistributionClientConstants { + public static final String CLIENT_DESCRIPTION = "ASDC Distribution Client Key for %s"; + public static final Pattern FQDN_PATTERN = Pattern.compile("^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*(:[0-9]{2,4})*$", Pattern.CASE_INSENSITIVE); + public static final String EMAIL = ""; + public static final int MIN_POLLING_INTERVAL_SEC = 15; + public static final int POOL_SIZE = 10; + public static final int POLLING_TIMEOUT_SEC = 15; + + public static final String HEADER_INSTANCE_ID = "X-ECOMP-InstanceID"; + public static final String HEADER_REQUEST_ID = "X-ECOMP-RequestID"; + public static final String APPLICATION_JSON = "application/json"; + public static final String HEADER_CONTENT_TYPE = "Content-Type"; + + private DistributionClientConstants(){ throw new UnsupportedOperationException();} +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionStatusEnum.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionStatusEnum.java new file mode 100644 index 0000000..e620195 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionStatusEnum.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.utils; + +public enum DistributionStatusEnum { + /**Can be sent when ONAP component successfully downloaded the specific artifact*/ + DOWNLOAD_OK, + + /**Can be sent when ONAP component failed to download the specific artifact (corrupted file)*/ + DOWNLOAD_ERROR, + + /**Can be sent only if the repeated distribution notification event is sent when the ONAP component already downloaded the artifact , but still not stored it in the local repository .*/ + ALREADY_DOWNLOADED, + + /**Can be sent when ONAP component successfully deployed the specific artifact in the local repository*/ + DEPLOY_OK, + + /**Can be sent when ONAP component failed to store the downloaded artifact in the local repository*/ + DEPLOY_ERROR, + + /**Sent when the repeated distribution notification event is sent for already stored in the local repository service artifact ( artifact's version and checksum match the one stored in the local repository)*/ + ALREADY_DEPLOYED, + /** + * ONAP component is requested to publish this status once component successfully complete downloading and storing all the data it needs from the service. + */ + COMPONENT_DONE_OK, + + /**ONAP component is requested to publish this status when component failed to download or failed to store one or more of the mandatory information it requires from the service model. + + It is recommended to populate the errorReason field with appropriate description of the error +*/ + COMPONENT_DONE_ERROR, + /** The DISTRIBUTION_COMPLETE_OK/ERROR status indicating the overall ONAP components status of retrieving and storing the information. +*/ + DISTRIBUTION_COMPLETE_OK, + + DISTRIBUTION_COMPLETE_ERROR +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/GeneralUtils.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/GeneralUtils.java new file mode 100644 index 0000000..a69e479 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/GeneralUtils.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.utils; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + +import org.apache.commons.codec.binary.Base64; +import org.onap.sdc.api.results.IDistributionClientResult; +import org.onap.sdc.impl.DistributionClientResultImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import fj.data.Either; + +public class GeneralUtils { + private static final Logger log = LoggerFactory.getLogger(GeneralUtils.class.getName()); + public static String calculateMD5 (String data){ + String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data); + // encode base-64 result + byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes()); + String encodeBase64Str = new String(encodeBase64); + return encodeBase64Str; + + } + + public static String calculateMD5(byte[] decodedPayload) { + String decodedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(decodedPayload); + byte[] encodeMd5 = Base64.encodeBase64(decodedMd5.getBytes()); + return new String(encodeMd5); + } + + public static boolean isBase64Encoded(String str){ + boolean isEncoded = false; + try + { + // If no exception is caught, then it is possibly a base64 encoded string + byte[] data = Base64.decodeBase64(str); + // checks if the string was properly padded to the + isEncoded= ((str.length() % 4 == 0) && (Pattern.matches("\\A[a-zA-Z0-9/+]+={1,2}\\z", str))); + + } + catch (Exception e) + { + // If exception is caught, then it is not a base64 encoded string + isEncoded= false; + } + return isEncoded; + } + + + public static Either, IDistributionClientResult> convertToValidHostName(List msgBusAddresses) { + List uebLocalHostsNames = new ArrayList<>(); + for(String name : msgBusAddresses){ + try { + uebLocalHostsNames.add(InetAddress.getByName(name).getHostName()); + } catch (UnknownHostException e) { + log.debug("UnknownHost: {}", e.getMessage(), e); + } + } + Either, IDistributionClientResult> response; + if( uebLocalHostsNames.isEmpty() ){ + response = Either.right(new DistributionClientResultImpl(DistributionActionResultEnum.CONF_INVALID_MSG_BUS_ADDRESS, "configuration is invalid: " + DistributionActionResultEnum.CONF_INVALID_MSG_BUS_ADDRESS.name())); + + } + else{ + response = Either.left(uebLocalHostsNames); + } + return response; + } +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/Pair.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/Pair.java new file mode 100644 index 0000000..097cafb --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/Pair.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.utils; + +public final class Pair { + private final F first; + private final S second; + + public Pair(F first, S second){ + this.first = first; + this.second = second; + } + + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/Wrapper.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/Wrapper.java new file mode 100644 index 0000000..d1d799c --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/Wrapper.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.utils; +/** + * Very Basic Wrapper class. + * @author mshitrit + * + * @param + */ +public class Wrapper{ + private T innerElement; + public Wrapper(T innerElement){ + this.innerElement = innerElement; + } + public Wrapper(){ + this.innerElement = null; + } + public T getInnerElement() { + return innerElement; + } + public void setInnerElement(T innerElement) { + this.innerElement = innerElement; + } + public boolean isEmpty(){ + return innerElement == null; + } +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/YamlToObjectConverter.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/YamlToObjectConverter.java new file mode 100644 index 0000000..9c294d2 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/YamlToObjectConverter.java @@ -0,0 +1,155 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.utils; + +import java.beans.IntrospectionException; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; + +import org.onap.sdc.utils.heat.HeatConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.TypeDescription; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.introspector.BeanAccess; +import org.yaml.snakeyaml.introspector.Property; +import org.yaml.snakeyaml.introspector.PropertyUtils; + +public class YamlToObjectConverter { + + private static Logger log = LoggerFactory + .getLogger(YamlToObjectConverter.class.getName()); + + private static HashMap yamls = new HashMap(); + + private static Yaml defaultYaml = new Yaml(); + + static { + + org.yaml.snakeyaml.constructor.Constructor heatConstructor = new org.yaml.snakeyaml.constructor.Constructor(HeatConfiguration.class); + TypeDescription heatDescription = new TypeDescription(HeatConfiguration.class); + //heatDescription.putListPropertyType("parameters", HeatParameterConfiguration.class); + heatConstructor.addTypeDescription(heatDescription); + PropertyUtils propertyUtils = new PropertyUtils() { + @Override + //This is in order to workaround "default" field in HeatParameterEntry, since default is Java keyword + public Property getProperty(Class type, String name, BeanAccess bAccess) + throws IntrospectionException { + name = name.substring(0, 1).toLowerCase() + name.substring(1); + return super.getProperty(type, name, bAccess); + } + + }; + //Skip properties which are not found - we only are interested in "parameters" + propertyUtils.setSkipMissingProperties(true); + heatConstructor.setPropertyUtils(propertyUtils); + + Yaml yaml = new Yaml(heatConstructor); + + yamls.put(HeatConfiguration.class.getName(), yaml); + + } + + private static Yaml getYamlByClassName(Class className) { + + Yaml yaml = yamls.get(className.getName()); + if (yaml == null) { + yaml = defaultYaml; + } + + return yaml; + } + + public T convert(String dirPath, Class className, + String configFileName) { + + T config = null; + + try { + + String fullFileName = dirPath + File.separator + configFileName; + + config = convert(fullFileName, className); + + } catch (Exception e) { + log.error("Failed to convert yaml file " + configFileName + + " to object.", e); + } + + return config; + } + + public T convert(String fullFileName, Class className) { + + T config = null; + + Yaml yaml = getYamlByClassName(className); + + InputStream in = null; + try { + + File f = new File(fullFileName); + if (false == f.exists()) { + log.warn("The file " + fullFileName + + " cannot be found. Ignore reading configuration."); + return null; + } + in = Files.newInputStream(Paths.get(fullFileName)); + + config = yaml.loadAs(in, className); + + // System.out.println(config.toString()); + } catch (Exception e) { + log.error("Failed to convert yaml file " + fullFileName + + " to object.", e); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + return config; + } + + public T convertFromString(String yamlContents, Class className) { + + T config = null; + + Yaml yaml = getYamlByClassName(className); + + try { + config = yaml.loadAs(yamlContents, className); + } catch (Exception e){ + log.error("Failed to convert YAML {} to object." , yamlContents, e); + } + + return config; + } +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatConfiguration.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatConfiguration.java new file mode 100644 index 0000000..ee272f4 --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatConfiguration.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.utils.heat; + +import java.util.Map; + +public class HeatConfiguration { + + //All the rest of heat file is not needed for now... + Map parameters; + + + public Map getParameters() { + return parameters; + } + + + public void setParameters(Map parameters) { + this.parameters = parameters; + } + + + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParameter.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParameter.java new file mode 100644 index 0000000..3638bcf --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParameter.java @@ -0,0 +1,207 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.utils.heat; + +import java.util.ArrayList; +import java.util.List; + +public class HeatParameter{ + + String type; + String label; + String description; + //This is in order to workaround "default" field in HeatParameterEntry, since default is Java keyword + //YAML constructor will lowercase it during parsing + String Default; + String hidden = "false";//Default value according to OpenStack spec + List constraints; + + + + public String getHidden() { + return hidden; + } + public void setHidden(String hidden) { + this.hidden = hidden; + } + + public List getConstraints() { + return constraints; + } + public void setConstraints(List constraints) { + this.constraints = constraints; + } + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public String getDefault() { + return Default; + } + public void setDefault(String default1) { + Default = default1; + } + + + + // Getting specific constraints + /** + * Get the first "length" constraint from HEAT parameter. + * No additional "length" constraint is searched for. + * + * @return first "length" constraint found for this parameter, + * or null if no such constraint exists. + */ + public HeatParameterConstraint getLengthConstraint(){ + HeatParameterConstraint res = null; + if (constraints != null){ + for (HeatParameterConstraint entry : constraints){ + if (entry.getLength() != null){ + res = entry; + break; + } + } + } + return res; + } + + + /** + * Get the first "range" constraint from HEAT parameter. + * No additional "range" constraint is searched for. + * + * @return first "range" constraint found for this parameter, + * or null if no such constraint exists. + */ + public HeatParameterConstraint getRangeConstraint(){ + HeatParameterConstraint res = null; + if (constraints != null){ + for (HeatParameterConstraint entry : constraints){ + if (entry.getRange() != null){ + res = entry; + break; + } + } + } + return res; + } + + /** + * Get the first "allowed_values" constraint from HEAT parameter. + * No additional "allowed_values" constraint is searched for. + * + * @return first "allowed_values" constraint found for this parameter, + * or null if no such constraint exists. + */ + public HeatParameterConstraint getAllowedValuesConstraint(){ + HeatParameterConstraint res = null; + if (constraints != null){ + for (HeatParameterConstraint entry : constraints){ + if (entry.getAllowed_values() != null){ + res = entry; + break; + } + } + } + return res; + } + + /** + * Get the "allowed_pattern" constraint list from HEAT parameter. + * + * @return "allowed_pattern" constraint list found for this parameter, + * or null if no such constraint exists. + */ + public List getAllowedPatternConstraint(){ + List res = null; + if (constraints != null){ + for (HeatParameterConstraint entry : constraints){ + if (entry.getAllowed_pattern() != null){ + if (res == null){ + res = new ArrayList<>(); + } + res.add(entry); + } + } + } + return res; + } + + /** + * Get the "custom_constraint" constraint list from HEAT parameter. + * + * @return "custom_constraint" constraint list found for this parameter, + * or null if no such constraint exists. + */ + public List getCustomConstraintConstraint(){ + List res = null; + if (constraints != null){ + for (HeatParameterConstraint entry : constraints){ + if (entry.getCustom_constraint() != null){ + if (res == null){ + res = new ArrayList<>(); + } + res.add(entry); + } + } + } + return res; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + if (type != null){ + sb.append("type:"+type+", "); + } + if (label != null){ + sb.append("label:"+label+", "); + } + if (Default != null){ + sb.append("default:"+Default+", "); + } + if (hidden != null){ + sb.append("hidden:"+hidden+", "); + } + if (constraints != null){ + sb.append("constraints:"+constraints+", "); + } + if (description != null){ + sb.append("description:"+description); + } + return sb.toString(); + } + +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParameterConstraint.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParameterConstraint.java new file mode 100644 index 0000000..d618caf --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParameterConstraint.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.utils.heat; + +import java.util.List; +import java.util.Map; + +public class HeatParameterConstraint { + + Map length; + Map range; + List allowed_values; + String allowed_pattern; + String custom_constraint; + String description; + + + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public Map getLength() { + return length; + } + public void setLength(Map length) { + this.length = length; + } + public Map getRange() { + return range; + } + public void setRange(Map range) { + this.range = range; + } + public List getAllowed_values() { + return allowed_values; + } + public void setAllowed_values(List allowed_values) { + this.allowed_values = allowed_values; + } + public String getAllowed_pattern() { + return allowed_pattern; + } + public void setAllowed_pattern(String allowed_pattern) { + this.allowed_pattern = allowed_pattern; + } + public String getCustom_constraint() { + return custom_constraint; + } + public void setCustom_constraint(String custom_constraint) { + this.custom_constraint = custom_constraint; + } + + @Override + public String toString() { + String constraintTypeValue = ""; + String descriptionStr = ""; + if (length != null){ + constraintTypeValue = "length:"+length; + } else if (range != null){ + constraintTypeValue = "range:"+range; + } else if (allowed_values != null){ + constraintTypeValue = "allowed_values:"+allowed_values; + } else if (allowed_pattern != null){ + constraintTypeValue = "allowed_pattern:"+allowed_pattern; + } else if (custom_constraint != null){ + constraintTypeValue = "custom_constraint:"+custom_constraint; + } + if (description != null){ + descriptionStr = "description:"+description; + } + return new StringBuilder().append(constraintTypeValue).append(", ").append(descriptionStr).toString(); + } +} diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParser.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParser.java new file mode 100644 index 0000000..340a59d --- /dev/null +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParser.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.utils.heat; + +import java.util.Map; + +import org.onap.sdc.utils.YamlToObjectConverter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HeatParser { + + private static Logger log = LoggerFactory.getLogger(HeatParser.class.getName()); + + + /** + * Parses and returns the contents of the "parameters" section of YAML-formatted HEAT template. + * + * @param heatFileContents - the string contents of HEAT template + * @return map of parameter name to HeatParameter object. + * For the following YAML snippet: + * parameters: + * image_name_1: + * type: string + * label: Image Name + * description: SCOIMAGE Specify an image name for instance1 + * default: cirros-0.3.1-x86_64 + * + * the map with one entry will be returned, the key will be "image_name_1". + * For a HeatParameter object, getConstraints() returns the list of all constraints, + * regardless of constraint type. + * For that reason, for each constraint type a sugaring function were added on the HeatParameter type, + * for example getLengthConstraint(). A correct way to fetch the "length" constraint values map would be + * parameter.getLengthConstraint().getLength(). Same logic was implemented for all other constraint types. + * + * In case of parse error, null will be returned. + * + */ + public Map getHeatParameters(String heatFileContents){ + log.debug("Start of extracting HEAT parameters from file, file contents: {}", heatFileContents); + Map heatParameters = null; + YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); + HeatConfiguration heatConfiguration = yamlToObjectConverter.convertFromString(heatFileContents, HeatConfiguration.class); + if (heatConfiguration != null){ + heatParameters = heatConfiguration.getParameters(); + } else { + log.error("Couldn't parse HEAT template."); + } + if (heatParameters != null && heatParameters.size() > 0){ + System.out.println("Found HEAT parameters: "+heatParameters.toString()); + log.debug("Found HEAT parameters: {}", heatParameters.toString()); + } else { + log.warn("HEAT template parameters section wasn't found or is empty."); + } + return heatParameters; + } +} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/IDistributionClient.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/IDistributionClient.java deleted file mode 100644 index 8caf109..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/IDistributionClient.java +++ /dev/null @@ -1,210 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.api; - -import java.util.List; - -import org.openecomp.sdc.api.consumer.*; -import org.openecomp.sdc.api.consumer.IStatusCallback; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.IVfModuleMetadata; -import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; -import org.openecomp.sdc.api.results.IDistributionClientResult; - -public interface IDistributionClient { - - /** - * Update the configuration of the distribution client
- * Updatable configuration parameters are: pollingInterval, pollingTimeout, - * consumerGroup and relevantArtifactTypes - * - * @param newConf - * - contains updated configuration - * - * @return IDistributionClientResult - */ - IDistributionClientResult updateConfiguration(IConfiguration newConf); - - /** - * Retrieve the configuration of the distribution client
- * - * @return IConfiguration - */ - IConfiguration getConfiguration(); - - /** - * Start distribution client
- * - start polling notification topic
- * - * @return IDistributionClientResult - */ - IDistributionClientResult start(); - - /** - * Stop distribution client
- * - stop polling notification topic
- * - unregister topics (via ASDC)
- * - delete keys from UEB - * - * @return IDistributionClientResult - */ - IDistributionClientResult stop(); - - /** - * Downloads an artifact from ASDC Catalog
- * - * @param artifactInfo - * @return IDistributionClientDownloadResult - */ - IDistributionClientDownloadResult download(IArtifactInfo artifactInfo); - - /** - * Initialize the distribution client
- * - fetch the UEB server list from ASDC
- * - create keys in UEB
- * - register for topics (via ASDC)
- * - set the notification callback
- * - * Note: all configuration fields are mandatory.
- * Password must be in clear text and not encrypted
- * ONAP-Component MUST store password as SHA-2 (256) hashed with - * dynamically generated salt value
- * - * @param conf - * @param callback - * @return IDistributionClientResult - */ - IDistributionClientResult init(IConfiguration conf, INotificationCallback callback); - - /** - * Initialize the distribution client
- * - fetch the UEB server list from ASDC
- * - create keys in UEB
- * - register for topics (via ASDC)
- * - set the notification callback
- * - * Note: all configuration fields are mandatory.
- * Password must be in clear text and not encrypted
- * ONAP-Component MUST store password as SHA-2 (256) hashed with - * dynamically generated salt value
- * - * @param conf - * @param notificationCallback - * @param statusCallback - * @return IDistributionClientResult - */ - IDistributionClientResult init(IConfiguration conf, INotificationCallback notificationCallback, - IStatusCallback statusCallback); - - /** - * Build and publish Distribution Download Status event to Distribution - * Status Topic - * - * @param statusMessage - * @return IDistributionClientResult - */ - IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage statusMessage); - - /** - * Build and publish Distribution Download Status event to Distribution - * Status Topic With Error Reason. - * - * @param statusMessage - * @param errorReason - * @return IDistributionClientResult - */ - IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage statusMessage, String errorReason); - - /** - * Build and publish Distribution Deployment Status event to Distribution - * Status Topic - * - * @param statusMessage - * @return IDistributionClientResult - */ - IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage statusMessage); - - /** - * Build and publish Distribution Deployment Status event to Distribution - * Status Topic With Error Reason. - * - * @param statusMessage - * @param errorReason - * @return IDistributionClientResult - */ - IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage statusMessage, String errorReason); - - /** - * Build and publish Distribution Component Status event to Distribution - * Status Topic - * - * @param statusMessage - * @return IDistributionClientResult - */ - IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage); - - /** - * Build and publish Distribution Component Status event to Distribution - * Status Topic With Error Reason. - * - * @param statusMessage - * @param errorReason - * @return IDistributionClientResult - */ - IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage, String errorReason); - - - /** - * Build and publish Distribution Final Status event to Distribution - * Status Topic - * - * @param statusMessage - * @return IDistributionClientResult - */ - IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage); - - - /** - * Build and publish Distribution Final Status event to Distribution - * Status Topic With Error Reason. - * - * @param statusMessage - * @param errorReason - * @return IDistributionClientResult - */ - IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage, String errorReason); - - - /** - * This method parses artifact of type VF_MODULES_METADATA payload data - * .
- * Method is deprecated due to VF Module changes. Only backward - * compatibility is supported.
- * - * @param artifactPayload - * @return IVfModuleMetadata list - */ - @Deprecated - List decodeVfModuleArtifact(byte[] artifactPayload); - - - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/IDistributionStatusMessageJsonBuilder.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/IDistributionStatusMessageJsonBuilder.java deleted file mode 100644 index 7c28271..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/IDistributionStatusMessageJsonBuilder.java +++ /dev/null @@ -1,25 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.api; - -public interface IDistributionStatusMessageJsonBuilder { - String build(); -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/asdc/RegistrationRequest.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/asdc/RegistrationRequest.java deleted file mode 100644 index 1e398be..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/asdc/RegistrationRequest.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.api.asdc; - -import java.util.List; - -public class RegistrationRequest { - - String apiPublicKey; - String distrEnvName; - Boolean isConsumerToSdcDistrStatusTopic; - List distEnvEndPoints; - - public RegistrationRequest(String apiPublicKey, String distrEnvName, boolean isConsumerToSdcDistrStatusTopic, List distEnvEndPoints) { - this.apiPublicKey = apiPublicKey; - this.distrEnvName = distrEnvName; - this.isConsumerToSdcDistrStatusTopic = isConsumerToSdcDistrStatusTopic; - this.distEnvEndPoints = distEnvEndPoints; - } - - public String getApiPublicKey() { - return apiPublicKey; - } - - public String getDistrEnvName() { - return distrEnvName; - } - - public Boolean getIsConsumerToSdcDistrStatusTopic() { - return isConsumerToSdcDistrStatusTopic; - } - - public List getDistEnvEndPoints() { - return distEnvEndPoints; - } - - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/asdc/ServerListResponse.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/asdc/ServerListResponse.java deleted file mode 100644 index c131a95..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/asdc/ServerListResponse.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.api.asdc; - -import java.util.List; - -public class ServerListResponse { - - private List uebServerList; - - public List getUebServerList() { - return uebServerList; - } - - public void setUebServerList(List uebServerList) { - this.uebServerList = uebServerList; - } -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IComponentDoneStatusMessage.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IComponentDoneStatusMessage.java deleted file mode 100644 index 25661bf..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IComponentDoneStatusMessage.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.openecomp.sdc.api.consumer; - -public interface IComponentDoneStatusMessage extends IDistributionStatusMessageBasic { - String getComponentName(); - default String getArtifactURL(){return "";} - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IConfiguration.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IConfiguration.java deleted file mode 100644 index 51d219f..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IConfiguration.java +++ /dev/null @@ -1,157 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.api.consumer; - -import java.util.List; -import org.openecomp.sdc.api.notification.INotificationData; - -public interface IConfiguration { - /** - * SDC Distribution Engine address. Value can be either hostname (with or - * without port), IP:port or FQDN (Fully Qualified Domain Name). * @return - * SDC Distribution Engine address. - */ - String getAsdcAddress(); - - /**SDC Distribution Addresses from ONAP Component - * Values need to be set from impl - */ - List getMsgBusAddress(); - - /** - * User Name for SDC distribution consumer authentication. - * - * @return User Name. - */ - String getUser(); - - /** - * User Password for SDC distribution consumer authentication. - * - * @return User Password. - */ - String getPassword(); - - /** - * Distribution Client Polling Interval towards UEB in seconds. Can Be - * reconfigured in runtime. - * - * @return Distribution Client Polling Interval. - */ - int getPollingInterval(); - - /** - * Distribution Client Timeout in seconds waiting to UEB server response in - * each fetch interval. Can Be reconfigured in runtime. - * - * @return Distribution Client Timeout in seconds. - */ - int getPollingTimeout(); - - /** - * List of artifact types.
- * If the service contains any of the artifacts in the list, the callback - * will be activated. Can Be reconfigured in runtime. - * - * @return List of artifact types. - */ - List getRelevantArtifactTypes(); - - /** - * Returns the consumer group defined for this ECOMP component, if no - * consumer group is defined return null. - * - * @return Consumer group. - */ - String getConsumerGroup(); - - /** - * Returns the environment name (testing, production etc...). Can Be - * reconfigured in runtime. - * - * @return - */ - String getEnvironmentName(); - - /** - * Unique ID of ECOMP component instance (e.x INSTAR name). - * - * @return - */ - String getConsumerID(); - - /** - * Return full path to Client's Key Store that contains either CA - * certificate or the ASDC's public key (e.g /etc/keystore/asdc-client.jks) - * file will be deployed with sdc-distribution jar. - * - * @return - */ - String getKeyStorePath(); - - /** - * @return Returns client's Key Store password - */ - String getKeyStorePassword(); - - /** - * Sets whether SDC server TLS authentication is activated. If set to false, - * Key Store path and password are not needed to be set. - * - * @return - */ - boolean activateServerTLSAuth(); - - /** - * If set to true the method {@link INotificationData#getResources()} will - * return all found resources.
- * That means that metadata of resources that do not contain relevant - * artifacts types (artifacts that are defined in - * {@link #getRelevantArtifactTypes()} will be returned.
- * Setting the method to false will activate the legacy behavior, in which - * empty resources are not part of the notification.
- * - * @return - */ - boolean isFilterInEmptyResources(); - - /** - * By default, Distribution Client will use HTTPS (TLS 1.2) when connecting - * to DMAAP. This param can be null, then default (HTTPS) behavior will be - * applied. If set to false, distribution client will use HTTP when - * connecting to DMAAP. - * - * @return - */ - Boolean isUseHttpsWithDmaap(); - - /** - * By default, (false value) Distribution Client will trigger the regular registration - * towards SDC (register component as consumer to the SDC-DISTR-NOTIF-TOPIC-[ENV] topic and register component as producer to the SDC-DISTR-STATUS-TOPIC-[ENV]).
- * If set to true, distribution client trigger Register to SDC indicating - * that this component request to be consumer and producer of the - * SDC-DISTR-STATUS-TOPIC-[ENV] topic.
- * @return - */ - default boolean isConsumeProduceStatusTopic() { - return false; - } -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IDistributionStatusMessage.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IDistributionStatusMessage.java deleted file mode 100644 index ab3d6a7..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IDistributionStatusMessage.java +++ /dev/null @@ -1,28 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.api.consumer; - -public interface IDistributionStatusMessage extends IDistributionStatusMessageBasic{ - - /**Resource URL of the downloaded/deployed artifact - URL specified in the distribution notification message*/ - String getArtifactURL(); - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IDistributionStatusMessageBasic.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IDistributionStatusMessageBasic.java deleted file mode 100644 index fb1194d..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IDistributionStatusMessageBasic.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.openecomp.sdc.api.consumer; - -import org.openecomp.sdc.utils.DistributionStatusEnum; - -public interface IDistributionStatusMessageBasic { - /** - * Distribution ID published in the distribution notification.
- * Should be used to link the distribution status reports to the appropriate - * distribution activation.
- * Global Distribution Identifier: UUID generated by SDC per each - * distribution activation.
- * Generated UUID is compliant with RFC 4122. It is a 128-bit value - * formatted into blocks of hexadecimal digits separated by a hyphen ("-"). - * Ex.: AA97B177-9383-4934-8543-0F91A7A02836 - */ - String getDistributionID(); - - /**Unique ID of ONAP component instance (e.x INSTAR name)*/ - String getConsumerID(); - - /** - * Timestamp of the distribution status report creation.
- * The number of seconds that have elapsed since January 1, 1970. - */ - long getTimestamp(); - /**Download/Deployment status*/ - DistributionStatusEnum getStatus(); -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IFinalDistrStatusMessage.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IFinalDistrStatusMessage.java deleted file mode 100644 index 42affd7..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IFinalDistrStatusMessage.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.openecomp.sdc.api.consumer; - - - -public interface IFinalDistrStatusMessage extends IDistributionStatusMessageBasic{ - - default String getConsumerID(){return "";} - default String getComponentName(){return "";} -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/INotificationCallback.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/INotificationCallback.java deleted file mode 100644 index 60666ed..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/INotificationCallback.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.api.consumer; - -import org.openecomp.sdc.api.notification.INotificationData; -/**When a relevant notification will be found activateCallback method will be activated with the notification data.
- * Please implement it according to your desired callback logic.*/ -public interface INotificationCallback { - void activateCallback(INotificationData data); -} - diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IStatusCallback.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IStatusCallback.java deleted file mode 100644 index a889f52..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/consumer/IStatusCallback.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.api.consumer; - -import org.openecomp.sdc.api.notification.IStatusData; - -/** - * When a relevant status will be found activateCallback method will be - * activated with the status data.
- * Please implement it according to your desired callback logic. - */ -@FunctionalInterface -public interface IStatusCallback { - void activateCallback(IStatusData data); - - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/IArtifactInfo.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/IArtifactInfo.java deleted file mode 100644 index f720e35..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/IArtifactInfo.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.api.notification; - -import java.util.List; - - -public interface IArtifactInfo { - - /** - * @return String of the Artifact File Name. - */ - String getArtifactName(); - - /** - * Artifact Type.
- * Following are valid values : HEAT , DG_XML.
- * List of values will be extended in post-1510 releases. - * - * @return String of the artifact type. - */ - String getArtifactType(); - - /** - * Relative artifact's URL. Should be used in REST GET API to download the artifact's payload.
- * The full artifact URL will be in the following format :
- * https://{serverBaseURL}/{resourcePath}
- * serverBaseURL - Hostname ( SDC LB FQDN) + optional port
- * resourcePath - "artifactURL"
- * Ex : https://sdc.com/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml - * - * @return String of the Relative artifact's URL. - */ - String getArtifactURL(); - - /** - * Base-64 encoded MD5 checksum of the artifact's payload.
- * Should be used for data integrity validation when an artifact's payload is downloaded.
- * - * @return String of the checksum of the artifact's payload. - */ - String getArtifactChecksum(); - - /** - * Installation timeout in minutes.
- * Used by the Orchestrator to determine how much time to wait for a heat (or other deployment artifact)
- * This field is only relevant for artifacts of ArtifactTypeEnum HEAT, for other artifacts it will be null.
- * deployment process to finish.
- * - * @return String of the Installation timeout in minutes. - */ - Integer getArtifactTimeout(); - - /** - * Artifact description - * @return - */ - String getArtifactDescription(); - - /** - * Artifact Version - * @return - */ - String getArtifactVersion(); - - /** - * Artifact Unique ID - * @return - */ - String getArtifactUUID(); - - - /** - * Returns the artifact it is generated from (relevant for heat_env), or null if there is no such artifact. - * @return - */ - IArtifactInfo getGeneratedArtifact(); - - /** - * Returns the list of related artifacts (relevant for HEAT_NESTED or HEAT_ARTIFACT), or null if there is no such artifacts. - * @return - */ - List getRelatedArtifacts(); - - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/INotificationData.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/INotificationData.java deleted file mode 100644 index 74ebf65..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/INotificationData.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.api.notification; - -import java.util.List; - - - - - -public interface INotificationData { - /** Global Distribution Identifier: UUID generated by ASDC per each distribution activation.
- * Generated UUID is compliant with RFC 4122.
- * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").
- Ex.: AA97B177-9383-4934-8543-0F91A7A02836 */ - String getDistributionID(); - - /**Logical Service Name.*/ - String getServiceName(); - - /** Service Version.
- * Two dot (".") separated digit blocks.
- Ex. : "2.0"*/ - String getServiceVersion(); - - /**Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.
- It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").
- Ex. : AA97B177-9383-4934-8543-0F91A7A02836*/ - String getServiceUUID(); - - /** - * Service description - */ - String getServiceDescription(); - - /** List of the resource instances */ - List getResources(); - - /** List of Artifacts On Service Level */ - List getServiceArtifacts(); - - /**This method allows getting details of the artifact by its uuid.*/ - IArtifactInfo getArtifactMetadataByUUID(String artifactUUID); - - /** - * Invariant UUID - */ - String getServiceInvariantUUID(); - - String getWorkloadContext(); - - void setWorkloadContext(String workloadContext); -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/IResourceInstance.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/IResourceInstance.java deleted file mode 100644 index a2f7828..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/IResourceInstance.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.api.notification; - -import java.util.List; - -public interface IResourceInstance { - /**Logical Resource Instance Name.
- * Unique Identifier of the instance of the specific resource in the service context.**/ - String getResourceInstanceName(); - - /**resource name */ - String getResourceName(); - - /**resource version */ - String getResourceVersion(); - - /**Resource Type (For Example: VF (Virtual Function) - A subsystem in a service, it can include one or more VFCs. This is what NFV spec refers as VNF.)**/ - String getResourceType(); - - /**Global UUID of the resource that specific artifact belongs to.
- It is generated by SDC per each resource version.
- Generated UUID is compliant with RFC 4122. It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").
- Ex.: AA97B177-9383-4934-8543-0F91A7A02836**/ - String getResourceUUID(); - - /**List of resource instance deployment artifacts.**/ - List getArtifacts(); - - /**Invariant (constant) resource UUID generated on resource creation.**/ - String getResourceInvariantUUID(); - - /**This UUID is unique in the context of the service.
- It is regenerated whenever a designer makes changes to the resource instance.
- A change may be updating HEAT value, updating property value or name of the resource instance.
- It is also regenerated when an artifact is uploaded to the resource instance.**/ - String getResourceCustomizationUUID(); - - /**The category of the resource model.
- E.g. "Application L4+".**/ - String getCategory(); - - /**The subcategory of the resource model.
- E.g. "Call Control"**/ - String getSubcategory(); - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/IStatusData.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/IStatusData.java deleted file mode 100644 index 7a46686..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/IStatusData.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.api.notification; - -import org.openecomp.sdc.utils.DistributionStatusEnum; - -public interface IStatusData { - /** - * Global Distribution Identifier: UUID generated by SDC per each - * distribution activation.
- * Generated UUID is compliant with RFC 4122.
- * It is a 128-bit value formatted into blocks of hexadecimal digits - * separated by a hyphen ("-").
- * Ex.: AA97B177-9383-4934-8543-0F91A7A02836 - */ - String getDistributionID(); - - /** Unique ID of ONAP component instance (e.x INSTAR name). */ - String getConsumerID(); - - /** The predefined ONAP component name configured on the component. */ - String getComponentName(); - - /** - * Timestamp of the distribution status report creation. The number of - * seconds that have elapsed since January 1, 1970 - */ - Long getTimestamp(); - /** - * Resource URL of the downloaded/deployed artifact - URL specified in the - * distribution notification message. - */ - String getArtifactURL(); - /** - * Status Event type - */ - DistributionStatusEnum getStatus(); - /** - * Error Reason describing the Status Event. - */ - String getErrorReason(); - - - - - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/IVfModuleMetadata.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/IVfModuleMetadata.java deleted file mode 100644 index a769d71..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/notification/IVfModuleMetadata.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.api.notification; - -import java.util.List; -/**VF Module in the resource (VF) context*/ -public interface IVfModuleMetadata { - /**Logical VF Module Name. Unique Identifier of VF Module in the resource (VF) context.
- Ex. : "PCRF-module-0" - */ - String getVfModuleModelName(); - - /**Invariant VF Module UUID generated on VF Module creation according to RFC 4122
- It is generated on service creation and stays invariant even if service name /version are updated. - */ - String getVfModuleModelInvariantUUID(); - - /** - Resource Version . Ex. : "1" - */ - String getVfModuleModelVersion(); - - /**Global UUID of the VF Module.
- It is generated by ASDC per each new VF module version. Generated UUID is compliant with RFC 4122. It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").
- Ex.: AA97B177-9383-4934-8543-0F91A7A02836 - */ - String getVfModuleModelUUID(); - - - /** - * VF Module textual description. Can be empty. - */ - String getVfModuleModelDescription(); - - - /** - * Is this VF module is the base module of the VF. - * */ - boolean isBase(); - - /** - * Array of VF Module deployment artifacts UUID. - * */ - List getArtifacts(); -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/results/IDistributionClientDownloadResult.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/results/IDistributionClientDownloadResult.java deleted file mode 100644 index 6030b9e..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/results/IDistributionClientDownloadResult.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.api.results; - -/**Distribution Client Result For Download API*/ -public interface IDistributionClientDownloadResult extends IDistributionClientResult{ - - - byte[] getArtifactPayload(); - - - /** - * @deprecated - * This method is deprecated and will be removed in 1710. - * It returns attachment; filename="filename" rather than "filename". - * Please use {@link #getArtifactFilename()}. - * @return - */ - @Deprecated - String getArtifactName(); - - /** - * Returns the filename of the artifact. - * @return the filename of the artifact. - */ - String getArtifactFilename(); -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/results/IDistributionClientResult.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/results/IDistributionClientResult.java deleted file mode 100644 index b4086ac..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/api/results/IDistributionClientResult.java +++ /dev/null @@ -1,28 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.api.results; - -import org.openecomp.sdc.utils.DistributionActionResultEnum; -/**General Distribution Client Result*/ -public interface IDistributionClientResult { - DistributionActionResultEnum getDistributionActionResult(); - String getDistributionMessageResult(); -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/AsdcUrls.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/AsdcUrls.java deleted file mode 100644 index 320cade..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/AsdcUrls.java +++ /dev/null @@ -1,30 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.http; - -public class AsdcUrls { - - public static final String GET_CLUSTER_SERVER_LIST = "/sdc/v1/distributionUebCluster"; - public static final String GET_VALID_ARTIFACT_TYPES = "/sdc/v1/artifactTypes"; - public static final String POST_FOR_TOPIC_REGISTRATION = "/sdc/v1/registerForDistribution"; - public static final String POST_FOR_UNREGISTER = "/sdc/v1/unRegisterForDistribution"; - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/HttpAsdcClient.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/HttpAsdcClient.java deleted file mode 100644 index c3a486a..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/HttpAsdcClient.java +++ /dev/null @@ -1,351 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.http; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.ConnectException; -import java.net.UnknownHostException; -import java.security.KeyStore; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -import org.apache.commons.codec.binary.Base64; -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpStatus; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.message.BasicHeader; -import org.apache.http.ssl.SSLContextBuilder; -import org.apache.http.ssl.TrustStrategy; -import org.openecomp.sdc.api.consumer.IConfiguration; -import org.openecomp.sdc.utils.Pair; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class HttpAsdcClient implements IHttpAsdcClient { - - private static final String TLS = "TLSv1.2"; - private static final String AUTHORIZATION_HEADER = "Authorization"; - private static final String HTTPS = "https://"; - private static Logger log = LoggerFactory.getLogger(HttpAsdcClient.class.getName()); - private CloseableHttpClient httpClient = null; - private String serverFqdn = null; - private String authHeaderValue = ""; - - public HttpAsdcClient(IConfiguration configuraion) { - this.serverFqdn = configuraion.getAsdcAddress(); - - String username = configuraion.getUser(); - String password = configuraion.getPassword(); - initSSL(username, password, configuraion.getKeyStorePath(), configuraion.getKeyStorePassword(), configuraion.activateServerTLSAuth()); - - String userNameAndPassword = username + ":" + password; - this.authHeaderValue = "Basic " + Base64.encodeBase64String(userNameAndPassword.getBytes()); - } - - // @SuppressWarnings("deprecation") - private void initSSL(String username, String password, String keyStorePath, String keyStoePass, boolean isSupportSSLVerification) { - - try { - HostnameVerifier hostnameVerifier = new HostnameVerifier() { - - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - - // SSLContextBuilder is not thread safe - // @SuppressWarnings("deprecation") - CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials(new AuthScope("localhost", 443), new UsernamePasswordCredentials(username, password)); - SSLContext sslContext; - sslContext = SSLContext.getInstance(TLS); - TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - KeyStore trustStore = null; - tmf.init(trustStore); - TrustManager[] tms = tmf.getTrustManagers(); - if (isSupportSSLVerification) { - - if (keyStorePath != null && !keyStorePath.isEmpty()) { - // trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - // trustStore.load(new FileInputStream(keyStorePath), keyStoePass.toCharArray()); - - // Using null here initialises the TMF with the default trust store. - - // Get hold of the default trust manager - X509TrustManager defaultTm = null; - for (TrustManager tm : tmf.getTrustManagers()) { - if (tm instanceof X509TrustManager) { - defaultTm = (X509TrustManager) tm; - break; - } - } - - // Do the same with your trust store this time - // Adapt how you load the keystore to your needs - trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - trustStore.load(new FileInputStream(keyStorePath), keyStoePass.toCharArray()); - - tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - tmf.init(trustStore); - - // Get hold of the default trust manager - X509TrustManager myTm = null; - for (TrustManager tm : tmf.getTrustManagers()) { - if (tm instanceof X509TrustManager) { - myTm = (X509TrustManager) tm; - break; - } - } - - // Wrap it in your own class. - final X509TrustManager finalDefaultTm = defaultTm; - final X509TrustManager finalMyTm = myTm; - X509TrustManager customTm = new X509TrustManager() { - @Override - public X509Certificate[] getAcceptedIssuers() { - // If you're planning to use client-cert auth, - // merge results from "defaultTm" and "myTm". - return finalDefaultTm.getAcceptedIssuers(); - } - - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - try { - finalMyTm.checkServerTrusted(chain, authType); - } catch (CertificateException e) { - // This will throw another CertificateException if this fails too. - finalDefaultTm.checkServerTrusted(chain, authType); - } - } - - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - // If you're planning to use client-cert auth, - // do the same as checking the server. - finalDefaultTm.checkClientTrusted(chain, authType); - } - }; - - tms = new TrustManager[] { customTm }; - - } - - sslContext.init(null, tms, null); - SSLContext.setDefault(sslContext); - - - - } else { - - SSLContextBuilder builder = new SSLContextBuilder(); - - builder.loadTrustMaterial(null, new TrustStrategy() { - public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { - return true; - } - }); - - sslContext = builder.build(); - } - - SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" }, null, hostnameVerifier); - httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).setSSLSocketFactory(sslsf).build(); - - } catch (Exception e) { - log.error("Failed to create https client", e); - - } - - return; - } - - public HttpAsdcResponse postRequest(String requestUrl, HttpEntity entity, Map headersMap) { - return postRequest(requestUrl, entity, headersMap, true).getFirst(); - } - - public Pair postRequest(String requestUrl, HttpEntity entity, Map headersMap, boolean closeTheRequest) { - Pair ret; - CloseableHttpResponse httpResponse = null; - HttpAsdcResponse response = null; - HttpPost httpPost = new HttpPost(HTTPS + serverFqdn + requestUrl); - List
headers = addHeadersToHttpRequest(headersMap); - for (Header header : headers) { - httpPost.addHeader(header); - } - - httpPost.setHeader(AUTHORIZATION_HEADER, this.authHeaderValue); - - httpPost.setEntity(entity); - try { - httpResponse = httpClient.execute(httpPost); - response = new HttpAsdcResponse(httpResponse.getStatusLine().getStatusCode(), httpResponse.getEntity()); - - } catch (IOException e) { - log.error("failed to send request to url: " + requestUrl); - StringEntity errorEntity = null; - try { - errorEntity = new StringEntity("failed to send request"); - } catch (UnsupportedEncodingException e1) { - } - - response = new HttpAsdcResponse(500, errorEntity); - - } finally { - if (closeTheRequest) { - if (httpResponse != null) { - try { - httpResponse.close(); - - } catch (IOException e) { - log.error("failed to close http response"); - } - } - ret = new Pair<>(response, null); - } else { - ret = new Pair<>(response, httpResponse); - } - } - - return ret; - } - - public HttpAsdcResponse getRequest(String requestUrl, Map headersMap) { - - return getRequest(requestUrl, headersMap, true).getFirst(); - - } - - public Pair getRequest(String requestUrl, Map headersMap, boolean closeTheRequest) { - Pair ret; - CloseableHttpResponse httpResponse = null; - String url = HTTPS + serverFqdn + requestUrl; - log.debug("url to send {}", url); - HttpGet httpGet = new HttpGet(url); - List
headers = addHeadersToHttpRequest(headersMap); - for (Header header : headers) { - httpGet.addHeader(header); - } - - httpGet.setHeader(AUTHORIZATION_HEADER, this.authHeaderValue); - - HttpAsdcResponse response = null; - try { - httpResponse = httpClient.execute(httpGet); - - log.debug("GET Response Status {}", httpResponse.getStatusLine().getStatusCode()); - Header[] headersRes = httpResponse.getAllHeaders(); - Map headersResMap = new HashMap<>(); - for (Header header : headersRes) { - headersResMap.put(header.getName(), header.getValue()); - } - response = new HttpAsdcResponse(httpResponse.getStatusLine().getStatusCode(), httpResponse.getEntity(), headersResMap); - - } catch (UnknownHostException | ConnectException e) { - log.error("failed to connect to url: {}", requestUrl, e); - StringEntity errorEntity = null; - try { - errorEntity = new StringEntity("failed to connect"); - } catch (UnsupportedEncodingException e1) { - } - - response = new HttpAsdcResponse(HttpStatus.SC_BAD_GATEWAY, errorEntity); - - } catch (IOException e) { - log.error("failed to send request to url: " + requestUrl + " error " + e.getMessage()); - StringEntity errorEntity = null; - try { - errorEntity = new StringEntity("failed to send request " + e.getMessage()); - } catch (UnsupportedEncodingException e1) { - } - - response = new HttpAsdcResponse(HttpStatus.SC_BAD_GATEWAY, errorEntity); - - } finally { - - if (closeTheRequest) { - if (httpResponse != null) { - try { - httpResponse.close(); - - } catch (IOException e) { - log.error("failed to close http response"); - } - } - ret = new Pair(response, null); - } else { - ret = new Pair(response, httpResponse); - } - } - - return ret; - - } - - public void closeHttpClient() { - try { - httpClient.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - log.error("failed to close http client"); - } - - } - - private List
addHeadersToHttpRequest(Map headersMap) { - - List
requestHeaders = new ArrayList
(); - - Set headersKyes = headersMap.keySet(); - for (String key : headersKyes) { - Header requestHeader = new BasicHeader(key, headersMap.get(key)); - requestHeaders.add(requestHeader); - } - - return requestHeaders; - } - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/HttpAsdcResponse.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/HttpAsdcResponse.java deleted file mode 100644 index 9e48d5e..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/HttpAsdcResponse.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.http; - -import java.util.Map; - -import org.apache.http.HttpEntity; - -public class HttpAsdcResponse { - - int status; - HttpEntity message; - Map headersMap; - - public HttpAsdcResponse(int status, HttpEntity message) { - super(); - this.status = status; - this.message = message; - } - - public HttpAsdcResponse(int status, HttpEntity message, Map headersMap) { - super(); - this.status = status; - this.message = message; - this.headersMap = headersMap; - } - - public Map getHeadersMap() { - return headersMap; - } - - public void setHeadersMap(Map headersMap) { - this.headersMap = headersMap; - } - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - public HttpEntity getMessage() { - return message; - } - - public void setMessage(HttpEntity message) { - this.message = message; - } - - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/IHttpAsdcClient.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/IHttpAsdcClient.java deleted file mode 100644 index aa62bac..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/IHttpAsdcClient.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.http; - -import java.util.Map; - -import org.apache.http.HttpEntity; - -public interface IHttpAsdcClient { - - HttpAsdcResponse postRequest(String requestUrl, HttpEntity entity, Map headersMap); - HttpAsdcResponse getRequest(String requestUrl, Map headersMap); - void closeHttpClient(); - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/SdcConnectorClient.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/SdcConnectorClient.java deleted file mode 100644 index 2ae78af..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/SdcConnectorClient.java +++ /dev/null @@ -1,398 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.http; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpEntity; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.openecomp.sdc.api.asdc.RegistrationRequest; -import org.openecomp.sdc.api.asdc.ServerListResponse; -import org.openecomp.sdc.api.consumer.IConfiguration; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.results.IDistributionClientResult; -import org.openecomp.sdc.impl.DistributionClientDownloadResultImpl; -import org.openecomp.sdc.impl.DistributionClientResultImpl; -import org.openecomp.sdc.utils.DistributionActionResultEnum; -import org.openecomp.sdc.utils.DistributionClientConstants; -import org.openecomp.sdc.utils.GeneralUtils; -import org.openecomp.sdc.utils.Pair; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.apiClient.credentials.ApiCredential; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; - -import fj.data.Either; - -public class SdcConnectorClient { - String contentDispositionHeader = "Content-Disposition"; - private static Logger log = LoggerFactory.getLogger(SdcConnectorClient.class.getName()); - private IConfiguration configuration; - private HttpAsdcClient httpClient = null; - - public void init(IConfiguration configuraion) { - this.configuration = configuraion; - httpClient = new HttpAsdcClient(configuration); - } - - public void close() { - if (httpClient != null) { - httpClient.closeHttpClient(); - } - } - - public IConfiguration getConfiguration() { - return configuration; - } - - public void setConfiguration(IConfiguration configuration) { - this.configuration = configuration; - } - - public HttpAsdcClient getHttpClient() { - return httpClient; - } - - public void setHttpClient(HttpAsdcClient httpClient) { - this.httpClient = httpClient; - } - - - public Either, IDistributionClientResult> getValidArtifactTypesList() { - Pair getServersResponsePair = performAsdcServerRequest(AsdcUrls.GET_VALID_ARTIFACT_TYPES); - HttpAsdcResponse getArtifactTypeResponse = getServersResponsePair.getFirst(); - - Either, IDistributionClientResult> response; - if (getArtifactTypeResponse.getStatus() == HttpStatus.SC_OK) { - response = parseGetValidArtifactTypesResponse(getArtifactTypeResponse); - } else { - IDistributionClientResult asdcError = handleAsdcError(getArtifactTypeResponse); - response = Either.right(asdcError); - - } - handeAsdcConnectionClose(getServersResponsePair); - return response; - - } - - private void handeAsdcConnectionClose(Pair getServersResponsePair) { - if (getServersResponsePair.getSecond() != null) { - try { - getServersResponsePair.getSecond().close(); - - } catch (IOException e) { - log.error("failed to close http response"); - } - - } - } - - private Pair performAsdcServerRequest(final String url) { - String requestId = UUID.randomUUID().toString(); - Map requestHeaders = addHeadersToHttpRequest(requestId); - log.debug("about to perform getServerList. requestId= {} url= {}", requestId, url); - Pair getServersResponsePair = httpClient.getRequest(url, requestHeaders, false); - return getServersResponsePair; - } - - public Either registerAsdcTopics(ApiCredential credential) { - - Either response = null; - - String requestId = UUID.randomUUID().toString(); - Map requestHeaders = addHeadersToHttpRequest(requestId); - - RegistrationRequest registrationRequest = new RegistrationRequest(credential.getApiKey(), configuration.getEnvironmentName(), configuration.isConsumeProduceStatusTopic(), configuration.getMsgBusAddress()); - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - String jsonRequest = gson.toJson(registrationRequest); - StringEntity body = new StringEntity(jsonRequest, ContentType.APPLICATION_JSON); - - log.debug("about to perform registerAsdcTopics. requestId= " + requestId + " url= " + AsdcUrls.POST_FOR_TOPIC_REGISTRATION); - Pair registerResponsePair = httpClient.postRequest(AsdcUrls.POST_FOR_TOPIC_REGISTRATION, body, requestHeaders, false); - HttpAsdcResponse registerResponse = registerResponsePair.getFirst(); - int status = registerResponse.getStatus(); - - if (status == HttpStatus.SC_OK) { - response = parseRegistrationResponse(registerResponse); - - } else { - DistributionClientResultImpl asdcError = handleAsdcError(registerResponse); - return Either.right(asdcError); - } - handeAsdcConnectionClose(registerResponsePair); - - log.debug("registerAsdcTopics response= " + status + ". requestId= " + requestId + " url= " + AsdcUrls.POST_FOR_TOPIC_REGISTRATION); - return response; - - } - - public IDistributionClientResult unregisterTopics(ApiCredential credential) { - - DistributionClientResultImpl response = null; - - String requestId = UUID.randomUUID().toString(); - HttpAsdcClient httpClient = new HttpAsdcClient(configuration); - Map requestHeaders = addHeadersToHttpRequest(requestId); - - RegistrationRequest registrationRequest = new RegistrationRequest(credential.getApiKey(), configuration.getEnvironmentName(), configuration.isConsumeProduceStatusTopic(), configuration.getMsgBusAddress()); - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - String jsonRequest = gson.toJson(registrationRequest); - StringEntity body = new StringEntity(jsonRequest, ContentType.APPLICATION_JSON); - - log.debug("about to perform unregisterTopics. requestId= " + requestId + " url= " + AsdcUrls.POST_FOR_UNREGISTER); - Pair unRegisterResponsePair = httpClient.postRequest(AsdcUrls.POST_FOR_UNREGISTER, body, requestHeaders, false); - HttpAsdcResponse unRegisterResponse = unRegisterResponsePair.getFirst(); - int status = unRegisterResponse.getStatus(); - if (status == HttpStatus.SC_NO_CONTENT || status == HttpStatus.SC_OK) { - response = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "unregistration successful"); - - } else { - response = handleAsdcError(unRegisterResponse); - } - - handeAsdcConnectionClose(unRegisterResponsePair); - - log.debug("unregisterTopics response = " + status + ". requestId= " + requestId + " url= " + AsdcUrls.POST_FOR_UNREGISTER); - - return response; - - } - - public DistributionClientDownloadResultImpl dowloadArtifact(IArtifactInfo artifactInfo) { - DistributionClientDownloadResultImpl response = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "failed to download artifact from ASDC"); - - String requestId = UUID.randomUUID().toString(); - Map requestHeaders = new HashMap(); - requestHeaders.put(DistributionClientConstants.HEADER_REQUEST_ID, requestId); - requestHeaders.put(DistributionClientConstants.HEADER_INSTANCE_ID, configuration.getConsumerID()); - requestHeaders.put(HttpHeaders.ACCEPT, ContentType.APPLICATION_OCTET_STREAM.toString()); - String requestUrl = artifactInfo.getArtifactURL(); - Pair downloadPair = httpClient.getRequest(requestUrl, requestHeaders, false); - HttpAsdcResponse downloadResponse = downloadPair.getFirst(); - - int status = downloadResponse.getStatus(); - if (status == 200) { - - response = parseDownloadArtifactResponse(artifactInfo, downloadResponse); - } else { - response = handleAsdcDownloadArtifactError(downloadResponse); - - } - handeAsdcConnectionClose(downloadPair); - return response; - } - - /* **************************** private methods ********************************************/ - - private Either, IDistributionClientResult> parseGetServersResponse(HttpAsdcResponse getServersResponse) { - Either, IDistributionClientResult> result; - try { - String jsonMessage = IOUtils.toString(getServersResponse.getMessage().getContent()); - - Gson gson = new GsonBuilder().create(); - ServerListResponse serverListResponse = gson.fromJson(jsonMessage, ServerListResponse.class); - List serverList = serverListResponse.getUebServerList(); - result = Either.left(serverList); - - } catch (UnsupportedOperationException | IOException e) { - result = handleParsingError(e); - } - - return result; - } - - private Either, IDistributionClientResult> parseGetValidArtifactTypesResponse(HttpAsdcResponse getArtifactTypesResponse) { - Either, IDistributionClientResult> result; - try { - String jsonMessage = IOUtils.toString(getArtifactTypesResponse.getMessage().getContent()); - Type listType = new TypeToken>() { - }.getType(); - Gson gson = new GsonBuilder().create(); - List artifactTypesList = gson.fromJson(jsonMessage, listType); - result = Either.left(artifactTypesList); - - } catch (UnsupportedOperationException | IOException e) { - result = handleParsingError(e); - } - - return result; - } - - private Either, IDistributionClientResult> handleParsingError(Exception e) { - Either, IDistributionClientResult> result; - log.error("failed to parse response from ASDC. error: " + e.getMessage()); - IDistributionClientResult response = new DistributionClientResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "failed to parse response from ASDC"); - result = Either.right(response); - return result; - } - - Either parseRegistrationResponse(HttpAsdcResponse registerResponse) { - - String jsonMessage; - try { - jsonMessage = IOUtils.toString(registerResponse.getMessage().getContent()); - - Gson gson = new GsonBuilder().create(); - TopicRegistrationResponse registrationResponse = gson.fromJson(jsonMessage, TopicRegistrationResponse.class); - - if (registrationResponse.getDistrNotificationTopicName() == null) { - DistributionClientResultImpl response = new DistributionClientResultImpl(DistributionActionResultEnum.FAIL, "failed to receive notification topic from ASDC"); - return Either.right(response); - } - - if (registrationResponse.getDistrStatusTopicName() == null) { - DistributionClientResultImpl response = new DistributionClientResultImpl(DistributionActionResultEnum.FAIL, "failed to receive status topic from ASDC"); - return Either.right(response); - } - return Either.left(registrationResponse); - - } catch (UnsupportedOperationException | IOException e) { - log.error("failed to pars response from ASDC. error: " + e.getMessage()); - DistributionClientResultImpl response = new DistributionClientResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "failed to parse response from ASDC"); - return Either.right(response); - } - } - - protected Map addHeadersToHttpRequest(String requestId) { - Map requestHeaders = new HashMap<>(); - requestHeaders.put(DistributionClientConstants.HEADER_REQUEST_ID, requestId); - requestHeaders.put(DistributionClientConstants.HEADER_INSTANCE_ID, configuration.getConsumerID()); - requestHeaders.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); - - return requestHeaders; - } - - private DistributionClientResultImpl handleAsdcError(HttpAsdcResponse registerResponse) { - int status = registerResponse.getStatus(); - DistributionClientResultImpl errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "failed to send request to ASDC"); - if (status == HttpStatus.SC_UNAUTHORIZED) { - errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_AUTHENTICATION_FAILED, "authentication to ASDC failed for user " + configuration.getUser()); - } else if (status == HttpStatus.SC_FORBIDDEN) { - errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_AUTHORIZATION_FAILED, "authorization failure for user " + configuration.getUser()); - } else if (status == HttpStatus.SC_BAD_REQUEST) { - errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.BAD_REQUEST, "ASDC call failed due to missing information"); - } else if (status == HttpStatus.SC_NOT_FOUND) { - errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_NOT_FOUND, "ASDC not found"); - } else if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) { - errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_SERVER_PROBLEM, "ASDC server problem"); - } else if (status == HttpStatus.SC_BAD_GATEWAY) { - errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, "ASDC server problem"); - } else if (status == HttpStatus.SC_GATEWAY_TIMEOUT) { - errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_SERVER_TIMEOUT, "ASDC server problem"); - } - log.error("status from ASDC is " + registerResponse); - log.error(errorResponse.toString()); - try { - String errorString = IOUtils.toString(registerResponse.getMessage().getContent()); - log.debug("error from ASDC is: " + errorString); - } catch (UnsupportedOperationException | IOException e) { - } - return errorResponse; - - } - - private DistributionClientDownloadResultImpl handleAsdcDownloadArtifactError(HttpAsdcResponse registerResponse) { - int status = registerResponse.getStatus(); - DistributionClientDownloadResultImpl errorResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "failed to send request to ASDC"); - if (status == HttpStatus.SC_UNAUTHORIZED) { - errorResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.ASDC_AUTHENTICATION_FAILED, "authentication to ASDC failed for user " + configuration.getUser()); - } else if (status == HttpStatus.SC_FORBIDDEN) { - errorResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.ASDC_AUTHORIZATION_FAILED, "authorization failure for user " + configuration.getUser()); - } else if (status == HttpStatus.SC_BAD_REQUEST || status == HttpStatus.SC_NOT_FOUND) { - errorResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.ARTIFACT_NOT_FOUND, "Specified artifact is not found"); - // } else if (status == 404){ - // errorResponse = new DistributionClientDownloadResultImpl( - // DistributionActionResultEnum.ASDC_NOT_FOUND, - // "ASDC not found"); - } else if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) { - errorResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.ASDC_SERVER_PROBLEM, "ASDC server problem"); - } - log.error("status from ASDC is " + registerResponse); - log.error(errorResponse.toString()); - try { - String errorString = IOUtils.toString(registerResponse.getMessage().getContent()); - log.debug("error from ASDC is: " + errorString); - } catch (UnsupportedOperationException | IOException e) { - } - return errorResponse; - - } - - private DistributionClientDownloadResultImpl parseDownloadArtifactResponse(IArtifactInfo artifactInfo, HttpAsdcResponse getServersResponse) { - HttpEntity entity = getServersResponse.getMessage(); - InputStream is; - try { - is = entity.getContent(); - String artifactName = ""; - if (getServersResponse.getHeadersMap().containsKey(contentDispositionHeader)) - artifactName = getServersResponse.getHeadersMap().get(contentDispositionHeader); - - byte[] payload = IOUtils.toByteArray(is); - if (artifactInfo.getArtifactChecksum() == null || artifactInfo.getArtifactChecksum().isEmpty()) { - return new DistributionClientDownloadResultImpl(DistributionActionResultEnum.DATA_INTEGRITY_PROBLEM, "failed to get artifact from ASDC. Empty checksum"); - } - - DistributionClientDownloadResultImpl resResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS, "success", artifactName, payload); - return resResponse; - - //Validate checksum removed as fix to bug 293657 - /*if (validateChecksum(artifactInfo, payload)) { - DistributionClientDownloadResultImpl resResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS, "success", artifactName, payload); - return resResponse; - - } else { - - return new DistributionClientDownloadResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "Invalid checksum. ArtifactInfo checksum "); - }*/ - - } catch (UnsupportedOperationException | IOException e) { - log.error("failed to get artifact from response "); - return new DistributionClientDownloadResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "UnsupportedOperationException "); - } - - } - - private boolean validateChecksum(IArtifactInfo artifactInfo, byte[] payload) { - boolean bRes = false; - String calculatedMD5 = GeneralUtils.calculateMD5(payload); - if (artifactInfo.getArtifactChecksum().equals(calculatedMD5)) { - bRes = true; - } - - return bRes; - } - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/TopicRegistrationResponse.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/TopicRegistrationResponse.java deleted file mode 100644 index 280d7da..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/http/TopicRegistrationResponse.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.http; - -public class TopicRegistrationResponse { - String distrNotificationTopicName; - String distrStatusTopicName; - - - public void setDistrNotificationTopicName(String distrNotificationTopicName) { - this.distrNotificationTopicName = distrNotificationTopicName; - } - public void setDistrStatusTopicName(String distrStatusTopicName) { - this.distrStatusTopicName = distrStatusTopicName; - } - - public String getDistrNotificationTopicName() { - return distrNotificationTopicName; - } - public String getDistrStatusTopicName() { - return distrStatusTopicName; - } -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/ArtifactInfoImpl.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/ArtifactInfoImpl.java deleted file mode 100644 index 64ff9a8..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/ArtifactInfoImpl.java +++ /dev/null @@ -1,192 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl; - -import java.util.ArrayList; -import java.util.List; - -import org.openecomp.sdc.api.notification.IArtifactInfo; - -class ArtifactInfoImpl implements IArtifactInfo { - - private String artifactName; - private String artifactType; - private String artifactURL; - private String artifactChecksum; - private String artifactDescription; - private Integer artifactTimeout; - private String artifactVersion; - private String artifactUUID; - private String generatedFromUUID; - private IArtifactInfo generatedArtifact; - private List relatedArtifacts; - private List relatedArtifactsInfo; - ArtifactInfoImpl(){} - - private ArtifactInfoImpl(IArtifactInfo iArtifactInfo){ - artifactName = iArtifactInfo.getArtifactName(); - artifactType = iArtifactInfo.getArtifactType(); - artifactURL = iArtifactInfo.getArtifactURL(); - artifactChecksum = iArtifactInfo.getArtifactChecksum(); - artifactDescription = iArtifactInfo.getArtifactDescription(); - artifactTimeout = iArtifactInfo.getArtifactTimeout(); - artifactVersion = iArtifactInfo.getArtifactVersion(); - artifactUUID = iArtifactInfo.getArtifactUUID(); - generatedArtifact = iArtifactInfo.getGeneratedArtifact(); - relatedArtifactsInfo = iArtifactInfo.getRelatedArtifacts(); - relatedArtifacts = fillRelatedArtifactsUUID(relatedArtifactsInfo); - - } - - - private List fillRelatedArtifactsUUID(List relatedArtifactsInfo) { - List relatedArtifactsUUID = null; - if( relatedArtifactsInfo != null && !relatedArtifactsInfo.isEmpty()){ - relatedArtifactsUUID = new ArrayList<>(); - for(IArtifactInfo curr: relatedArtifactsInfo){ - relatedArtifactsUUID.add(curr.getArtifactUUID()); - } - } - return relatedArtifactsUUID; - } - - public static List convertToArtifactInfoImpl(List list){ - List ret = new ArrayList(); - if( list != null ){ - for(IArtifactInfo artifactInfo : list ){ - ret.add(new ArtifactInfoImpl(artifactInfo)); - } - } - return ret; - } - - public String getArtifactName() { - return artifactName; - } - - public void setArtifactName(String artifactName) { - this.artifactName = artifactName; - } - - public String getArtifactType() { - return artifactType; - } - - public void setArtifactType(String artifactType) { - this.artifactType = artifactType; - } - - public String getArtifactURL() { - return artifactURL; - } - - public void setArtifactURL(String artifactURL) { - this.artifactURL = artifactURL; - } - - public String getArtifactChecksum() { - return artifactChecksum; - } - - public void setArtifactChecksum(String artifactChecksum) { - this.artifactChecksum = artifactChecksum; - } - - public String getArtifactDescription() { - return artifactDescription; - } - - public void setArtifactDescription(String artifactDescription) { - this.artifactDescription = artifactDescription; - } - - public Integer getArtifactTimeout() { - return artifactTimeout; - } - - public void setArtifactTimeout(Integer artifactTimeout) { - this.artifactTimeout = artifactTimeout; - } - - @Override - public String toString() { - return "BaseArtifactInfoImpl [artifactName=" + artifactName - + ", artifactType=" + artifactType + ", artifactURL=" - + artifactURL + ", artifactChecksum=" + artifactChecksum - + ", artifactDescription=" + artifactDescription - + ", artifactVersion=" + artifactVersion - + ", artifactUUID=" + artifactUUID - + ", artifactTimeout=" + artifactTimeout + "]"; - } - - public String getArtifactVersion() { - return artifactVersion; - } - - public void setArtifactVersion(String artifactVersion) { - this.artifactVersion = artifactVersion; - } - - public String getArtifactUUID() { - return artifactUUID; - } - - public void setArtifactUUID(String artifactUUID) { - this.artifactUUID = artifactUUID; - } - - public String getGeneratedFromUUID() { - return generatedFromUUID; - } - - public void setGeneratedFromUUID(String generatedFromUUID) { - this.generatedFromUUID = generatedFromUUID; - } - - public IArtifactInfo getGeneratedArtifact() { - return generatedArtifact; - } - - public void setGeneratedArtifact(IArtifactInfo generatedArtifact) { - this.generatedArtifact = generatedArtifact; - } - - public List getRelatedArtifacts(){ - List temp = new ArrayList(); - if( relatedArtifactsInfo != null ){ - temp.addAll(relatedArtifactsInfo); - } - return temp; - } - - public void setRelatedArtifacts(List relatedArtifacts) { - this.relatedArtifacts = relatedArtifacts; - } - - public void setRelatedArtifactsInfo(List relatedArtifactsInfo) { - this.relatedArtifactsInfo = relatedArtifactsInfo; - } - - public List getRelatedArtifactsUUID(){ - return relatedArtifacts; - } - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/Configuration.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/Configuration.java deleted file mode 100644 index 851a198..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/Configuration.java +++ /dev/null @@ -1,228 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl; - -import java.util.List; - -import fj.data.Either; -import org.openecomp.sdc.api.consumer.IConfiguration; -import org.openecomp.sdc.api.results.IDistributionClientResult; -import org.openecomp.sdc.utils.DistributionActionResultEnum; -import org.openecomp.sdc.utils.DistributionClientConstants; - -public class Configuration implements IConfiguration { - - private List msgBusAddressList; - private String asdcAddress; - private String user; - private String password; - private int pollingInterval = DistributionClientConstants.MIN_POLLING_INTERVAL_SEC; - private int pollingTimeout = DistributionClientConstants.POLLING_TIMEOUT_SEC; - private List relevantArtifactTypes; - private String consumerGroup; - private String environmentName; - private String comsumerID; - private String keyStorePath; - private String keyStorePassword; - private boolean activateServerTLSAuth; - private boolean filterInEmptyResources; - private Boolean useHttpsWithDmaap; - private boolean consumeProduceStatusTopic; - - public Configuration(IConfiguration other) { - this.asdcAddress = other.getAsdcAddress(); - this.msgBusAddressList = other.getMsgBusAddress(); - this.comsumerID = other.getConsumerID(); - this.consumerGroup = other.getConsumerGroup(); - this.environmentName = other.getEnvironmentName(); - this.password = other.getPassword(); - this.pollingInterval = other.getPollingInterval(); - this.pollingTimeout = other.getPollingTimeout(); - this.relevantArtifactTypes = other.getRelevantArtifactTypes(); - this.user = other.getUser(); - this.keyStorePath = other.getKeyStorePath(); - this.keyStorePassword = other.getKeyStorePassword(); - this.activateServerTLSAuth = other.activateServerTLSAuth(); - this.filterInEmptyResources = other.isFilterInEmptyResources(); - this.useHttpsWithDmaap = other.isUseHttpsWithDmaap(); - this.consumeProduceStatusTopic = other.isConsumeProduceStatusTopic(); - } - - @Override - public String getAsdcAddress() { - return asdcAddress; - } - - @Override - public List getMsgBusAddress() { - return msgBusAddressList; - } - - @Override - public String getUser() { - return user; - } - - @Override - public String getPassword() { - return password; - } - - @Override - public int getPollingInterval() { - return pollingInterval; - } - - @Override - public int getPollingTimeout() { - return pollingTimeout; - } - - @Override - public List getRelevantArtifactTypes() { - return relevantArtifactTypes; - } - - @Override - public String getConsumerGroup() { - return consumerGroup; - } - - @Override - public String getEnvironmentName() { - return environmentName; - } - - @Override - public String getConsumerID() { - return comsumerID; - } - - @Override - public String getKeyStorePath() { - return keyStorePath; - } - - @Override - public String getKeyStorePassword() { - return keyStorePassword; - } - - public String getComsumerID() { - return comsumerID; - } - - public void setComsumerID(String comsumerID) { - this.comsumerID = comsumerID; - } - - public void setAsdcAddress(String asdcAddress) { - this.asdcAddress = asdcAddress; - } - - public void setUser(String user) { - this.user = user; - } - - public void setPassword(String password) { - this.password = password; - } - - public void setPollingInterval(int pollingInterval) { - this.pollingInterval = pollingInterval; - } - - public void setPollingTimeout(int pollingTimeout) { - this.pollingTimeout = pollingTimeout; - } - - public void setRelevantArtifactTypes(List relevantArtifactTypes) { - this.relevantArtifactTypes = relevantArtifactTypes; - } - - public void setConsumerGroup(String consumerGroup) { - this.consumerGroup = consumerGroup; - } - - public void setEnvironmentName(String environmentName) { - this.environmentName = environmentName; - } - - public void setKeyStorePath(String keyStorePath) { - this.keyStorePath = keyStorePath; - } - - public void setKeyStorePassword(String keyStorePassword) { - this.keyStorePassword = keyStorePassword; - } - - public void setactivateServerTLSAuth(boolean activateServerTLSAuth) { - this.activateServerTLSAuth = activateServerTLSAuth; - } - - @Override - public boolean activateServerTLSAuth() { - return this.activateServerTLSAuth; - } - - @Override - public boolean isFilterInEmptyResources() { - return this.filterInEmptyResources; - } - - @Override - public Boolean isUseHttpsWithDmaap() { - return this.useHttpsWithDmaap; - } - - public void setUseHttpsWithDmaap(boolean useHttpsWithDmaap) { - this.useHttpsWithDmaap = useHttpsWithDmaap; - } - - @Override - public boolean isConsumeProduceStatusTopic() { - return this.consumeProduceStatusTopic; - } - - @Override - public String toString() { - //@formatter:off - return "Configuration ["+ - "asdcAddress=" + asdcAddress + - ", user=" + user + - ", password=" + password + - ", pollingInterval=" + pollingInterval + - ", pollingTimeout=" + pollingTimeout + - ", relevantArtifactTypes=" + relevantArtifactTypes + - ", consumerGroup=" + consumerGroup + - ", environmentName=" + environmentName + - ", comsumerID=" + comsumerID + - ", keyStorePath=" + keyStorePath + - ", keyStorePassword=" + keyStorePassword + - ", activateServerTLSAuth=" + activateServerTLSAuth + - ", filterInEmptyResources=" + filterInEmptyResources + - ", useHttpsWithDmaap=" + useHttpsWithDmaap + - ", consumeProduceStatusTopic=" + consumeProduceStatusTopic + - "]"; - //@formatter:on - } - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionClientDownloadResultImpl.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionClientDownloadResultImpl.java deleted file mode 100644 index 0fa918a..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionClientDownloadResultImpl.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl; - -import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; -import org.openecomp.sdc.utils.DistributionActionResultEnum; - -public class DistributionClientDownloadResultImpl extends DistributionClientResultImpl implements IDistributionClientDownloadResult{ - byte[] artifactPayload; - String artifactName; - - - public DistributionClientDownloadResultImpl( - DistributionActionResultEnum responseStatus, String responseMessage) { - super(responseStatus, responseMessage); - - } - - public DistributionClientDownloadResultImpl( - DistributionActionResultEnum responseStatus, - String responseMessage, String artifactName, byte[] artifactPayload) { - super(responseStatus, responseMessage); - this.artifactPayload = artifactPayload; - this.artifactName = artifactName; - } - - - public void setArtifactPayload(byte[] payload) { - this.artifactPayload = payload; - } - - - public byte[] getArtifactPayload() { - - return artifactPayload; - } - - public String getArtifactName(){ - return artifactName; - } - - public void setArtifactName(String artifactName){ - this.artifactName = artifactName; - } - - @Override - public String getArtifactFilename() { - //Fix of bug 292443 in TDP - if (artifactName == null || !artifactName.matches("attachment;\\s*filename=\".*?\"")){ - return artifactName; - } - String fileName = "filename=\""; - return artifactName.substring(artifactName.indexOf(fileName)+fileName.length(), artifactName.lastIndexOf("\"")); - } - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionClientFactory.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionClientFactory.java deleted file mode 100644 index 467f9cb..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionClientFactory.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl; - -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.impl.mock.DistributionClientStubImpl; - -public class DistributionClientFactory { - public static IDistributionClient createDistributionClient(){ - return new DistributionClientImpl(); - } - - public static IDistributionClient createMockDistributionClient(){ - return new DistributionClientStubImpl(); - } -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionClientImpl.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionClientImpl.java deleted file mode 100644 index a8778e5..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionClientImpl.java +++ /dev/null @@ -1,778 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl; - -import static java.util.Objects.isNull; - -import java.io.IOException; -import java.lang.reflect.Type; -import java.net.MalformedURLException; -import java.nio.charset.StandardCharsets; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.UUID; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; - -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.IDistributionStatusMessageJsonBuilder; -import org.openecomp.sdc.api.consumer.*; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.IVfModuleMetadata; -import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; -import org.openecomp.sdc.api.results.IDistributionClientResult; -import org.openecomp.sdc.http.SdcConnectorClient; -import org.openecomp.sdc.http.TopicRegistrationResponse; -import org.openecomp.sdc.utils.DistributionActionResultEnum; -import org.openecomp.sdc.utils.DistributionClientConstants; -import org.openecomp.sdc.utils.GeneralUtils; -import org.openecomp.sdc.utils.Wrapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.apiClient.credentials.ApiCredential; -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.cambria.client.CambriaBatchingPublisher; -import com.att.nsa.cambria.client.CambriaClient.CambriaApiException; -import com.att.nsa.cambria.client.CambriaClientBuilders.AbstractAuthenticatedManagerBuilder; -import com.att.nsa.cambria.client.CambriaClientBuilders.ConsumerBuilder; -import com.att.nsa.cambria.client.CambriaClientBuilders.IdentityManagerBuilder; -import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder; -import com.att.nsa.cambria.client.CambriaConsumer; -import com.att.nsa.cambria.client.CambriaIdentityManager; -import com.att.nsa.cambria.client.CambriaPublisher.message; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; - -import fj.data.Either; - -public class DistributionClientImpl implements IDistributionClient { - - private static Logger log = LoggerFactory.getLogger(DistributionClientImpl.class.getName()); - - protected SdcConnectorClient asdcConnector = new SdcConnectorClient(); - private ScheduledExecutorService executorPool = null; - protected CambriaIdentityManager cambriaIdentityManager = null; - private List brokerServers; - protected ApiCredential credential; - protected Configuration configuration; - private INotificationCallback callback; - private IStatusCallback statusCallback; - private String notificationTopic; - private String statusTopic; - private boolean isConsumerGroupGenerated = false; - - private boolean isInitialized, isStarted, isTerminated; - - @Override - public IConfiguration getConfiguration() { - return configuration; - } - - @Override - /* see javadoc */ - public synchronized IDistributionClientResult updateConfiguration(IConfiguration conf) { - - log.info("update DistributionClient configuration"); - Wrapper errorWrapper = new Wrapper<>(); - validateRunReady(errorWrapper); - - if (!errorWrapper.isEmpty()) { - return errorWrapper.getInnerElement(); - } - - IDistributionClientResult updateResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "configuration updated successfuly"); - - boolean needToUpdateCambriaConsumer = false; - - if (conf.getRelevantArtifactTypes() != null && !conf.getRelevantArtifactTypes().isEmpty()) { - configuration.setRelevantArtifactTypes(conf.getRelevantArtifactTypes()); - needToUpdateCambriaConsumer = true; - } - if (isPollingIntervalValid(conf.getPollingInterval())) { - configuration.setPollingInterval(conf.getPollingInterval()); - needToUpdateCambriaConsumer = true; - } - if (isPollingTimeoutValid(conf.getPollingTimeout())) { - configuration.setPollingTimeout(conf.getPollingTimeout()); - needToUpdateCambriaConsumer = true; - } - if (conf.getConsumerGroup() != null) { - configuration.setConsumerGroup(conf.getConsumerGroup()); - isConsumerGroupGenerated = false; - needToUpdateCambriaConsumer = true; - } else if (!isConsumerGroupGenerated) { - generateConsumerGroup(); - } - - if (needToUpdateCambriaConsumer) { - updateResult = restartConsumer(); - } - - return updateResult; - } - - @Override - /** - * Start polling the Notification topic - */ - public synchronized IDistributionClientResult start() { - - log.info("start DistributionClient"); - IDistributionClientResult startResult; - CambriaConsumer cambriaNotificationConsumer = null; - Wrapper errorWrapper = new Wrapper<>(); - validateRunReady(errorWrapper); - if (errorWrapper.isEmpty()) { - validateNotStarted(errorWrapper); - } - if (errorWrapper.isEmpty()) { - try { - cambriaNotificationConsumer = new ConsumerBuilder().authenticatedBy(credential.getApiKey(), credential.getApiSecret()).knownAs(configuration.getConsumerGroup(), configuration.getConsumerID()).onTopic(notificationTopic).usingHttps(configuration.isUseHttpsWithDmaap()).usingHosts(brokerServers) - .withSocketTimeout(configuration.getPollingTimeout() * 1000).build(); - - } catch (MalformedURLException | GeneralSecurityException e) { - handleCambriaInitFailure(errorWrapper, e); - } - } - if (errorWrapper.isEmpty()) { - - List relevantArtifactTypes = configuration.getRelevantArtifactTypes(); - // Remove nulls from list - workaround for how configuration is built - while (relevantArtifactTypes.remove(null)); - - NotificationConsumer consumer = new NotificationConsumer(cambriaNotificationConsumer, callback, relevantArtifactTypes, this); - executorPool = Executors.newScheduledThreadPool(DistributionClientConstants.POOL_SIZE); - executorPool.scheduleAtFixedRate(consumer, 0, configuration.getPollingInterval(), TimeUnit.SECONDS); - - handleStatusConsumer(errorWrapper, executorPool); - } - if (!errorWrapper.isEmpty()) { - startResult = errorWrapper.getInnerElement(); - } - else{ - startResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "distribution client started successfuly"); - isStarted = true; - } - return startResult; - } - - private void handleStatusConsumer(Wrapper errorWrapper, ScheduledExecutorService executorPool) { - if( configuration.isConsumeProduceStatusTopic()){ - CambriaConsumer cambriaStatusConsumer = null; - try { - cambriaStatusConsumer = new ConsumerBuilder().authenticatedBy(credential.getApiKey(), credential.getApiSecret()).knownAs(configuration.getConsumerGroup(), configuration.getConsumerID()).onTopic(statusTopic).usingHttps(configuration.isUseHttpsWithDmaap()).usingHosts(brokerServers) - .withSocketTimeout(configuration.getPollingTimeout() * 1000).build(); - StatusConsumer statusConsumer = new StatusConsumer(cambriaStatusConsumer, statusCallback); - executorPool.scheduleAtFixedRate(statusConsumer, 0, configuration.getPollingInterval(), TimeUnit.SECONDS); - } catch (MalformedURLException | GeneralSecurityException e) { - handleCambriaInitFailure(errorWrapper, e); - } - } - } - - @Override - /* see javadoc */ - public synchronized IDistributionClientResult stop() { - - log.info("stop DistributionClient"); - Wrapper errorWrapper = new Wrapper<>(); - validateRunReady(errorWrapper); - if (!errorWrapper.isEmpty()) { - return errorWrapper.getInnerElement(); - } - // 1. stop polling notification topic - shutdownExecutor(); - - // 2. send to ASDC unregister to topic - IDistributionClientResult unregisterResult = asdcConnector.unregisterTopics(credential); - if (unregisterResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) { - log.info("client failed to unregister from topics"); - } else { - log.info("client unregistered from topics successfully"); - } - asdcConnector.close(); - - try { - cambriaIdentityManager.deleteCurrentApiKey(); - } catch (HttpException | IOException e) { - log.debug("failed to delete cambria keys", e); - } - cambriaIdentityManager.close(); - - isInitialized = false; - isTerminated = true; - - DistributionClientResultImpl stopResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "distribution client stopped successfuly"); - return stopResult; - } - - @Override - public IDistributionClientDownloadResult download(IArtifactInfo artifactInfo) { - log.info("DistributionClient - download"); - Wrapper errorWrapper = new Wrapper<>(); - validateRunReady(errorWrapper); - if (!errorWrapper.isEmpty()) { - IDistributionClientResult result = errorWrapper.getInnerElement(); - IDistributionClientDownloadResult downloadResult = new DistributionClientDownloadResultImpl(result.getDistributionActionResult(), result.getDistributionMessageResult()); - return downloadResult; - } - return asdcConnector.dowloadArtifact(artifactInfo); - } - @Override - public synchronized IDistributionClientResult init(IConfiguration conf, INotificationCallback notificationCallback, - IStatusCallback statusCallback) { - IDistributionClientResult initResult; - if( !conf.isConsumeProduceStatusTopic() ){ - initResult = new DistributionClientResultImpl(DistributionActionResultEnum.CONF_INVALID_CONSUME_PRODUCE_STATUS_TOPIC_FALG, "configuration is invalid: isConsumeProduceStatusTopic() should be set to 'true'" ); - - } - else if( isNull(statusCallback) ){ - initResult = new DistributionClientResultImpl(DistributionActionResultEnum.CONF_INVALID_CONSUME_PRODUCE_STATUS_TOPIC_FALG, "configuration is invalid: statusCallback is not defined" ); - } - else{ - this.statusCallback = statusCallback; - initResult = init(conf, notificationCallback); - } - return initResult; - } - - @Override - /* - * see javadoc - */ - public synchronized IDistributionClientResult init(IConfiguration conf, INotificationCallback callback) { - - log.info("DistributionClient - init"); - - Wrapper errorWrapper = new Wrapper<>(); - validateNotInitilized(errorWrapper); - if (errorWrapper.isEmpty()) { - validateNotTerminated(errorWrapper); - } - if (errorWrapper.isEmpty()) { - validateAndInitConfiguration(errorWrapper, conf); - } - // 1. get ueb server list from configuration - if (errorWrapper.isEmpty()) { - initUebServerList(errorWrapper); - } - // 2.validate artifact types against asdc server - if (errorWrapper.isEmpty()) { - validateArtifactTypesWithAsdcServer(conf, errorWrapper); - } - // 3. create keys - if (errorWrapper.isEmpty()) { - this.callback = callback; - createUebKeys(errorWrapper); - } - // 4. register for topics - if (errorWrapper.isEmpty()) { - registerForTopics(errorWrapper); - } - - IDistributionClientResult result; - if (errorWrapper.isEmpty()) { - isInitialized = true; - result = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "distribution client initialized successfuly"); - } else { - result = errorWrapper.getInnerElement(); - } - - return result; - } - - private void registerForTopics(Wrapper errorWrapper) { - Either registerAsdcTopics = asdcConnector.registerAsdcTopics(credential); - if (registerAsdcTopics.isRight()) { - - try { - cambriaIdentityManager.deleteCurrentApiKey(); - } catch (HttpException | IOException e) { - log.debug("failed to delete cambria keys", e); - } - errorWrapper.setInnerElement(registerAsdcTopics.right().value()); - } else { - TopicRegistrationResponse topics = registerAsdcTopics.left().value(); - notificationTopic = topics.getDistrNotificationTopicName(); - statusTopic = topics.getDistrStatusTopicName(); - } - - } - - private void createUebKeys(Wrapper errorWrapper) { - initCambriaClient(errorWrapper); - if (errorWrapper.isEmpty()) { - log.debug("create keys"); - DistributionClientResultImpl createKeysResponse = createUebKeys(); - if (createKeysResponse.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) { - errorWrapper.setInnerElement(createKeysResponse); - } - } - } - - private void validateArtifactTypesWithAsdcServer(IConfiguration conf, Wrapper errorWrapper) { - asdcConnector.init(configuration); - Either, IDistributionClientResult> eitherValidArtifactTypesList = asdcConnector.getValidArtifactTypesList(); - if (eitherValidArtifactTypesList.isRight()) { - DistributionActionResultEnum errorType = eitherValidArtifactTypesList.right().value().getDistributionActionResult(); - // Support the case of a new client and older ASDC Server which does not have the API - if (errorType != DistributionActionResultEnum.ASDC_NOT_FOUND) { - errorWrapper.setInnerElement(eitherValidArtifactTypesList.right().value()); - } - } else { - final List artifactTypesFromAsdc = eitherValidArtifactTypesList.left().value(); - boolean isArtifactTypesValid = artifactTypesFromAsdc.containsAll(conf.getRelevantArtifactTypes()); - if (!isArtifactTypesValid) { - List invalidArtifactTypes = new ArrayList<>(); - invalidArtifactTypes.addAll(conf.getRelevantArtifactTypes()); - invalidArtifactTypes.removeAll(artifactTypesFromAsdc); - DistributionClientResultImpl errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.CONF_CONTAINS_INVALID_ARTIFACT_TYPES, - "configuration contains invalid artifact types:" + invalidArtifactTypes + " valid types are:" + artifactTypesFromAsdc); - errorWrapper.setInnerElement(errorResponse); - } else { - log.debug("Artifact types: {} were validated with ASDC server", conf.getRelevantArtifactTypes()); - } - } - } - - private void initUebServerList(Wrapper errorWrapper) { - log.debug("get ueb cluster server list from component(configuration file)"); - - Either, IDistributionClientResult> serverListResponse = getUEBServerList(); - if (serverListResponse.isRight()) { - errorWrapper.setInnerElement(serverListResponse.right().value()); - } else { - - brokerServers = serverListResponse.left().value(); - } - - } - - private void validateNotInitilized(Wrapper errorWrapper) { - if (isInitialized) { - log.warn("distribution client already initialized"); - DistributionClientResultImpl alreadyInitResponse = new DistributionClientResultImpl(DistributionActionResultEnum.DISTRIBUTION_CLIENT_ALREADY_INITIALIZED, "distribution client already initialized"); - errorWrapper.setInnerElement(alreadyInitResponse); - } - } - - @Override - public IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage statusMessage) { - log.info("DistributionClient - sendDownloadStatus"); - Wrapper errorWrapper = new Wrapper<>(); - validateRunReady(errorWrapper); - if (!errorWrapper.isEmpty()) { - return errorWrapper.getInnerElement(); - } - - return sendStatus(DistributionStatusMessageJsonBuilderFactory.getSimpleBuilder(statusMessage)); - } - - private IDistributionClientResult sendStatus(IDistributionStatusMessageJsonBuilder builder) { - DistributionClientResultImpl statusResult = new DistributionClientResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "Failed to send status"); - log.info("DistributionClient - sendStatus"); - Either eitherPublisher = getCambriaPublisher(); - if (eitherPublisher.isRight()) { - return eitherPublisher.right().value(); - } - CambriaBatchingPublisher pub = eitherPublisher.left().value(); - - log.debug("after create publisher server list " + brokerServers.toString()); - String jsonRequest = builder.build(); - - log.debug("try to send status " + jsonRequest); - - try { - pub.send("MyPartitionKey", jsonRequest); - Thread.sleep(1000L); - } catch (IOException e) { - log.debug("DistributionClient - sendDownloadStatus. Failed to send download status"); - } catch (InterruptedException e) { - log.debug("DistributionClient - sendDownloadStatus. thread was interrupted"); - } - - finally { - - try { - List stuck = pub.close(10L, TimeUnit.SECONDS); - - if (!stuck.isEmpty()) { - log.debug("DistributionClient - sendDownloadStatus. " + stuck.size() + " messages unsent"); - } else { - statusResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "messages successfully sent"); - } - } catch (IOException | InterruptedException e) { - log.debug("DistributionClient - sendDownloadStatus. failed to send messages and close publisher "); - } - - } - return statusResult; - } - - private Either getCambriaPublisher() { - CambriaBatchingPublisher cambriaPublisher = null; - try { - cambriaPublisher = new PublisherBuilder().onTopic(statusTopic).usingHttps(configuration.isUseHttpsWithDmaap()).usingHosts(brokerServers).build(); - cambriaPublisher.setApiCredentials(credential.getApiKey(), credential.getApiSecret()); - } catch (MalformedURLException | GeneralSecurityException e) { - Wrapper errorWrapper = new Wrapper<>(); - handleCambriaInitFailure(errorWrapper, e); - return Either.right(errorWrapper.getInnerElement()); - } - return Either.left(cambriaPublisher); - } - - @Override - public IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage statusMessage) { - log.info("DistributionClient - sendDeploymentStatus"); - Wrapper errorWrapper = new Wrapper<>(); - validateRunReady(errorWrapper); - if (!errorWrapper.isEmpty()) { - return errorWrapper.getInnerElement(); - } - return sendStatus(DistributionStatusMessageJsonBuilderFactory.getSimpleBuilder(statusMessage)); - } - - IDistributionClientResult sendNotificationStatus(long currentTimeMillis, String distributionId, ArtifactInfoImpl artifactInfo, boolean isNotified) { - log.info("DistributionClient - sendNotificationStatus"); - Wrapper errorWrapper = new Wrapper<>(); - validateRunReady(errorWrapper); - if (!errorWrapper.isEmpty()) { - return errorWrapper.getInnerElement(); - } - return sendStatus(DistributionStatusMessageJsonBuilderFactory.prepareBuilderForNotificationStatus(getConfiguration().getConsumerID(), currentTimeMillis, distributionId, artifactInfo, isNotified)); - } - - /* *************************** Private Methods *************************************************** */ - - protected DistributionClientResultImpl createUebKeys() { - DistributionClientResultImpl response = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "keys created successfuly"); - try { - String description = String.format(DistributionClientConstants.CLIENT_DESCRIPTION, configuration.getConsumerID()); - credential = cambriaIdentityManager.createApiKey(DistributionClientConstants.EMAIL, description); - cambriaIdentityManager.setApiCredentials(credential.getApiKey(), credential.getApiSecret()); - - } catch (HttpException | CambriaApiException | IOException e) { - response = new DistributionClientResultImpl(DistributionActionResultEnum.UEB_KEYS_CREATION_FAILED, "failed to create keys: " + e.getMessage()); - log.error(response.toString()); - } - return response; - } - - private IDistributionClientResult restartConsumer() { - shutdownExecutor(); - return start(); - } - - protected DistributionActionResultEnum validateAndInitConfiguration(Wrapper errorWrapper, IConfiguration conf) { - DistributionActionResultEnum result = DistributionActionResultEnum.SUCCESS; - - if (conf == null) { - result = DistributionActionResultEnum.CONFIGURATION_IS_MISSING; - } else if (conf.getConsumerID() == null || conf.getConsumerID().isEmpty()) { - result = DistributionActionResultEnum.CONF_MISSING_CONSUMER_ID; - } else if (conf.getUser() == null || conf.getUser().isEmpty()) { - result = DistributionActionResultEnum.CONF_MISSING_USERNAME; - } else if (conf.getPassword() == null || conf.getPassword().isEmpty()) { - result = DistributionActionResultEnum.CONF_MISSING_PASSWORD; - } else if (conf.getMsgBusAddress() == null || conf.getMsgBusAddress().isEmpty()) { - result = DistributionActionResultEnum.CONF_MISSING_MSG_BUS_ADDRESS; - } else if (conf.getAsdcAddress() == null || conf.getAsdcAddress().isEmpty()) { - result = DistributionActionResultEnum.CONF_MISSING_ASDC_FQDN; - } else if (!isValidFqdn(conf.getAsdcAddress())) { - result = DistributionActionResultEnum.CONF_INVALID_ASDC_FQDN; - } else if (!isValidFqdns(conf.getMsgBusAddress())){ - result = DistributionActionResultEnum.CONF_INVALID_MSG_BUS_ADDRESS; - } else if (conf.getEnvironmentName() == null || conf.getEnvironmentName().isEmpty()) { - result = DistributionActionResultEnum.CONF_MISSING_ENVIRONMENT_NAME; - } else if (conf.getRelevantArtifactTypes() == null || conf.getRelevantArtifactTypes().isEmpty()) { - result = DistributionActionResultEnum.CONF_MISSING_ARTIFACT_TYPES; - } - else if( conf.isConsumeProduceStatusTopic() && Objects.isNull(statusCallback) ){ - result = DistributionActionResultEnum.CONF_INVALID_CONSUME_PRODUCE_STATUS_TOPIC_FALG; - } - // DistributionActionResultEnum.SUCCESS - else { - handleValidConf(conf); - } - - if (result != DistributionActionResultEnum.SUCCESS) { - - DistributionClientResultImpl initResult = new DistributionClientResultImpl(result, "configuration is invalid: " + result.name()); - - log.error(initResult.toString()); - errorWrapper.setInnerElement(initResult); - } - return result; - } - - private void handleValidConf(IConfiguration conf) { - this.configuration = new Configuration(conf); - if (!isPollingIntervalValid(conf.getPollingInterval())) { - configuration.setPollingInterval(DistributionClientConstants.MIN_POLLING_INTERVAL_SEC); - } - if (!isPollingTimeoutValid(conf.getPollingTimeout())) { - configuration.setPollingTimeout(DistributionClientConstants.POLLING_TIMEOUT_SEC); - } - if (conf.getConsumerGroup() == null) { - generateConsumerGroup(); - } - - //Default use HTTPS with DMAAP - if (conf.isUseHttpsWithDmaap() == null){ - configuration.setUseHttpsWithDmaap(true); - } - } - - private void generateConsumerGroup() { - String generatedConsumerGroup = UUID.randomUUID().toString(); - configuration.setConsumerGroup(generatedConsumerGroup); - isConsumerGroupGenerated = true; - } - - protected boolean isValidFqdn(String fqdn) { - try { - Matcher matcher = DistributionClientConstants.FQDN_PATTERN.matcher(fqdn); - return matcher.matches(); - } catch (Exception e) { - } - return false; - } - protected boolean isValidFqdns(List fqdns) { - if (fqdns != null && !fqdns.isEmpty()) { - for (String fqdn : fqdns) { - if (isValidFqdn(fqdn)) { - continue; - } else { - return false; - } - } - return true; - } - return false; - } - - private void shutdownExecutor() { - if (executorPool == null) - return; - - executorPool.shutdown(); // Disable new tasks from being submitted - try { - // Wait a while for existing tasks to terminate - if (!executorPool.awaitTermination(60, TimeUnit.SECONDS)) { - executorPool.shutdownNow(); // Cancel currently executing tasks - // Wait a while for tasks to respond to being cancelled - if (!executorPool.awaitTermination(60, TimeUnit.SECONDS)) - log.error("Pool did not terminate"); - } - } catch (InterruptedException ie) { - // (Re-)Cancel if current thread also interrupted - executorPool.shutdownNow(); - // Preserve interrupt status - Thread.currentThread().interrupt(); - } finally { - isStarted = false; - } - } - - private void validateRunReady(Wrapper errorWrapper) { - if (errorWrapper.isEmpty()) { - validateInitilized(errorWrapper); - } - if (errorWrapper.isEmpty()) { - validateNotTerminated(errorWrapper); - } - - } - - private void validateInitilized(Wrapper errorWrapper) { - if (!isInitialized) { - log.debug("client was not initialized"); - IDistributionClientResult result = new DistributionClientResultImpl(DistributionActionResultEnum.DISTRIBUTION_CLIENT_NOT_INITIALIZED, "distribution client was not initialized"); - errorWrapper.setInnerElement(result); - } - } - - private void validateNotStarted(Wrapper errorWrapper) { - if (isStarted) { - log.debug("client already started"); - IDistributionClientResult result = new DistributionClientResultImpl(DistributionActionResultEnum.DISTRIBUTION_CLIENT_ALREADY_STARTED, "distribution client already started"); - errorWrapper.setInnerElement(result); - } - } - - private void validateNotTerminated(Wrapper errorWrapper) { - if (isTerminated) { - log.debug("client was terminated"); - IDistributionClientResult result = new DistributionClientResultImpl(DistributionActionResultEnum.DISTRIBUTION_CLIENT_IS_TERMINATED, "distribution client was terminated"); - errorWrapper.setInnerElement(result); - } - } - - private boolean isPollingTimeoutValid(int timeout) { - boolean isValid = (timeout >= DistributionClientConstants.POLLING_TIMEOUT_SEC); - if (!isValid) { - log.warn("polling interval is out of range. value should be greater than or equals to " + DistributionClientConstants.POLLING_TIMEOUT_SEC); - log.warn("setting polling interval to default: " + DistributionClientConstants.POLLING_TIMEOUT_SEC); - } - return isValid; - } - - private boolean isPollingIntervalValid(int pollingInt) { - boolean isValid = (pollingInt >= DistributionClientConstants.MIN_POLLING_INTERVAL_SEC); - if (!isValid) { - log.warn("polling interval is out of range. value should be greater than or equals to " + DistributionClientConstants.MIN_POLLING_INTERVAL_SEC); - log.warn("setting polling interval to default: " + DistributionClientConstants.MIN_POLLING_INTERVAL_SEC); - } - return isValid; - } - - private synchronized void initCambriaClient(Wrapper errorWrapper) { - if (cambriaIdentityManager == null) { - try { - AbstractAuthenticatedManagerBuilder managerBuilder = new IdentityManagerBuilder().usingHosts(brokerServers); - if (configuration.isUseHttpsWithDmaap()){ - managerBuilder = managerBuilder.usingHttps(); - } - cambriaIdentityManager = managerBuilder.build(); - } catch (MalformedURLException | GeneralSecurityException e) { - handleCambriaInitFailure(errorWrapper, e); - } - } - } - - private void handleCambriaInitFailure(Wrapper errorWrapper, Exception e) { - final String errorMessage = "Failed initilizing cambria component:" + e.getMessage(); - IDistributionClientResult errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.CAMBRIA_INIT_FAILED, errorMessage); - errorWrapper.setInnerElement(errorResponse); - log.error(errorMessage); - log.debug(errorMessage, e); - } - - @Override - public IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage statusMessage, String errorReason) { - log.info("DistributionClient - sendDownloadStatus with errorReason"); - Wrapper errorWrapper = new Wrapper<>(); - validateRunReady(errorWrapper); - if (!errorWrapper.isEmpty()) { - return errorWrapper.getInnerElement(); - } - - return sendStatus(DistributionStatusMessageJsonBuilderFactory.getErrorReasonBuilder(statusMessage, errorReason)); - - } - - @Override - public IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage statusMessage, String errorReason) { - log.info("DistributionClient - sendDeploymentStatus with errorReason"); - Wrapper errorWrapper = new Wrapper<>(); - validateRunReady(errorWrapper); - if (!errorWrapper.isEmpty()) { - return errorWrapper.getInnerElement(); - } - return sendStatus(DistributionStatusMessageJsonBuilderFactory.getErrorReasonBuilder(statusMessage, errorReason)); - - } - - @Override - public IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage) { - log.info("DistributionClient - sendComponentDone status"); - Wrapper errorWrapper = new Wrapper<>(); - validateRunReady(errorWrapper); - if (!errorWrapper.isEmpty()) { - return errorWrapper.getInnerElement(); - } - return sendStatus(DistributionStatusMessageJsonBuilderFactory.getSimpleBuilder(statusMessage)); - - } - - @Override - public IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage, - String errorReason) { - log.info("DistributionClient - sendComponentDone status with errorReason"); - Wrapper errorWrapper = new Wrapper<>(); - validateRunReady(errorWrapper); - if (!errorWrapper.isEmpty()) { - return errorWrapper.getInnerElement(); - } - return sendStatus(DistributionStatusMessageJsonBuilderFactory.getErrorReasonBuilder(statusMessage, errorReason)); - } - - - @Override - public List decodeVfModuleArtifact(byte[] artifactPayload) { - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - String vfModuleJsonString = new String(artifactPayload, StandardCharsets.UTF_8); - final Type type = new TypeToken>() { - }.getType(); - List vfModules = gson.fromJson(vfModuleJsonString, type); - return vfModules; - } - - - public IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage) { - log.info("DistributionClient - sendFinalDistributionStatus status"); - Wrapper errorWrapper = new Wrapper<>(); - validateRunReady(errorWrapper); - if (!errorWrapper.isEmpty()) { - return errorWrapper.getInnerElement(); - } - return sendStatus(DistributionStatusMessageJsonBuilderFactory.getSimpleBuilder(statusMessage)); - - } - - - @Override - public IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage, - String errorReason) { - log.info("DistributionClient - sendFinalDistributionStatus status with errorReason"); - Wrapper errorWrapper = new Wrapper<>(); - validateRunReady(errorWrapper); - if (!errorWrapper.isEmpty()) { - return errorWrapper.getInnerElement(); - } - return sendStatus(DistributionStatusMessageJsonBuilderFactory.getErrorReasonBuilder(statusMessage, errorReason)); - - - } - - public Either,IDistributionClientResult> getUEBServerList() { - List msgBusAddresses = configuration.getMsgBusAddress(); - if(msgBusAddresses.isEmpty()){ - return Either.right(new DistributionClientResultImpl(DistributionActionResultEnum.CONF_MISSING_MSG_BUS_ADDRESS, "Message bus address was not found in the config file")); - } - else{ - return GeneralUtils.convertToValidHostName(msgBusAddresses); - } - } - - - - - - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionClientResultImpl.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionClientResultImpl.java deleted file mode 100644 index a5af31a..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionClientResultImpl.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl; - -import org.openecomp.sdc.api.results.IDistributionClientResult; -import org.openecomp.sdc.utils.DistributionActionResultEnum; - -public class DistributionClientResultImpl implements IDistributionClientResult { - - DistributionActionResultEnum responseStatus; - String responseMessage; - - public DistributionClientResultImpl(DistributionActionResultEnum responseStatus, String responseMessage) { - this.responseStatus = responseStatus; - this.responseMessage = responseMessage; - } - - @Override - public DistributionActionResultEnum getDistributionActionResult() { - return responseStatus; - } - - @Override - public String getDistributionMessageResult() { - return responseMessage; - } - - @Override - public String toString() { - return "DistributionClientResultImpl [responseStatus=" + responseStatus + ", responseMessage=" + responseMessage + "]"; - } -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionStatusMessageImpl.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionStatusMessageImpl.java deleted file mode 100644 index d9ed654..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionStatusMessageImpl.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl; - -import org.openecomp.sdc.api.consumer.IComponentDoneStatusMessage; -import org.openecomp.sdc.api.consumer.IDistributionStatusMessage; -import org.openecomp.sdc.api.consumer.IFinalDistrStatusMessage; -import org.openecomp.sdc.utils.DistributionStatusEnum; - -class DistributionStatusMessageImpl implements IDistributionStatusMessage { - - String distributionID; - String consumerID; - long timestamp; - String artifactURL; - DistributionStatusEnum status; - String errorReason; - private String componentName; - - public DistributionStatusMessageImpl(IDistributionStatusMessage message) { - super(); - distributionID = message.getDistributionID(); - consumerID = message.getConsumerID(); - timestamp = message.getTimestamp(); - artifactURL = message.getArtifactURL(); - status = message.getStatus(); - - } - - public DistributionStatusMessageImpl(IComponentDoneStatusMessage message) { - super(); - distributionID = message.getDistributionID(); - consumerID = message.getConsumerID(); - timestamp = message.getTimestamp(); - artifactURL = message.getArtifactURL(); - status = message.getStatus(); - componentName = message.getComponentName(); - } - - public DistributionStatusMessageImpl(IFinalDistrStatusMessage message) { - super(); - distributionID = message.getDistributionID(); - consumerID = message.getConsumerID(); - timestamp = message.getTimestamp(); - - artifactURL = ""; - status = message.getStatus(); - componentName = message.getComponentName(); - } - - @Override - public String getDistributionID() { - - return distributionID; - } - - @Override - public String getConsumerID() { - - return consumerID; - } - - @Override - public long getTimestamp() { - - return timestamp; - } - - @Override - public String getArtifactURL() { - - return artifactURL; - } - - @Override - public DistributionStatusEnum getStatus() { - - return status; - } - - public String getErrorReason() { - return errorReason; - } - - public void setErrorReason(String errorReason) { - this.errorReason = errorReason; - } - - public String getComponentName() { - return componentName; - } - - - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionStatusMessageJsonBuilderFactory.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionStatusMessageJsonBuilderFactory.java deleted file mode 100644 index e2f9f89..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/DistributionStatusMessageJsonBuilderFactory.java +++ /dev/null @@ -1,148 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl; - -import org.openecomp.sdc.api.IDistributionStatusMessageJsonBuilder; -import org.openecomp.sdc.api.consumer.IComponentDoneStatusMessage; -import org.openecomp.sdc.api.consumer.IDistributionStatusMessage; -import org.openecomp.sdc.api.consumer.IFinalDistrStatusMessage; -import org.openecomp.sdc.utils.DistributionStatusEnum; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -public class DistributionStatusMessageJsonBuilderFactory { - static Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - public static IDistributionStatusMessageJsonBuilder getSimpleBuilder(IDistributionStatusMessage statusMessage){ - DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage); - - return prepareBuilderFromImpl(message); - } - - public static IDistributionStatusMessageJsonBuilder getSimpleBuilder(IComponentDoneStatusMessage statusMessage){ - DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage); - - return prepareBuilderFromImpl(message); - } - - public static IDistributionStatusMessageJsonBuilder getSimpleBuilder(IFinalDistrStatusMessage statusMessage){ - DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage); - - return prepareBuilderFromImpl(message); - } - - public static IDistributionStatusMessageJsonBuilder getErrorReasonBuilder(IDistributionStatusMessage statusMessage, String errorReason){ - DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage); - message.setErrorReason(errorReason); - - return prepareBuilderFromImpl(message); - } - - public static IDistributionStatusMessageJsonBuilder getErrorReasonBuilder(IComponentDoneStatusMessage statusMessage, - String errorReason) { - DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage); - message.setErrorReason(errorReason); - return prepareBuilderFromImpl(message); - } - - public static IDistributionStatusMessageJsonBuilder getErrorReasonBuilder(IFinalDistrStatusMessage statusMessage, - String errorReason) { - DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage); - message.setErrorReason(errorReason); - return prepareBuilderFromImpl(message); - } - - static IDistributionStatusMessageJsonBuilder prepareBuilderForNotificationStatus(final String consumerId, final long currentTimeMillis, final String distributionId, - final ArtifactInfoImpl artifactInfo, boolean isNotified){ - - final DistributionStatusEnum fakeStatusToReplace = DistributionStatusEnum.DOWNLOAD_OK; - final String jsonRequest = buildDistributionStatusJson(consumerId, currentTimeMillis, distributionId, artifactInfo, fakeStatusToReplace); - - DistributionStatusNotificationEnum notificationStatus = isNotified ? DistributionStatusNotificationEnum.NOTIFIED : DistributionStatusNotificationEnum.NOT_NOTIFIED; - final String changedRequest = jsonRequest.replace(fakeStatusToReplace.name(), notificationStatus.name()); - IDistributionStatusMessageJsonBuilder builder = new IDistributionStatusMessageJsonBuilder() { - @Override - public String build() { - return changedRequest; - } - }; - return builder; - - } - - private static String buildDistributionStatusJson(final String consumerId, - final long currentTimeMillis, final String distributionId, - final ArtifactInfoImpl artifactInfo, - final DistributionStatusEnum fakeStatusToBeReplaced) { - IDistributionStatusMessage statusMessage = new IDistributionStatusMessage() { - @Override - public long getTimestamp() { - return currentTimeMillis; - } - - @Override - public DistributionStatusEnum getStatus() { - - return fakeStatusToBeReplaced; - } - - @Override - public String getDistributionID() { - return distributionId; - } - - @Override - public String getConsumerID() { - return consumerId; - } - - @Override - public String getArtifactURL() { - return artifactInfo.getArtifactURL(); - } - }; - - DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage); - final String jsonRequest = gson.toJson(message); - return jsonRequest; - } - - private static IDistributionStatusMessageJsonBuilder prepareBuilderFromImpl( DistributionStatusMessageImpl message) { - final String jsonRequest = gson.toJson(message); - IDistributionStatusMessageJsonBuilder builder = new IDistributionStatusMessageJsonBuilder() { - @Override - public String build() { - return jsonRequest; - } - }; - return builder; - } - - private enum DistributionStatusNotificationEnum { - NOTIFIED, NOT_NOTIFIED - } - - - - - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/JsonContainerResourceInstance.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/JsonContainerResourceInstance.java deleted file mode 100644 index 0000806..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/JsonContainerResourceInstance.java +++ /dev/null @@ -1,158 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl; - -import java.util.ArrayList; -import java.util.List; - -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.IResourceInstance; - -class JsonContainerResourceInstance implements IResourceInstance{ - JsonContainerResourceInstance (){} - private String resourceInstanceName; - private String resourceCustomizationUUID; - private String resourceName; - private String resourceVersion; - private String resoucreType; - private String resourceUUID; - private String resourceInvariantUUID; - private String category; - private String subcategory; - private List artifacts; - - private JsonContainerResourceInstance(IResourceInstance resourceInstance){ - resourceInstanceName = resourceInstance.getResourceInstanceName(); - resourceCustomizationUUID = resourceInstance.getResourceCustomizationUUID(); - resourceName = resourceInstance.getResourceName(); - resourceVersion = resourceInstance.getResourceVersion(); - resoucreType = resourceInstance.getResourceType(); - resourceUUID = resourceInstance.getResourceUUID(); - resourceInvariantUUID = resourceInstance.getResourceInvariantUUID(); - category = resourceInstance.getCategory(); - subcategory = resourceInstance.getSubcategory(); - artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(resourceInstance.getArtifacts()); - } - - public static List convertToJsonContainer(List resources){ - List buildResources = new ArrayList(); - if( resources != null ){ - for( IResourceInstance resourceInstance : resources ){ - buildResources.add(new JsonContainerResourceInstance(resourceInstance)); - } - } - return buildResources; - } - - @Override - public String getResourceInstanceName() { - return resourceInstanceName; - } - - public void setResourceInstanceName(String resourceInstanceName) { - this.resourceInstanceName = resourceInstanceName; - } - - @Override - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - @Override - public String getResourceVersion() { - return resourceVersion; - } - - public void setResourceVersion(String resourceVersion) { - this.resourceVersion = resourceVersion; - } - - @Override - public String getResourceType() { - return resoucreType; - } - - public void setResoucreType(String resoucreType) { - this.resoucreType = resoucreType; - } - - @Override - public String getResourceUUID() { - return resourceUUID; - } - - public void setResourceUUID(String resourceUUID) { - this.resourceUUID = resourceUUID; - } - - @Override - public List getArtifacts() { - List temp = new ArrayList(); - if( artifacts != null ){ - temp.addAll(artifacts); - } - return temp; - } - - public void setArtifacts(List artifacts) { - this.artifacts = artifacts; - } - - public List getArtifactsImpl(){ - return artifacts; - } - - @Override - public String getResourceInvariantUUID() { - return resourceInvariantUUID; - } - - public void setResourceInvariantUUID(String resourceInvariantUUID) { - this.resourceInvariantUUID = resourceInvariantUUID; - } - public String getResourceCustomizationUUID() { - return resourceCustomizationUUID; - } - - public void setResourceCustomizationUUID(String resourceCustomizationUUID) { - this.resourceCustomizationUUID = resourceCustomizationUUID; - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getSubcategory() { - return subcategory; - } - - public void setSubcategory(String subcategory) { - this.subcategory = subcategory; - } -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/NotificationConsumer.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/NotificationConsumer.java deleted file mode 100644 index ccfc6ca..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/NotificationConsumer.java +++ /dev/null @@ -1,181 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl; - -import java.util.ArrayList; -import java.util.List; - -import org.openecomp.sdc.api.consumer.INotificationCallback; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IResourceInstance; -import org.openecomp.sdc.api.results.IDistributionClientResult; -import org.openecomp.sdc.utils.ArtifactTypeEnum; -import org.openecomp.sdc.utils.DistributionActionResultEnum; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.cambria.client.CambriaConsumer; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -class NotificationConsumer implements Runnable { - - private static Logger log = LoggerFactory.getLogger(NotificationConsumer.class.getName()); - - private CambriaConsumer cambriaConsumer; - private INotificationCallback clientCallback; - private List artifactsTypes; - private DistributionClientImpl distributionClient; - - public NotificationConsumer(CambriaConsumer cambriaConsumer, INotificationCallback clientCallback, List artifactsTypes, DistributionClientImpl distributionClient) { - this.cambriaConsumer = cambriaConsumer; - this.clientCallback = clientCallback; - this.artifactsTypes = artifactsTypes; - this.distributionClient = distributionClient; - } - - @Override - public void run() { - - try { - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - long currentTimeMillis = System.currentTimeMillis(); - for (String notificationMsg : cambriaConsumer.fetch()) { - log.debug("received message from topic"); - log.debug("recieved notification from broker: {}", notificationMsg); - - final NotificationDataImpl notificationFromUEB = gson.fromJson(notificationMsg, NotificationDataImpl.class); - NotificationDataImpl notificationForCallback = buildCallbackNotificationLogic(currentTimeMillis, notificationFromUEB); - if (isActivateCallback(notificationForCallback)) { - String stringNotificationForCallback = gson.toJson(notificationForCallback); - log.debug("sending notification to client: {}", stringNotificationForCallback); - clientCallback.activateCallback(notificationForCallback); - } - } - - } catch (Exception e) { - log.error("Error exception occured when fetching with Cambria Client:{}", e.getMessage()); - log.debug("Error exception occured when fetching with Cambria Client:{}", e.getMessage(), e); - } - } - - private boolean isActivateCallback(NotificationDataImpl notificationForCallback) { - boolean hasRelevantArtifactsInResourceInstance = notificationForCallback.getResources() != null && !notificationForCallback.getResources().isEmpty(); - boolean hasRelevantArtifactsInService = notificationForCallback.getServiceArtifacts() != null && !notificationForCallback.getServiceArtifacts().isEmpty(); - - return hasRelevantArtifactsInResourceInstance || hasRelevantArtifactsInService; - } - - protected NotificationDataImpl buildCallbackNotificationLogic(long currentTimeMillis, final NotificationDataImpl notificationFromUEB) { - List relevantResourceInstances = buildResourceInstancesLogic(notificationFromUEB, currentTimeMillis); - List relevantServiceArtifacts = handleRelevantArtifacts(notificationFromUEB, currentTimeMillis, notificationFromUEB.getServiceArtifactsImpl()); - notificationFromUEB.setResources(relevantResourceInstances); - notificationFromUEB.setServiceArtifacts(relevantServiceArtifacts); - return notificationFromUEB; - } - - private List buildResourceInstancesLogic(NotificationDataImpl notificationFromUEB, long currentTimeMillis) { - - List relevantResourceInstances = new ArrayList<>(); - - for (JsonContainerResourceInstance resourceInstance : notificationFromUEB.getResourcesImpl()) { - final List artifactsImplList = resourceInstance.getArtifactsImpl(); - List foundRelevantArtifacts = handleRelevantArtifacts(notificationFromUEB, currentTimeMillis, artifactsImplList); - if (!foundRelevantArtifacts.isEmpty() || distributionClient.getConfiguration().isFilterInEmptyResources()) { - resourceInstance.setArtifacts(foundRelevantArtifacts); - relevantResourceInstances.add(resourceInstance); - } - } - return relevantResourceInstances; - - } - - private List handleRelevantArtifacts(NotificationDataImpl notificationFromUEB, long currentTimeMillis, final List artifactsImplList) { - List relevantArtifacts = new ArrayList<>(); - if (artifactsImplList != null) { - for (ArtifactInfoImpl artifactInfo : artifactsImplList) { - handleRelevantArtifact(notificationFromUEB, currentTimeMillis, artifactsImplList, relevantArtifacts, artifactInfo); - } - } - return relevantArtifacts; - } - - private void handleRelevantArtifact(NotificationDataImpl notificationFromUEB, long currentTimeMillis, final List artifactsImplList, List relevantArtifacts, ArtifactInfoImpl artifactInfo) { - boolean isArtifactRelevant = artifactsTypes.contains(artifactInfo.getArtifactType()); - String artifactType = artifactInfo.getArtifactType(); - if (artifactInfo.getGeneratedFromUUID() != null && !artifactInfo.getGeneratedFromUUID().isEmpty()) { - IArtifactInfo generatedFromArtInfo = findGeneratedFromArtifact(artifactInfo.getGeneratedFromUUID(), artifactsImplList); - if (generatedFromArtInfo != null) - isArtifactRelevant = isArtifactRelevant && artifactsTypes.contains(generatedFromArtInfo.getArtifactType()); - else - isArtifactRelevant = false; - } - if (isArtifactRelevant) { - setRelatedArtifacts(artifactInfo, notificationFromUEB); - if (artifactType.equals(ArtifactTypeEnum.HEAT.name()) || artifactType.equals(ArtifactTypeEnum.HEAT_VOL.name()) || artifactType.equals(ArtifactTypeEnum.HEAT_NET.name())) { - setGeneratedArtifact(artifactsImplList, artifactInfo); - } - relevantArtifacts.add(artifactInfo); - - } - IDistributionClientResult notificationStatus = distributionClient.sendNotificationStatus(currentTimeMillis, notificationFromUEB.getDistributionID(), artifactInfo, isArtifactRelevant); - if (notificationStatus.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) { - log.error("Error failed to send notification status to UEB failed status:{}, error message:{}", notificationStatus.getDistributionActionResult().name(), notificationStatus.getDistributionMessageResult()); - } - } - - private void setRelatedArtifacts(ArtifactInfoImpl artifact, INotificationData notificationData) { - if (artifact.getRelatedArtifactsUUID() != null) { - List relatedArtifacts = new ArrayList<>(); - for (String relatedArtifactUUID : artifact.getRelatedArtifactsUUID()) { - relatedArtifacts.add(notificationData.getArtifactMetadataByUUID(relatedArtifactUUID)); - } - artifact.setRelatedArtifactsInfo(relatedArtifacts); - } - - } - - private void setGeneratedArtifact(final List artifactsImplList, ArtifactInfoImpl artifactInfo) { - IArtifactInfo found = null; - String artifactUUID = artifactInfo.getArtifactUUID(); - for (ArtifactInfoImpl generatedArtifactInfo : artifactsImplList) { - if (generatedArtifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.name()) && artifactUUID.equals(generatedArtifactInfo.getGeneratedFromUUID())) { - found = generatedArtifactInfo; - break; - } - } - - artifactInfo.setGeneratedArtifact(found); - } - - private IArtifactInfo findGeneratedFromArtifact(String getGeneratedFromUUID, List list) { - IArtifactInfo found = null; - for (ArtifactInfoImpl artifactInfo : list) { - if (getGeneratedFromUUID.equals(artifactInfo.getArtifactUUID())) { - found = artifactInfo; - break; - } - } - return found; - } - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/NotificationDataImpl.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/NotificationDataImpl.java deleted file mode 100644 index c60e2fd..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/NotificationDataImpl.java +++ /dev/null @@ -1,179 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl; - -import java.util.ArrayList; -import java.util.List; - -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IResourceInstance; - - -class NotificationDataImpl implements INotificationData { - - private String distributionID; - private String serviceName; - private String serviceVersion; - private String serviceUUID; - private String serviceDescription; - private String serviceInvariantUUID; - private List resources; - private List serviceArtifacts; - private String workloadContext; - - @Override - public String getDistributionID() { - return distributionID; - } - - @Override - public String getServiceName() { - return serviceName; - } - - @Override - public String getServiceVersion() { - return serviceVersion; - } - - @Override - public String getServiceUUID() { - return serviceUUID; - } - - public void setDistributionID(String distributionID) { - this.distributionID = distributionID; - } - - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } - - public void setServiceVersion(String serviceVersion) { - this.serviceVersion = serviceVersion; - } - - public void setServiceUUID(String serviceUUID) { - this.serviceUUID = serviceUUID; - } - - - - public String getServiceDescription() { - return serviceDescription; - } - - public void setServiceDescription(String serviceDescription) { - this.serviceDescription = serviceDescription; - } - - @Override - public String getWorkloadContext() { - return workloadContext; - } - - @Override - public void setWorkloadContext(String workloadContext) { - this.workloadContext = workloadContext; - } - - @Override - public String toString() { - return "NotificationDataImpl [distributionID=" + distributionID + ", serviceName=" + serviceName - + ", serviceVersion=" + serviceVersion + ", serviceUUID=" + serviceUUID + ", serviceDescription=" - + serviceDescription + ", serviceInvariantUUID=" + serviceInvariantUUID + ", resources=" + resources - + ", serviceArtifacts=" + serviceArtifacts + ", workloadContext=" + workloadContext + "]"; - } - - @Override - public List getResources() { - List ret = new ArrayList(); - if( resources != null ){ - ret.addAll(resources); - } - return ret; - } - - public void setResources(List resources){ - this.resources = JsonContainerResourceInstance.convertToJsonContainer(resources); - } - - public List getResourcesImpl(){ - return resources; - } - - List getServiceArtifactsImpl(){ - return serviceArtifacts; - } - - @Override - public List getServiceArtifacts() { - - List temp = new ArrayList(); - if( serviceArtifacts != null ){ - temp.addAll(serviceArtifacts); - } - return temp; - } - - void setServiceArtifacts(List relevantServiceArtifacts) { - serviceArtifacts = relevantServiceArtifacts; - - } - - @Override - public String getServiceInvariantUUID() { - return serviceInvariantUUID; - } - - - public void setServiceInvariantUUID(String serviceInvariantUUID) { - this.serviceInvariantUUID = serviceInvariantUUID; - } - @Override - public IArtifactInfo getArtifactMetadataByUUID(String artifactUUID){ - IArtifactInfo ret = findArtifactInfoByUUID(artifactUUID, serviceArtifacts); - if( ret == null && resources != null ){ - for( JsonContainerResourceInstance currResourceInstance : resources ){ - ret = findArtifactInfoByUUID(artifactUUID, currResourceInstance.getArtifactsImpl()); - if( ret != null ){ - break; - } - } - } - return ret; - - } - - private IArtifactInfo findArtifactInfoByUUID(String artifactUUID, List listToCheck) { - IArtifactInfo ret = null; - if( listToCheck != null ){ - for(IArtifactInfo curr: listToCheck ){ - if(curr.getArtifactUUID().equals(artifactUUID) ){ - ret = curr; - break; - } - } - } - return ret; - } -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/StatusConsumer.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/StatusConsumer.java deleted file mode 100644 index 34d85ec..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/StatusConsumer.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl; - -import org.openecomp.sdc.api.consumer.IStatusCallback; -import org.openecomp.sdc.api.notification.IStatusData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.cambria.client.CambriaConsumer; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -class StatusConsumer implements Runnable { - - private static Logger log = LoggerFactory.getLogger(StatusConsumer.class.getName()); - - private CambriaConsumer cambriaConsumer; - private IStatusCallback clientCallback; - - public StatusConsumer(CambriaConsumer cambriaConsumer, IStatusCallback clientCallback) { - this.cambriaConsumer = cambriaConsumer; - this.clientCallback = clientCallback; - } - - @Override - public void run() { - - try { - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - for (String statusMsg : cambriaConsumer.fetch()) { - log.debug("received message from topic"); - log.debug("recieved notification from broker: {}", statusMsg); - IStatusData statusData = gson.fromJson(statusMsg, StatusDataImpl.class); - clientCallback.activateCallback(statusData); - - - } - - } catch (Exception e) { - log.error("Error exception occured when fetching with Cambria Client:{}", e.getMessage()); - log.debug("Error exception occured when fetching with Cambria Client:{}", e.getMessage(), e); - } - } - - - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/StatusDataImpl.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/StatusDataImpl.java deleted file mode 100644 index 119a7f3..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/StatusDataImpl.java +++ /dev/null @@ -1,95 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl; - -import org.openecomp.sdc.api.notification.IStatusData; -import org.openecomp.sdc.utils.DistributionStatusEnum; - -public class StatusDataImpl implements IStatusData{ - - String distributionID; - String consumerID; - long timestamp; - String artifactURL; - DistributionStatusEnum status; - String componentName; - String errorReason; - - @Override - public String getDistributionID() { - return distributionID; - } - - public void setDistributionID(String distributionId) { - this.distributionID = distributionId; - } - @Override - public String getConsumerID() { - return consumerID; - } - - public void setConsumerID(String consumerId) { - this.consumerID = consumerId; - } - @Override - public Long getTimestamp() { - return timestamp; - } - - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } - @Override - public String getArtifactURL() { - return artifactURL; - } - - public void setArtifactURL(String artifactURL) { - this.artifactURL = artifactURL; - } - @Override - public DistributionStatusEnum getStatus() { - return status; - } - - public void setStatus(DistributionStatusEnum status) { - this.status = status; - } - - - @Override - public String toString() { - return "StatusDataImpl [distributionId=" + distributionID + ", consumerId=" + consumerID + ", timestamp=" + timestamp + ", artifactURL=" + artifactURL + ", status=" + status +", errorReason=" + errorReason+ "]"; - } - @Override - public String getComponentName() { - return componentName; - } - - @Override - public String getErrorReason() { - return errorReason; - } - - - - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/VfModuleMetadata.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/VfModuleMetadata.java deleted file mode 100644 index 3932253..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/VfModuleMetadata.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl; - -import java.util.List; - -import org.openecomp.sdc.api.notification.IVfModuleMetadata; - -final class VfModuleMetadata implements IVfModuleMetadata { - private VfModuleMetadata(){ - //This Class is only built by parsing Json - } - - private String vfModuleModelName; - private String vfModuleModelInvariantUUID; - private String vfModuleModelVersion; - private String vfModuleModelUUID; - private String vfModuleModelDescription; - private boolean isBase; - private List artifacts; - - public String getVfModuleModelName() { - return vfModuleModelName; - } - public String getVfModuleModelInvariantUUID() { - return vfModuleModelInvariantUUID; - } - public String getVfModuleModelVersion() { - return vfModuleModelVersion; - } - public String getVfModuleModelUUID() { - return vfModuleModelUUID; - } - public String getVfModuleModelDescription() { - return vfModuleModelDescription; - } - public boolean isBase() { - return isBase; - } - public List getArtifacts() { - return artifacts; - } -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/mock/DistributionClientDownloadResultStubImpl.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/mock/DistributionClientDownloadResultStubImpl.java deleted file mode 100644 index aff0d0e..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/mock/DistributionClientDownloadResultStubImpl.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl.mock; - -import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; - -/** Mock Implementation */ -public class DistributionClientDownloadResultStubImpl extends DistributionClientResultStubImpl implements IDistributionClientDownloadResult { - - @Override - public byte[] getArtifactPayload() { - String mockPayload = "heat_template_version: 2013-05-23\r\n" + - "\r\n" + - "description: >\r\n" + - " HOT template that creates one COR network (direct).\r\n" + - "\r\n" + - "parameters:\r\n" + - " cor_direct_net_name:\r\n" + - " type: string\r\n" + - " description: Name of COR direct network\r\n" + - " cor_direct_net_cidr:\r\n" + - " type: string\r\n" + - " description: Direct network address (CIDR notation)\r\n" + - " cor_direct_net_gateway:\r\n" + - " type: string\r\n" + - " description: Direct network gateway address\r\n" + - " cor_direct_net_RT:\r\n" + - " type: string\r\n" + - " description: Direct network route-target (RT)\r\n" + - "\r\n" + - "resources:\r\n" + - " cor_direct_net:\r\n" + - " type: OS::Contrail::VirtualNetwork\r\n" + - " properties:\r\n" + - " name: { get_param: cor_direct_net_name }\r\n" + - " route_targets: [ get_param: cor_direct_net_RT ]\r\n" + - "\r\n" + - " cor_direct_ip_subnet:\r\n" + - " type: OS::Neutron::Subnet\r\n" + - " properties:\r\n" + - " network_id: { get_resource: cor_direct_net }\r\n" + - " cidr: {get_param: cor_direct_net_cidr}\r\n" + - " gateway_ip: { get_param: cor_direct_net_gateway }\r\n"; - - return mockPayload.getBytes(); - } - - @Override - public String getArtifactName() { - // TODO Auto-generated method stub - return "MackArtifactName"; - } - - @Override - public String getArtifactFilename() { - // TODO Auto-generated method stub - return "MackArtifactName"; - } - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/mock/DistributionClientResultStubImpl.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/mock/DistributionClientResultStubImpl.java deleted file mode 100644 index 13d64a4..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/mock/DistributionClientResultStubImpl.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl.mock; - -import org.openecomp.sdc.api.results.IDistributionClientResult; -import org.openecomp.sdc.utils.DistributionActionResultEnum; -/** Mock Implementation */ -public class DistributionClientResultStubImpl implements IDistributionClientResult { - @Override - public DistributionActionResultEnum getDistributionActionResult() { - return DistributionActionResultEnum.SUCCESS; - } - - @Override - public String getDistributionMessageResult() { - return "Stub Result, method not implemented!"; - } - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/mock/DistributionClientStubImpl.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/mock/DistributionClientStubImpl.java deleted file mode 100644 index 1730290..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/impl/mock/DistributionClientStubImpl.java +++ /dev/null @@ -1,125 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl.mock; - -import java.util.List; - -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.consumer.*; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.IVfModuleMetadata; -import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; -import org.openecomp.sdc.api.results.IDistributionClientResult; -/** Mock Implementation */ -public class DistributionClientStubImpl implements IDistributionClient{ - - - public IDistributionClientResult updateConfiguration(IConfiguration newConf) { - return new DistributionClientResultStubImpl(); - } - - public IDistributionClientResult start() { - return new DistributionClientResultStubImpl(); - } - - public IDistributionClientResult stop() { - return new DistributionClientResultStubImpl(); - } - - public IDistributionClientResult sendDownloadStatus( IDistributionStatusMessage statusMessage) { - return new DistributionClientResultStubImpl(); - } - - public IDistributionClientResult sendDeploymentStatus( IDistributionStatusMessage statusMessage) { - return new DistributionClientResultStubImpl(); - } - - @Override - public IDistributionClientDownloadResult download(IArtifactInfo artifactInfo) { - return new DistributionClientDownloadResultStubImpl(); - } - - @Override - public IDistributionClientResult init(IConfiguration conf, INotificationCallback callback) { - return new DistributionClientResultStubImpl(); - } - - @Override - public IDistributionClientResult init(IConfiguration conf, INotificationCallback notificationCallback, - IStatusCallback statusCallback) { - return new DistributionClientResultStubImpl(); - } - - @Override - public IConfiguration getConfiguration() { - // TODO Auto-generated method stub - return null; - } - - @Override - public IDistributionClientResult sendDownloadStatus( - IDistributionStatusMessage statusMessage, String errorReason) { - // TODO Auto-generated method stub - return null; - } - - @Override - public IDistributionClientResult sendDeploymentStatus( - IDistributionStatusMessage statusMessage, String errorReason) { - // TODO Auto-generated method stub - return null; - } - - @Override - public IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage) { - return null; - } - - @Override - public IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage) { - return null; - } - - @Override - public List decodeVfModuleArtifact(byte[] artifactPayload) { - // TODO Auto-generated method stub - return null; - } - - @Override - public IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage, - String errorReason) { - // TODO Auto-generated method stub - return null; - } - - @Override - public IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage, String errorReason) { - // TODO Auto-generated method stub - return null; - } - - - - - - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/ArtifactTypeEnum.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/ArtifactTypeEnum.java deleted file mode 100644 index ca5339f..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/ArtifactTypeEnum.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.utils; - -public enum ArtifactTypeEnum { - HEAT, - HEAT_VOL, - HEAT_NET, - MURANO_PKG, - HEAT_ENV, - YANG_XML, - OTHER, - VF_LICENSE, - VENDOR_LICENSE, - MODEL_INVENTORY_PROFILE, - MODEL_QUERY_SPEC, - APPC_CONFIG, - VNF_CATALOG, - HEAT_NESTED, - HEAT_ARTIFACT, - VF_MODULES_METADATA, - //DCAE Artifacts - DCAE_TOSCA, DCAE_JSON, DCAE_POLICY, DCAE_DOC, - DCAE_EVENT, DCAE_INVENTORY_TOSCA, DCAE_INVENTORY_JSON, - DCAE_INVENTORY_POLICY, DCAE_INVENTORY_DOC, - DCAE_INVENTORY_BLUEPRINT, DCAE_INVENTORY_EVENT; - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/DistributionActionResultEnum.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/DistributionActionResultEnum.java deleted file mode 100644 index 6ac4d35..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/DistributionActionResultEnum.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.utils; - -public enum DistributionActionResultEnum { - SUCCESS, - FAIL, - GENERAL_ERROR, - BAD_REQUEST, - DISTRIBUTION_CLIENT_NOT_INITIALIZED, - DISTRIBUTION_CLIENT_IS_TERMINATED, - DISTRIBUTION_CLIENT_ALREADY_INITIALIZED, - DISTRIBUTION_CLIENT_ALREADY_STARTED, - - DATA_INTEGRITY_PROBLEM, - ARTIFACT_NOT_FOUND, - - CONFIGURATION_IS_MISSING, - CONF_MISSING_USERNAME, - CONF_MISSING_PASSWORD, - CONF_MISSING_ASDC_FQDN, - CONF_MISSING_ARTIFACT_TYPES, - CONF_CONTAINS_INVALID_ARTIFACT_TYPES, - CONF_MISSING_CONSUMER_ID, - CONF_MISSING_ENVIRONMENT_NAME, - CONF_MISSING_CONSUMER_GROUP, - CONF_INVALID_ASDC_FQDN, - CONF_INVALID_CONSUME_PRODUCE_STATUS_TOPIC_FALG, - CONF_MISSING_MSG_BUS_ADDRESS, - CONF_INVALID_MSG_BUS_ADDRESS, - ASDC_AUTHENTICATION_FAILED, - ASDC_AUTHORIZATION_FAILED, - ASDC_NOT_FOUND, - ASDC_SERVER_PROBLEM, - ASDC_CONNECTION_FAILED, - ASDC_SERVER_TIMEOUT, - - CAMBRIA_INIT_FAILED, - UEB_KEYS_CREATION_FAILED -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/DistributionClientConstants.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/DistributionClientConstants.java deleted file mode 100644 index 37b8ae3..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/DistributionClientConstants.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.utils; - -import java.util.regex.Pattern; - -/** - * Constants Used By Distribution Client - * @author mshitrit - * - */ -public final class DistributionClientConstants { - public static final String CLIENT_DESCRIPTION = "ASDC Distribution Client Key for %s"; - public static final Pattern FQDN_PATTERN = Pattern.compile("^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*(:[0-9]{2,4})*$", Pattern.CASE_INSENSITIVE); - public static final String EMAIL = ""; - public static final int MIN_POLLING_INTERVAL_SEC = 15; - public static final int POOL_SIZE = 10; - public static final int POLLING_TIMEOUT_SEC = 15; - - public static final String HEADER_INSTANCE_ID = "X-ECOMP-InstanceID"; - public static final String HEADER_REQUEST_ID = "X-ECOMP-RequestID"; - public static final String APPLICATION_JSON = "application/json"; - public static final String HEADER_CONTENT_TYPE = "Content-Type"; - - private DistributionClientConstants(){ throw new UnsupportedOperationException();} -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/DistributionStatusEnum.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/DistributionStatusEnum.java deleted file mode 100644 index 13fcfcc..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/DistributionStatusEnum.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.utils; - -public enum DistributionStatusEnum { - /**Can be sent when ONAP component successfully downloaded the specific artifact*/ - DOWNLOAD_OK, - - /**Can be sent when ONAP component failed to download the specific artifact (corrupted file)*/ - DOWNLOAD_ERROR, - - /**Can be sent only if the repeated distribution notification event is sent when the ONAP component already downloaded the artifact , but still not stored it in the local repository .*/ - ALREADY_DOWNLOADED, - - /**Can be sent when ONAP component successfully deployed the specific artifact in the local repository*/ - DEPLOY_OK, - - /**Can be sent when ONAP component failed to store the downloaded artifact in the local repository*/ - DEPLOY_ERROR, - - /**Sent when the repeated distribution notification event is sent for already stored in the local repository service artifact ( artifact's version and checksum match the one stored in the local repository)*/ - ALREADY_DEPLOYED, - /** - * ONAP component is requested to publish this status once component successfully complete downloading and storing all the data it needs from the service. - */ - COMPONENT_DONE_OK, - - /**ONAP component is requested to publish this status when component failed to download or failed to store one or more of the mandatory information it requires from the service model. - - It is recommended to populate the errorReason field with appropriate description of the error -*/ - COMPONENT_DONE_ERROR, - /** The DISTRIBUTION_COMPLETE_OK/ERROR status indicating the overall ONAP components status of retrieving and storing the information. -*/ - DISTRIBUTION_COMPLETE_OK, - - DISTRIBUTION_COMPLETE_ERROR -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/GeneralUtils.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/GeneralUtils.java deleted file mode 100644 index 0f76574..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/GeneralUtils.java +++ /dev/null @@ -1,92 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.utils; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Pattern; - -import org.apache.commons.codec.binary.Base64; -import org.openecomp.sdc.api.results.IDistributionClientResult; -import org.openecomp.sdc.impl.DistributionClientResultImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import fj.data.Either; - -public class GeneralUtils { - private static final Logger log = LoggerFactory.getLogger(GeneralUtils.class.getName()); - public static String calculateMD5 (String data){ - String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data); - // encode base-64 result - byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes()); - String encodeBase64Str = new String(encodeBase64); - return encodeBase64Str; - - } - - public static String calculateMD5(byte[] decodedPayload) { - String decodedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(decodedPayload); - byte[] encodeMd5 = Base64.encodeBase64(decodedMd5.getBytes()); - return new String(encodeMd5); - } - - public static boolean isBase64Encoded(String str){ - boolean isEncoded = false; - try - { - // If no exception is caught, then it is possibly a base64 encoded string - byte[] data = Base64.decodeBase64(str); - // checks if the string was properly padded to the - isEncoded= ((str.length() % 4 == 0) && (Pattern.matches("\\A[a-zA-Z0-9/+]+={1,2}\\z", str))); - - } - catch (Exception e) - { - // If exception is caught, then it is not a base64 encoded string - isEncoded= false; - } - return isEncoded; - } - - - public static Either, IDistributionClientResult> convertToValidHostName(List msgBusAddresses) { - List uebLocalHostsNames = new ArrayList<>(); - for(String name : msgBusAddresses){ - try { - uebLocalHostsNames.add(InetAddress.getByName(name).getHostName()); - } catch (UnknownHostException e) { - log.debug("UnknownHost: {}", e.getMessage(), e); - } - } - Either, IDistributionClientResult> response; - if( uebLocalHostsNames.isEmpty() ){ - response = Either.right(new DistributionClientResultImpl(DistributionActionResultEnum.CONF_INVALID_MSG_BUS_ADDRESS, "configuration is invalid: " + DistributionActionResultEnum.CONF_INVALID_MSG_BUS_ADDRESS.name())); - - } - else{ - response = Either.left(uebLocalHostsNames); - } - return response; - } -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/Pair.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/Pair.java deleted file mode 100644 index eca644a..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/Pair.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.utils; - -public final class Pair { - private final F first; - private final S second; - - public Pair(F first, S second){ - this.first = first; - this.second = second; - } - - public F getFirst() { - return first; - } - - public S getSecond() { - return second; - } -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/Wrapper.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/Wrapper.java deleted file mode 100644 index 047ea86..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/Wrapper.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.utils; -/** - * Very Basic Wrapper class. - * @author mshitrit - * - * @param - */ -public class Wrapper{ - private T innerElement; - public Wrapper(T innerElement){ - this.innerElement = innerElement; - } - public Wrapper(){ - this.innerElement = null; - } - public T getInnerElement() { - return innerElement; - } - public void setInnerElement(T innerElement) { - this.innerElement = innerElement; - } - public boolean isEmpty(){ - return innerElement == null; - } -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/YamlToObjectConverter.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/YamlToObjectConverter.java deleted file mode 100644 index 50feb6c..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/YamlToObjectConverter.java +++ /dev/null @@ -1,155 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.utils; - -import java.beans.IntrospectionException; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.HashMap; - -import org.openecomp.sdc.utils.heat.HeatConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.yaml.snakeyaml.TypeDescription; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.introspector.BeanAccess; -import org.yaml.snakeyaml.introspector.Property; -import org.yaml.snakeyaml.introspector.PropertyUtils; - -public class YamlToObjectConverter { - - private static Logger log = LoggerFactory - .getLogger(YamlToObjectConverter.class.getName()); - - private static HashMap yamls = new HashMap(); - - private static Yaml defaultYaml = new Yaml(); - - static { - - org.yaml.snakeyaml.constructor.Constructor heatConstructor = new org.yaml.snakeyaml.constructor.Constructor(HeatConfiguration.class); - TypeDescription heatDescription = new TypeDescription(HeatConfiguration.class); - //heatDescription.putListPropertyType("parameters", HeatParameterConfiguration.class); - heatConstructor.addTypeDescription(heatDescription); - PropertyUtils propertyUtils = new PropertyUtils() { - @Override - //This is in order to workaround "default" field in HeatParameterEntry, since default is Java keyword - public Property getProperty(Class type, String name, BeanAccess bAccess) - throws IntrospectionException { - name = name.substring(0, 1).toLowerCase() + name.substring(1); - return super.getProperty(type, name, bAccess); - } - - }; - //Skip properties which are not found - we only are interested in "parameters" - propertyUtils.setSkipMissingProperties(true); - heatConstructor.setPropertyUtils(propertyUtils); - - Yaml yaml = new Yaml(heatConstructor); - - yamls.put(HeatConfiguration.class.getName(), yaml); - - } - - private static Yaml getYamlByClassName(Class className) { - - Yaml yaml = yamls.get(className.getName()); - if (yaml == null) { - yaml = defaultYaml; - } - - return yaml; - } - - public T convert(String dirPath, Class className, - String configFileName) { - - T config = null; - - try { - - String fullFileName = dirPath + File.separator + configFileName; - - config = convert(fullFileName, className); - - } catch (Exception e) { - log.error("Failed to convert yaml file " + configFileName - + " to object.", e); - } - - return config; - } - - public T convert(String fullFileName, Class className) { - - T config = null; - - Yaml yaml = getYamlByClassName(className); - - InputStream in = null; - try { - - File f = new File(fullFileName); - if (false == f.exists()) { - log.warn("The file " + fullFileName - + " cannot be found. Ignore reading configuration."); - return null; - } - in = Files.newInputStream(Paths.get(fullFileName)); - - config = yaml.loadAs(in, className); - - // System.out.println(config.toString()); - } catch (Exception e) { - log.error("Failed to convert yaml file " + fullFileName - + " to object.", e); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - return config; - } - - public T convertFromString(String yamlContents, Class className) { - - T config = null; - - Yaml yaml = getYamlByClassName(className); - - try { - config = yaml.loadAs(yamlContents, className); - } catch (Exception e){ - log.error("Failed to convert YAML {} to object." , yamlContents, e); - } - - return config; - } -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/heat/HeatConfiguration.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/heat/HeatConfiguration.java deleted file mode 100644 index 6cd2de0..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/heat/HeatConfiguration.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.utils.heat; - -import java.util.Map; - -public class HeatConfiguration { - - //All the rest of heat file is not needed for now... - Map parameters; - - - public Map getParameters() { - return parameters; - } - - - public void setParameters(Map parameters) { - this.parameters = parameters; - } - - - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/heat/HeatParameter.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/heat/HeatParameter.java deleted file mode 100644 index 954152d..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/heat/HeatParameter.java +++ /dev/null @@ -1,207 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.utils.heat; - -import java.util.ArrayList; -import java.util.List; - -public class HeatParameter{ - - String type; - String label; - String description; - //This is in order to workaround "default" field in HeatParameterEntry, since default is Java keyword - //YAML constructor will lowercase it during parsing - String Default; - String hidden = "false";//Default value according to OpenStack spec - List constraints; - - - - public String getHidden() { - return hidden; - } - public void setHidden(String hidden) { - this.hidden = hidden; - } - - public List getConstraints() { - return constraints; - } - public void setConstraints(List constraints) { - this.constraints = constraints; - } - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - public String getLabel() { - return label; - } - public void setLabel(String label) { - this.label = label; - } - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - public String getDefault() { - return Default; - } - public void setDefault(String default1) { - Default = default1; - } - - - - // Getting specific constraints - /** - * Get the first "length" constraint from HEAT parameter. - * No additional "length" constraint is searched for. - * - * @return first "length" constraint found for this parameter, - * or null if no such constraint exists. - */ - public HeatParameterConstraint getLengthConstraint(){ - HeatParameterConstraint res = null; - if (constraints != null){ - for (HeatParameterConstraint entry : constraints){ - if (entry.getLength() != null){ - res = entry; - break; - } - } - } - return res; - } - - - /** - * Get the first "range" constraint from HEAT parameter. - * No additional "range" constraint is searched for. - * - * @return first "range" constraint found for this parameter, - * or null if no such constraint exists. - */ - public HeatParameterConstraint getRangeConstraint(){ - HeatParameterConstraint res = null; - if (constraints != null){ - for (HeatParameterConstraint entry : constraints){ - if (entry.getRange() != null){ - res = entry; - break; - } - } - } - return res; - } - - /** - * Get the first "allowed_values" constraint from HEAT parameter. - * No additional "allowed_values" constraint is searched for. - * - * @return first "allowed_values" constraint found for this parameter, - * or null if no such constraint exists. - */ - public HeatParameterConstraint getAllowedValuesConstraint(){ - HeatParameterConstraint res = null; - if (constraints != null){ - for (HeatParameterConstraint entry : constraints){ - if (entry.getAllowed_values() != null){ - res = entry; - break; - } - } - } - return res; - } - - /** - * Get the "allowed_pattern" constraint list from HEAT parameter. - * - * @return "allowed_pattern" constraint list found for this parameter, - * or null if no such constraint exists. - */ - public List getAllowedPatternConstraint(){ - List res = null; - if (constraints != null){ - for (HeatParameterConstraint entry : constraints){ - if (entry.getAllowed_pattern() != null){ - if (res == null){ - res = new ArrayList<>(); - } - res.add(entry); - } - } - } - return res; - } - - /** - * Get the "custom_constraint" constraint list from HEAT parameter. - * - * @return "custom_constraint" constraint list found for this parameter, - * or null if no such constraint exists. - */ - public List getCustomConstraintConstraint(){ - List res = null; - if (constraints != null){ - for (HeatParameterConstraint entry : constraints){ - if (entry.getCustom_constraint() != null){ - if (res == null){ - res = new ArrayList<>(); - } - res.add(entry); - } - } - } - return res; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - if (type != null){ - sb.append("type:"+type+", "); - } - if (label != null){ - sb.append("label:"+label+", "); - } - if (Default != null){ - sb.append("default:"+Default+", "); - } - if (hidden != null){ - sb.append("hidden:"+hidden+", "); - } - if (constraints != null){ - sb.append("constraints:"+constraints+", "); - } - if (description != null){ - sb.append("description:"+description); - } - return sb.toString(); - } - -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/heat/HeatParameterConstraint.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/heat/HeatParameterConstraint.java deleted file mode 100644 index b89ad48..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/heat/HeatParameterConstraint.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.utils.heat; - -import java.util.List; -import java.util.Map; - -public class HeatParameterConstraint { - - Map length; - Map range; - List allowed_values; - String allowed_pattern; - String custom_constraint; - String description; - - - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - public Map getLength() { - return length; - } - public void setLength(Map length) { - this.length = length; - } - public Map getRange() { - return range; - } - public void setRange(Map range) { - this.range = range; - } - public List getAllowed_values() { - return allowed_values; - } - public void setAllowed_values(List allowed_values) { - this.allowed_values = allowed_values; - } - public String getAllowed_pattern() { - return allowed_pattern; - } - public void setAllowed_pattern(String allowed_pattern) { - this.allowed_pattern = allowed_pattern; - } - public String getCustom_constraint() { - return custom_constraint; - } - public void setCustom_constraint(String custom_constraint) { - this.custom_constraint = custom_constraint; - } - - @Override - public String toString() { - String constraintTypeValue = ""; - String descriptionStr = ""; - if (length != null){ - constraintTypeValue = "length:"+length; - } else if (range != null){ - constraintTypeValue = "range:"+range; - } else if (allowed_values != null){ - constraintTypeValue = "allowed_values:"+allowed_values; - } else if (allowed_pattern != null){ - constraintTypeValue = "allowed_pattern:"+allowed_pattern; - } else if (custom_constraint != null){ - constraintTypeValue = "custom_constraint:"+custom_constraint; - } - if (description != null){ - descriptionStr = "description:"+description; - } - return new StringBuilder().append(constraintTypeValue).append(", ").append(descriptionStr).toString(); - } -} diff --git a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/heat/HeatParser.java b/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/heat/HeatParser.java deleted file mode 100644 index 5aa4968..0000000 --- a/sdc-distribution-client/src/main/java/org/openecomp/sdc/utils/heat/HeatParser.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.utils.heat; - -import java.util.Map; - -import org.openecomp.sdc.utils.YamlToObjectConverter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class HeatParser { - - private static Logger log = LoggerFactory.getLogger(HeatParser.class.getName()); - - - /** - * Parses and returns the contents of the "parameters" section of YAML-formatted HEAT template. - * - * @param heatFileContents - the string contents of HEAT template - * @return map of parameter name to HeatParameter object. - * For the following YAML snippet: - * parameters: - * image_name_1: - * type: string - * label: Image Name - * description: SCOIMAGE Specify an image name for instance1 - * default: cirros-0.3.1-x86_64 - * - * the map with one entry will be returned, the key will be "image_name_1". - * For a HeatParameter object, getConstraints() returns the list of all constraints, - * regardless of constraint type. - * For that reason, for each constraint type a sugaring function were added on the HeatParameter type, - * for example getLengthConstraint(). A correct way to fetch the "length" constraint values map would be - * parameter.getLengthConstraint().getLength(). Same logic was implemented for all other constraint types. - * - * In case of parse error, null will be returned. - * - */ - public Map getHeatParameters(String heatFileContents){ - log.debug("Start of extracting HEAT parameters from file, file contents: {}", heatFileContents); - Map heatParameters = null; - YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); - HeatConfiguration heatConfiguration = yamlToObjectConverter.convertFromString(heatFileContents, HeatConfiguration.class); - if (heatConfiguration != null){ - heatParameters = heatConfiguration.getParameters(); - } else { - log.error("Couldn't parse HEAT template."); - } - if (heatParameters != null && heatParameters.size() > 0){ - System.out.println("Found HEAT parameters: "+heatParameters.toString()); - log.debug("Found HEAT parameters: {}", heatParameters.toString()); - } else { - log.warn("HEAT template parameters section wasn't found or is empty."); - } - return heatParameters; - } -} diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/http/SdcConnectorClientTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/http/SdcConnectorClientTest.java new file mode 100644 index 0000000..7b46f33 --- /dev/null +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/http/SdcConnectorClientTest.java @@ -0,0 +1,119 @@ +package org.onap.sdc.http; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.onap.sdc.impl.DistributionClientResultImpl; +import org.onap.sdc.api.asdc.RegistrationRequest; +import org.onap.sdc.api.consumer.IConfiguration; +import org.onap.sdc.utils.Pair; + +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import fj.data.Either; + +public class SdcConnectorClientTest { + private Gson gson = new GsonBuilder().create(); + private static final String MOCK_ENV = "MockEnv"; + private static final String MOCK_API_KEY = "MockApikey"; + private static HttpAsdcClient httpClient = Mockito.mock(HttpAsdcClient.class); + private static IConfiguration configuration = Mockito.mock(IConfiguration.class); + private static ApiCredential apiCredential = Mockito.mock(ApiCredential.class); + private static HttpAsdcResponse httpAsdcResponse = Mockito.mock(HttpAsdcResponse.class); + @SuppressWarnings("unchecked") + private static Either mockResponse = Mockito + .mock(Either.class); + private static Map mockHeaders = new HashMap<>(); + Pair mockPair = new Pair<>(httpAsdcResponse, null); + private HttpEntity lastHttpEntity = null; + + private static SdcConnectorClient asdcClient = Mockito.spy(new SdcConnectorClient()); + + @BeforeClass + public static void beforeClass() { + asdcClient.setConfiguration(configuration); + asdcClient.setHttpClient(httpClient); + when(apiCredential.getApiKey()).thenReturn(MOCK_API_KEY); + when(httpAsdcResponse.getStatus()).thenReturn(HttpStatus.SC_OK); + + doReturn(mockHeaders).when(asdcClient).addHeadersToHttpRequest(Mockito.anyString()); + doReturn(mockResponse).when(asdcClient).parseRegistrationResponse(httpAsdcResponse); + } + + @Before + public void beforeMethod() { + Mockito.reset(configuration, httpClient); + lastHttpEntity = null; + when(configuration.getEnvironmentName()).thenReturn(MOCK_ENV); + + + doAnswer(new Answer>() { + @Override + public Pair answer(InvocationOnMock invocation) throws Throwable { + lastHttpEntity = invocation.getArgumentAt(1, HttpEntity.class); + return mockPair; + } + }).when(httpClient).postRequest(Mockito.eq(AsdcUrls.POST_FOR_TOPIC_REGISTRATION), Mockito.any(HttpEntity.class), + Mockito.eq(mockHeaders), Mockito.eq(false)); + } + + @Test + public void testConsumeProduceStatusTopicFalse() throws UnsupportedOperationException, IOException { + + testConsumeProduceStatusTopic(false); + + } + + @Test + public void testConsumeProduceStatusTopicTrue() throws UnsupportedOperationException, IOException { + + testConsumeProduceStatusTopic(true); + + } + + private void testConsumeProduceStatusTopic(final boolean isConsumeProduceStatusFlag) throws IOException { + when(configuration.isConsumeProduceStatusTopic()).thenReturn(isConsumeProduceStatusFlag); + asdcClient.registerAsdcTopics(apiCredential); + verify(httpClient, times(1)).postRequest(Mockito.eq(AsdcUrls.POST_FOR_TOPIC_REGISTRATION), + Mockito.any(HttpEntity.class), Mockito.eq(mockHeaders), Mockito.eq(false)); + assertNotNull(lastHttpEntity); + RegistrationRequest actualRegRequest = gson.fromJson(IOUtils.toString(lastHttpEntity.getContent(), StandardCharsets.UTF_8), RegistrationRequest.class); + RegistrationRequest expectedRegRequest = gson.fromJson(excpectedStringBody(isConsumeProduceStatusFlag), RegistrationRequest.class); + + assertTrue(actualRegRequest.getApiPublicKey().equals(expectedRegRequest.getApiPublicKey())); + assertTrue(actualRegRequest.getDistrEnvName().equals(expectedRegRequest.getDistrEnvName())); + assertTrue(actualRegRequest.getIsConsumerToSdcDistrStatusTopic() + .equals(expectedRegRequest.getIsConsumerToSdcDistrStatusTopic())); + } + + + + private String excpectedStringBody(boolean isConsumeProduceStatusTopic) { + String stringBodyTemplate = "{\r\n" + " \"apiPublicKey\": \"MockApikey\",\r\n" + + " \"distrEnvName\": \"MockEnv\",\r\n" + " \"isConsumerToSdcDistrStatusTopic\": %s\r\n" + "}"; + return String.format(stringBodyTemplate, isConsumeProduceStatusTopic); + + } +} diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionClientDownloadResultTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionClientDownloadResultTest.java new file mode 100644 index 0000000..d12d828 --- /dev/null +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionClientDownloadResultTest.java @@ -0,0 +1,55 @@ +package org.onap.sdc.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.sdc.utils.DistributionActionResultEnum; + + +public class DistributionClientDownloadResultTest { + + public static DistributionClientDownloadResultImpl distributionClientDownloadResult; + + @BeforeClass + public static void init(){ + distributionClientDownloadResult = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS, ""); + } + + @Test + public void testNonHeaderFilename(){ + distributionClientDownloadResult.setArtifactName("service-BkPerformanceSrvs-csar.csar"); + assertEquals("service-BkPerformanceSrvs-csar.csar", distributionClientDownloadResult.getArtifactFilename()); + } + + @Test + public void testNullFilename(){ + distributionClientDownloadResult.setArtifactName(null); + assertNull(distributionClientDownloadResult.getArtifactFilename()); + } + + @Test + public void testFilenameFromHeaderNoSpace(){ + distributionClientDownloadResult.setArtifactName("attachment;filename=\"service-BkPerformanceSrvs-csar.csar\""); + assertEquals("service-BkPerformanceSrvs-csar.csar", distributionClientDownloadResult.getArtifactFilename()); + } + + @Test + public void testFilenameFromHeaderOneSpace(){ + distributionClientDownloadResult.setArtifactName("attachment; filename=\"service-BkPerformanceSrvs-csar.csar\""); + assertEquals("service-BkPerformanceSrvs-csar.csar", distributionClientDownloadResult.getArtifactFilename()); + } + + @Test + public void testFilenameFromHeaderManySpaces(){ + distributionClientDownloadResult.setArtifactName("attachment; filename=\"service-BkPerformanceSrvs-csar.csar\""); + assertEquals("service-BkPerformanceSrvs-csar.csar", distributionClientDownloadResult.getArtifactFilename()); + } + + @Test + public void testFilenameEmpty(){ + distributionClientDownloadResult.setArtifactName("attachment; filename=\"\""); + assertEquals("", distributionClientDownloadResult.getArtifactFilename()); + } +} diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionClientTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionClientTest.java new file mode 100644 index 0000000..e2bad5a --- /dev/null +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionClientTest.java @@ -0,0 +1,505 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doReturn; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.sdc.utils.TestConfiguration; +import org.onap.sdc.api.IDistributionClient; +import org.onap.sdc.api.consumer.IConfiguration; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.IVfModuleMetadata; +import org.onap.sdc.api.results.IDistributionClientResult; +import org.onap.sdc.http.SdcConnectorClient; +import org.onap.sdc.http.TopicRegistrationResponse; +import org.onap.sdc.utils.ArtifactTypeEnum; +import org.onap.sdc.utils.ArtifactsUtils; +import org.onap.sdc.utils.DistributionActionResultEnum; +import org.onap.sdc.utils.TestNotificationCallback; +import org.onap.sdc.utils.Wrapper; + +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.cambria.client.CambriaClient.CambriaApiException; +import com.att.nsa.cambria.client.CambriaIdentityManager; + +import fj.data.Either; + +public class DistributionClientTest { + + static CambriaIdentityManager cc; + DistributionClientImpl client = Mockito.spy(new DistributionClientImpl()); + IConfiguration testConfiguration = new TestConfiguration(); + SdcConnectorClient connector = Mockito.mock(SdcConnectorClient.class); + + + @After + public void afterTest() { + client.stop(); + } + + @Test + public void validateConfigurationTest() { + DistributionActionResultEnum validationResult = client.validateAndInitConfiguration(new Wrapper(), testConfiguration); + Assert.assertEquals(DistributionActionResultEnum.SUCCESS, validationResult); + Assert.assertEquals(testConfiguration.getPollingInterval(), client.configuration.getPollingInterval()); + Assert.assertEquals(testConfiguration.getPollingTimeout(), client.configuration.getPollingTimeout()); + } + + @Test + public void validateConfigurationToDefaultTest() { + TestConfiguration userConfig = new TestConfiguration(); + userConfig.setPollingInterval(1); + userConfig.setPollingTimeout(2); + DistributionActionResultEnum validationResult = client.validateAndInitConfiguration(new Wrapper(), userConfig); + Assert.assertEquals(DistributionActionResultEnum.SUCCESS, validationResult); + assertEquals(15, client.configuration.getPollingInterval()); + assertEquals(15, client.configuration.getPollingTimeout()); + } + + @Test + public void validateConfigurationFqdnTest() { + + String[] validFqdns = { "myHostname", "myHostname:80", "myHostname:8080", "1.1.1.1", "1.1.1.1:8080", "ueb01hydc.it.open.com", "ueb01hydc.it.open.com:8080", "ueb01hydc.it", "my-good.and-simple.fqdn" }; + + String[] invalidFqdns = { "myHostname:808080", /* 70 letters */"abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij", "not**good", "very#not#good#" }; + + boolean validationResult = true; + + for (int i = 0; i < validFqdns.length; i++) { + validationResult = client.isValidFqdn(validFqdns[i]); + assertEquals("assertion failed for FQDN " + validFqdns[i] + " expected to be valid, actual invalid", true, validationResult); + } + + for (int i = 0; i < invalidFqdns.length; i++) { + validationResult = client.isValidFqdn(invalidFqdns[i]); + assertEquals("assertion failed for FQDN " + invalidFqdns[i] + " expected to be invalid, actual valid", false, validationResult); + } + + } + + @Test + public void validateConfigurationPasswordTest() { + Wrapper errorWrapper = new Wrapper<>(); + TestConfiguration testPassword = new TestConfiguration(); + testPassword.setPassword(null); + DistributionActionResultEnum validationResult = client.validateAndInitConfiguration(errorWrapper, testPassword); + Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_PASSWORD, validationResult); + + testPassword.setPassword(""); + validationResult = client.validateAndInitConfiguration(errorWrapper, testPassword); + Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_PASSWORD, validationResult); + + } + + @Test + public void validateConfigurationUserTest() { + Wrapper errorWrapper = new Wrapper<>(); + TestConfiguration testUser = new TestConfiguration(); + testUser.setUser(null); + DistributionActionResultEnum validationResult = client.validateAndInitConfiguration(errorWrapper, testUser); + Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_USERNAME, validationResult); + + testUser.setUser(""); + validationResult = client.validateAndInitConfiguration(errorWrapper, testUser); + Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_USERNAME, validationResult); + + } + + @Test + public void initWithMocksBadConfigurationTest() throws HttpException, CambriaApiException, IOException { + + + TopicRegistrationResponse topics = new TopicRegistrationResponse(); + topics.setDistrNotificationTopicName("notificationTopic"); + topics.setDistrStatusTopicName("statusTopic"); + Either topicsResult = Either.left(topics); + Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); + + client.asdcConnector = connector; + + // cambriaMock + + CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); + Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))).thenReturn(new ApiCredential("public", "secret")); + client.cambriaIdentityManager = cambriaMock; + + // no password + TestConfiguration testPassword = new TestConfiguration(); + testPassword.setPassword(null); + IDistributionClientResult validationResult = client.init(testPassword, new TestNotificationCallback()); + Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_PASSWORD, validationResult.getDistributionActionResult()); + + testPassword.setPassword(""); + validationResult = client.init(testPassword, new TestNotificationCallback()); + Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_PASSWORD, validationResult.getDistributionActionResult()); + + // no username + TestConfiguration testUser = new TestConfiguration(); + testUser.setUser(null); + validationResult = client.init(testUser, new TestNotificationCallback()); + Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_USERNAME, validationResult.getDistributionActionResult()); + + testUser.setUser(""); + validationResult = client.init(testUser, new TestNotificationCallback()); + Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_USERNAME, validationResult.getDistributionActionResult()); + + // no ASDC server fqdn + TestConfiguration testServerFqdn = new TestConfiguration(); + testServerFqdn.setAsdcAddress(null); + validationResult = client.init(testServerFqdn, new TestNotificationCallback()); + Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_ASDC_FQDN, validationResult.getDistributionActionResult()); + + testServerFqdn.setAsdcAddress(""); + validationResult = client.init(testServerFqdn, new TestNotificationCallback()); + Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_ASDC_FQDN, validationResult.getDistributionActionResult()); + + testServerFqdn.setAsdcAddress("this##is##bad##fqdn"); + validationResult = client.init(testServerFqdn, new TestNotificationCallback()); + Assert.assertEquals(DistributionActionResultEnum.CONF_INVALID_ASDC_FQDN, validationResult.getDistributionActionResult()); + + // no consumerId + TestConfiguration testConsumerId = new TestConfiguration(); + testConsumerId.setComsumerID(null); + validationResult = client.init(testConsumerId, new TestNotificationCallback()); + Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_CONSUMER_ID, validationResult.getDistributionActionResult()); + + testConsumerId.setComsumerID(""); + validationResult = client.init(testConsumerId, new TestNotificationCallback()); + Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_CONSUMER_ID, validationResult.getDistributionActionResult()); + + // no environmentName + TestConfiguration testEnv = new TestConfiguration(); + testEnv.setEnvironmentName(null); + validationResult = client.init(testEnv, new TestNotificationCallback()); + Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_ENVIRONMENT_NAME, validationResult.getDistributionActionResult()); + + testEnv.setEnvironmentName(""); + validationResult = client.init(testEnv, new TestNotificationCallback()); + Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_ENVIRONMENT_NAME, validationResult.getDistributionActionResult()); + + Mockito.verify(client, Mockito.times(0)).getUEBServerList(); + Mockito.verify(cambriaMock, Mockito.times(0)).createApiKey(Mockito.anyString(), Mockito.anyString()); + Mockito.verify(connector, Mockito.times(0)).registerAsdcTopics(Mockito.any(ApiCredential.class)); + } + + @Test + public void initFailedConnectAsdcTest() throws HttpException, CambriaApiException, IOException { + // cambriaMock + + CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); + Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))).thenReturn(new ApiCredential("public", "secret")); + client.cambriaIdentityManager = cambriaMock; + + TestConfiguration badAsdcConfig = new TestConfiguration(); + badAsdcConfig.setAsdcAddress("badhost:8080"); + + IDistributionClientResult init = client.init(badAsdcConfig, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, init.getDistributionActionResult()); + + badAsdcConfig = new TestConfiguration(); + badAsdcConfig.setAsdcAddress("localhost:8181"); + + init = client.init(badAsdcConfig, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, init.getDistributionActionResult()); + + } + + @Test + public void getConfigurationTest() throws HttpException, CambriaApiException, IOException { + // connectorMock + mockArtifactTypeList(); + TopicRegistrationResponse topics = new TopicRegistrationResponse(); + topics.setDistrNotificationTopicName("notificationTopic"); + topics.setDistrStatusTopicName("statusTopic"); + Either topicsResult = Either.left(topics); + Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); + IDistributionClientResult success = initSuccesResult(); + Mockito.when(connector.unregisterTopics(Mockito.any(ApiCredential.class))).thenReturn(success); + + client.asdcConnector = connector; + + // cambriaMock + + CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); + Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))).thenReturn(new ApiCredential("public", "secret")); + client.cambriaIdentityManager = cambriaMock; + + TestConfiguration badAsdcConfig = new TestConfiguration(); + badAsdcConfig.setPollingInterval(-5); + + IDistributionClientResult init = client.init(badAsdcConfig, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.SUCCESS, init.getDistributionActionResult()); + + String confString = client.getConfiguration().toString(); + System.out.println(confString); + + } + + private IDistributionClientResult initSuccesResult() { + return new IDistributionClientResult() { + + @Override + public String getDistributionMessageResult() { + return "success"; + } + + @Override + public DistributionActionResultEnum getDistributionActionResult() { + return DistributionActionResultEnum.SUCCESS; + } + }; + } + + @Test + public void initWithMocksTest() throws HttpException, CambriaApiException, IOException { + + mockArtifactTypeList(); + + TopicRegistrationResponse topics = new TopicRegistrationResponse(); + topics.setDistrNotificationTopicName("notificationTopic"); + topics.setDistrStatusTopicName("statusTopic"); + Either topicsResult = Either.left(topics); + Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); + IDistributionClientResult success = initSuccesResult(); + Mockito.when(connector.unregisterTopics(Mockito.any(ApiCredential.class))).thenReturn(success); + + client.asdcConnector = connector; + + // cambriaMock + + CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); + Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))).thenReturn(new ApiCredential("public", "secret")); + client.cambriaIdentityManager = cambriaMock; + + IDistributionClientResult initResponse = client.init(testConfiguration, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.SUCCESS, initResponse.getDistributionActionResult()); + Mockito.verify(client, Mockito.times(1)).getUEBServerList(); + Mockito.verify(cambriaMock, Mockito.times(1)).createApiKey(Mockito.anyString(), Mockito.anyString()); + Mockito.verify(connector, Mockito.times(1)).registerAsdcTopics(Mockito.any(ApiCredential.class)); + System.out.println(initResponse); + } + + private void mockArtifactTypeList() { + List artifactTypes = new ArrayList<>(); + for (ArtifactTypeEnum artifactType : ArtifactTypeEnum.values()) { + artifactTypes.add(artifactType.name()); + } + + final Either, IDistributionClientResult> eitherArtifactTypes = Either.left(artifactTypes); + Mockito.when(connector.getValidArtifactTypesList()).thenReturn(eitherArtifactTypes); + } + + @Test + public void testAlreadyInitTest() throws HttpException, CambriaApiException, IOException { + initWithMocksTest(); + IDistributionClientResult initResponse = client.init(testConfiguration, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.DISTRIBUTION_CLIENT_ALREADY_INITIALIZED, initResponse.getDistributionActionResult()); + } + + @Test + public void initGetServerFailedTest() throws HttpException, CambriaApiException, IOException { + + // connectorMock + IDistributionClientResult getServersResult = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_SERVER_PROBLEM, "problem"); + Either, IDistributionClientResult> serversResult = Either.right(getServersResult); + doReturn(serversResult).when(client).getUEBServerList(); + + TopicRegistrationResponse topics = new TopicRegistrationResponse(); + topics.setDistrNotificationTopicName("notificationTopic"); + topics.setDistrStatusTopicName("statusTopic"); + Either topicsResult = Either.left(topics); + Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); + + client.asdcConnector = connector; + + // cambriaMock + + CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); + Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))).thenReturn(new ApiCredential("public", "secret")); + client.cambriaIdentityManager = cambriaMock; + + IDistributionClientResult initResponse = client.init(testConfiguration, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.ASDC_SERVER_PROBLEM, initResponse.getDistributionActionResult()); + + Mockito.verify(client, Mockito.times(1)).getUEBServerList(); + Mockito.verify(cambriaMock, Mockito.times(0)).createApiKey(Mockito.anyString(), Mockito.anyString()); + Mockito.verify(connector, Mockito.times(0)).registerAsdcTopics(Mockito.any(ApiCredential.class)); + + System.out.println(initResponse); + } + + @Test + public void initCreateKeysFailedTest() throws HttpException, CambriaApiException, IOException { + + // connectorMock + mockArtifactTypeList(); + + TopicRegistrationResponse topics = new TopicRegistrationResponse(); + topics.setDistrNotificationTopicName("notificationTopic"); + topics.setDistrStatusTopicName("statusTopic"); + Either topicsResult = Either.left(topics); + Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); + + client.asdcConnector = connector; + + // cambriaMock + + CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); + Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))).thenThrow(new CambriaApiException("failure")); + client.cambriaIdentityManager = cambriaMock; + + IDistributionClientResult initResponse = client.init(testConfiguration, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.UEB_KEYS_CREATION_FAILED, initResponse.getDistributionActionResult()); + + Mockito.verify(client, Mockito.times(1)).getUEBServerList(); + Mockito.verify(cambriaMock, Mockito.times(1)).createApiKey(Mockito.anyString(), Mockito.anyString()); + Mockito.verify(connector, Mockito.times(0)).registerAsdcTopics(Mockito.any(ApiCredential.class)); + System.out.println(initResponse); + } + + @Test + public void initRegistrationFailedTest() throws HttpException, CambriaApiException, IOException { + + // connectorMock + mockArtifactTypeList(); + DistributionClientResultImpl failureResult = new DistributionClientResultImpl(DistributionActionResultEnum.BAD_REQUEST, "Bad Request"); + Either topicsResult = Either.right(failureResult); + Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); + + client.asdcConnector = connector; + + // cambriaMock + + CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); + Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))).thenReturn(new ApiCredential("public", "secret")); + client.cambriaIdentityManager = cambriaMock; + + IDistributionClientResult initResponse = client.init(testConfiguration, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.BAD_REQUEST, initResponse.getDistributionActionResult()); + Mockito.verify(client, Mockito.times(1)).getUEBServerList(); + Mockito.verify(cambriaMock, Mockito.times(1)).createApiKey(Mockito.anyString(), Mockito.anyString()); + Mockito.verify(connector, Mockito.times(1)).registerAsdcTopics(Mockito.any(ApiCredential.class)); + System.out.println(initResponse); + } + + @Test + public void testStartWithoutInit() { + IDistributionClientResult result = client.start(); + assertTrue(result.getDistributionActionResult() == DistributionActionResultEnum.DISTRIBUTION_CLIENT_NOT_INITIALIZED); + } + + private IArtifactInfo initArtifactInfo() { + ArtifactInfoImpl artifactInfo = new ArtifactInfoImpl(); + artifactInfo.setArtifactURL("/sdc/v1/services/serviceName/0.1/artifacts/aaa.hh"); + artifactInfo.setArtifactChecksum(ArtifactsUtils.getValidChecksum()); + return artifactInfo; + } + + // ########### TESTS TO ADD TO CI START ########### + /*public void createKeysTestCI() throws MalformedURLException, GeneralSecurityException { + validateConfigurationTest(); + CambriaIdentityManager trueCambria = new CambriaClientBuilders.IdentityManagerBuilder().usingHttps().usingHosts(serverList).build(); + client.cambriaIdentityManager = trueCambria; + DistributionClientResultImpl keysResult = client.createUebKeys(); + Assert.assertEquals(DistributionActionResultEnum.SUCCESS, keysResult.getDistributionActionResult()); + Assert.assertFalse(client.credential.getApiKey().isEmpty()); + Assert.assertFalse(client.credential.getApiSecret().isEmpty()); + + System.out.println(keysResult); + System.out.println("keys: public=" + client.credential.getApiKey() + " | secret=" + client.credential.getApiSecret()); + } +*/ + public void initTestCI() { + IDistributionClient distributionClient = DistributionClientFactory.createDistributionClient(); + IDistributionClientResult init = distributionClient.init(testConfiguration, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.SUCCESS, init.getDistributionActionResult()); + + } + + @Test + public void testDecodeVfModuleArtifact() throws IOException{ + String vfModuleContent = getVFModuleExample(); + List decodeVfModuleArtifact = client.decodeVfModuleArtifact(vfModuleContent.getBytes()); + assertTrue(decodeVfModuleArtifact.size() == 1); + IVfModuleMetadata iVfModuleMetadata = decodeVfModuleArtifact.get(0); + assertTrue(iVfModuleMetadata.getArtifacts().size() == 11); + assertEquals(iVfModuleMetadata.getVfModuleModelName(), "Vccfdb..base_vDB_11032016..module-0"); + } + + private String getVFModuleExample() { + return "[\r\n" + + " {\r\n" + + " \"vfModuleModelName\": \"Vccfdb..base_vDB_11032016..module-0\",\r\n" + + " \"vfModuleModelInvariantUUID\": \"89bcc10e-84f9-475a-b7e3-bdac6cd2b31a\",\r\n" + + " \"vfModuleModelVersion\": \"1\",\r\n" + + " \"vfModuleModelUUID\": \"f7e1c7aa-cc7b-4dfc-b761-237e8063bd96\",\r\n" + + " \"GuguBubu\": true,\r\n" + + " \"isBase\": true,\r\n" + + " \"artifacts\": [\r\n" + + " \"68733000-7656-487c-aecb-040af96df5a5\",\r\n" + + " \"d3519bb4-be98-4c04-8815-4557379fdff3\",\r\n" + + " \"b445d84b-de23-4f0c-a0aa-8d794d85bebe\",\r\n" + + " \"52a6656a-63f4-4ae8-80f4-40febcaa15d6\",\r\n" + + " \"fdcf20b5-1bac-4da7-9e77-b0b565115027\",\r\n" + + " \"d3fcfd98-941c-4627-8b94-386dd3eab1ab\",\r\n" + + " \"bdd6c2b6-793b-49d7-8590-51e7d6998f69\",\r\n" + + " \"554a62b0-3a56-4c29-bc5e-23badf6da67f\",\r\n" + + " \"4b922d87-f2c9-44da-b933-57a91294fb42\",\r\n" + + " \"ad5cceda-0fa4-415e-b319-96f080e4b5c7\",\r\n" + + " \"8f4312f4-7be5-4d64-a3f5-564be7a0f01e\"\r\n" + + " ]\r\n" + + " }\r\n" + + "]"; + } + + + + public void connectorRegisterCI() { + SdcConnectorClient connector = new SdcConnectorClient(); + connector.init(testConfiguration); + + ApiCredential creds = new ApiCredential("publicKey", "secretKey"); + Either topicsFromAsdc = connector.registerAsdcTopics(creds); + assertTrue(topicsFromAsdc.isLeft()); + + } + + public void downloadArtifactTestCI() { + SdcConnectorClient connector = new SdcConnectorClient(); + connector.init(testConfiguration); + IArtifactInfo artifactInfo = initArtifactInfo(); + connector.dowloadArtifact(artifactInfo); + + } + // ########### TESTS TO ADD TO CI END ########### + +} diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/impl/HeatParserTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/HeatParserTest.java new file mode 100644 index 0000000..815d749 --- /dev/null +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/HeatParserTest.java @@ -0,0 +1,139 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; +import org.onap.sdc.utils.heat.HeatParser; +import org.onap.sdc.utils.heat.HeatParameter; +import org.onap.sdc.utils.heat.HeatParameterConstraint; + +import com.google.common.base.Charsets; +import com.google.common.io.Resources; + +public class HeatParserTest { + + @Test + public void testParametersParsing() throws IOException{ + String resourceName = "heatExample.yaml"; + URL url = Resources.getResource(resourceName); + String heatFileContents = Resources.toString(url, Charsets.UTF_8); + assertNotNull("Didn't find "+resourceName, heatFileContents); + + HeatParser heatParser = new HeatParser(); + //Flat parameter entry + Map parameters = heatParser.getHeatParameters(heatFileContents); + HeatParameter heatParameter1 = parameters.get("image_name_1"); + validateField("string", heatParameter1.getType(), "type"); + validateField("Image Name", heatParameter1.getLabel(), "label"); + validateField("SCOIMAGE Specify an image name for instance1", heatParameter1.getDescription(), "description"); + validateField("cirros-0.3.1-x86_64", heatParameter1.getDefault(), "default"); + validateField(null, heatParameter1.getConstraints(), "constraints"); + validateField("false", heatParameter1.getHidden(), "hidden"); + + + //Flat parameter entry with constraints + heatParameter1 = parameters.get("network_id"); + validateField("string", heatParameter1.getType(), "type"); + validateField("Network ID", heatParameter1.getLabel(), "label"); + validateField("SCONETWORK Network to be used for the compute instance", heatParameter1.getDescription(), "description"); + validateField(null, heatParameter1.getDefault(), "default"); + validateField("true", heatParameter1.getHidden(), "hidden"); + + //Constraints + List constraints = heatParameter1.getConstraints(); + assertEquals("Number of constraints", 6, constraints.size()); + + //Length + HeatParameterConstraint lengthConstraint = heatParameter1.getLengthConstraint(); + assertNotNull(lengthConstraint); + Map expectedMap = new HashMap<>(); + expectedMap.put("min", "6"); + expectedMap.put("max", "8"); + validateField(expectedMap, lengthConstraint.getLength(), "length"); + validateField("Password length must be between 6 and 8 characters.", lengthConstraint.getDescription(), "length description"); + + //Range + HeatParameterConstraint rangeConstraint = heatParameter1.getRangeConstraint(); + assertNotNull(rangeConstraint); + validateField(expectedMap, rangeConstraint.getRange(), "range"); + validateField("Range description", rangeConstraint.getDescription(), "range description"); + + //Allowed values + HeatParameterConstraint allowedValues = heatParameter1.getAllowedValuesConstraint(); + assertNotNull(allowedValues); + List expectedValues = new ArrayList<>(); + expectedValues.add("m1.small"); + expectedValues.add("m1.medium"); + expectedValues.add("m1.large"); + validateField(expectedValues, allowedValues.getAllowed_values(), "allowed_values"); + validateField("Allowed values description", allowedValues.getDescription(), "allowed_values description"); + + //Allowed pattern + List allowedPatternList = heatParameter1.getAllowedPatternConstraint(); + assertNotNull(allowedPatternList); + assertEquals("Allowed pattern list", 2, allowedPatternList.size()); + HeatParameterConstraint allowedPattern = allowedPatternList.get(0); + validateField("[a-zA-Z0-9]+", allowedPattern.getAllowed_pattern(), "allowed_pattern"); + validateField("Password must consist of characters and numbers only.", allowedPattern.getDescription(), "allowed_pattern description"); + allowedPattern = allowedPatternList.get(1); + validateField("[A-Z]+[a-zA-Z0-9]*", allowedPattern.getAllowed_pattern(), "allowed_pattern"); + validateField("Password must start with an uppercase character.", allowedPattern.getDescription(), "allowed_pattern description"); + + //Custom constraint + List customConstraintList = heatParameter1.getCustomConstraintConstraint(); + assertNotNull(customConstraintList); + assertEquals("Custom constraint list", 1, customConstraintList.size()); + HeatParameterConstraint customConstraint = customConstraintList.get(0); + validateField("nova.keypair", customConstraint.getCustom_constraint(), "custom_constraint"); + validateField("Custom description", customConstraint.getDescription(), "custom_constraint description"); + } + + @Test + public void testParametersParsingInvalidYaml() throws IOException{ + String invalidHeatFileContents = "just text"; + HeatParser heatParser = new HeatParser(); + //Flat parameter entry + Map parameters = heatParser.getHeatParameters(invalidHeatFileContents); + assertNull(parameters); + } + + @Test + public void testParametersParsingNoParamteresSection() throws IOException{ + String heatFileContentsNoParams = "heat_template_version: 2013-05-23\r\n\r\ndescription: Simple template to deploy a stack with two virtual machine instances"; + HeatParser heatParser = new HeatParser(); + //Flat parameter entry + Map parameters = heatParser.getHeatParameters(heatFileContentsNoParams); + assertNull(parameters); + } + + private void validateField(Object expected, Object actual, String type){ + assertEquals("Field of type "+type+":", expected, actual); + } +} diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/impl/NotificationConsumerTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/NotificationConsumerTest.java new file mode 100644 index 0000000..7603d0c --- /dev/null +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/NotificationConsumerTest.java @@ -0,0 +1,352 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.impl; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import org.eclipse.jetty.util.ArrayQueue; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.onap.sdc.utils.TestConfiguration; +import org.onap.sdc.api.consumer.INotificationCallback; +import org.onap.sdc.api.notification.INotificationData; +import org.onap.sdc.api.results.IDistributionClientResult; +import org.onap.sdc.utils.ArtifactTypeEnum; +import org.onap.sdc.utils.DistributionActionResultEnum; +import org.onap.sdc.utils.DistributionClientConstants; + +import com.att.nsa.cambria.client.CambriaConsumer; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class NotificationConsumerTest { + private CambriaConsumer cambriaConsumer = mock(CambriaConsumer.class); + private INotificationCallback clientCallback = spy(INotificationCallback.class); + private Queue> notificationsQueue = new ArrayQueue<>(100); + private DistributionClientImpl distributionClient = Mockito.spy(DistributionClientImpl.class); + private List artifactsTypes = Arrays.asList(ArtifactTypeEnum.HEAT.name()); + private List notificationStatusResults = new ArrayList<>(); + final static IDistributionClientResult DISTRIBUTION_SUCCESS_RESULT = buildSuccessResult(); + + private NotificationConsumer createNotificationConsumer() { + return new NotificationConsumer(cambriaConsumer, clientCallback, artifactsTypes, distributionClient); + } + + @Before + public void beforeTest() throws IOException { + Mockito.reset(clientCallback, distributionClient); + when(cambriaConsumer.fetch()).then(new Answer>() { + @Override + public Iterable answer(InvocationOnMock invocation) throws Throwable { + if (!notificationsQueue.isEmpty()) { + return notificationsQueue.remove(); + } else { + return new ArrayList<>(); + } + } + }); + when(distributionClient.sendNotificationStatus(Mockito.anyLong(), Mockito.anyString(), Mockito.any(ArtifactInfoImpl.class), Mockito.anyBoolean())).then(new Answer() { + @Override + public IDistributionClientResult answer(InvocationOnMock invocation) throws Throwable { + boolean isNotified = (boolean) invocation.getArguments()[3]; + notificationStatusResults.add(Boolean.valueOf(isNotified)); + return DISTRIBUTION_SUCCESS_RESULT; + } + }); + + } + + private static IDistributionClientResult buildSuccessResult() { + return new IDistributionClientResult() { + + @Override + public String getDistributionMessageResult() { + return ""; + } + + @Override + public DistributionActionResultEnum getDistributionActionResult() { + return DistributionActionResultEnum.SUCCESS; + } + }; + } + + @Test + public void testNoNotifiactionsSent() throws InterruptedException { + + ScheduledExecutorService executorPool = Executors.newScheduledThreadPool(DistributionClientConstants.POOL_SIZE); + executorPool.scheduleAtFixedRate(createNotificationConsumer(), 0, 100, TimeUnit.MILLISECONDS); + + Thread.sleep(1000); + executorPool.shutdown(); + + Mockito.verify(clientCallback, Mockito.times(0)).activateCallback(Mockito.any(INotificationData.class)); + + } + + @Test + public void testNonRelevantNotificationSent() throws InterruptedException { + + simulateNotificationFromUEB(getAsdcServiceNotificationWithoutHeatArtifact()); + Mockito.verify(clientCallback, Mockito.times(0)).activateCallback(Mockito.any(INotificationData.class)); + + } + + @Test + public void testRelevantNotificationSent() throws InterruptedException { + simulateNotificationFromUEB(getAsdcServiceNotificationWithHeatArtifact()); + Mockito.verify(clientCallback, Mockito.times(1)).activateCallback(Mockito.any(INotificationData.class)); + + } + + @Test + public void testNonExistingArtifactsNotificationSent() throws InterruptedException { + simulateNotificationFromUEB(getAsdcNotificationWithNonExistentArtifact()); + Mockito.verify(clientCallback, Mockito.times(1)).activateCallback(Mockito.any(INotificationData.class)); + + } + + @Test + public void testNotificationStatusSent() throws InterruptedException { + simulateNotificationFromUEB(getAsdcServiceNotificationWithHeatArtifact()); + + Mockito.verify(distributionClient, Mockito.times(3)).sendNotificationStatus(Mockito.anyLong(), Mockito.anyString(), Mockito.any(ArtifactInfoImpl.class), Mockito.anyBoolean()); + assertTrue(countInstances(notificationStatusResults, Boolean.TRUE) == 1); + assertTrue(countInstances(notificationStatusResults, Boolean.FALSE) == 2); + } + + @Test + public void testNotificationRelatedArtifacts() throws InterruptedException { + List artifactTypesTmp = new ArrayList<>(); + for (ArtifactTypeEnum artifactTypeEnum : ArtifactTypeEnum.values()) { + artifactTypesTmp.add(artifactTypeEnum.name()); + } + artifactsTypes = artifactTypesTmp; + simulateNotificationFromUEB(getAsdcServiceNotificationWithRelatedArtifacts()); + + Mockito.verify(distributionClient, Mockito.times(3)).sendNotificationStatus(Mockito.anyLong(), Mockito.anyString(), Mockito.any(ArtifactInfoImpl.class), Mockito.anyBoolean()); + assertTrue(countInstances(notificationStatusResults, Boolean.TRUE) == 3); + assertTrue(countInstances(notificationStatusResults, Boolean.FALSE) == 0); + } + + @Test + public void testNotificationStatusWithServiceArtifatcs() throws InterruptedException { + simulateNotificationFromUEB(getNotificationWithServiceArtifatcs()); + Mockito.verify(distributionClient, Mockito.times(6)).sendNotificationStatus(Mockito.anyLong(), Mockito.anyString(), Mockito.any(ArtifactInfoImpl.class), Mockito.anyBoolean()); + assertTrue(countInstances(notificationStatusResults, Boolean.TRUE) == 2); + assertTrue(countInstances(notificationStatusResults, Boolean.FALSE) == 4); + + } + + @Test + public final void testBuildCallbackNotificationLogicFlagIsFalse() { + NotificationConsumer consumer = createNotificationConsumer(); + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + TestConfiguration testConfiguration = new TestConfiguration(); + testConfiguration.setFilterInEmptyResources(false); + when(distributionClient.getConfiguration()).thenReturn(testConfiguration); + NotificationDataImpl notification = gson.fromJson(getNotificationWithMultipleResources(), NotificationDataImpl.class); + NotificationDataImpl notificationBuiltInClient = consumer.buildCallbackNotificationLogic(0, notification); + assertTrue(notificationBuiltInClient.getResources().size() == 1); + } + + @Test + public final void testBuildCallbackNotificationLogicFlagIsTrue() { + NotificationConsumer consumer = createNotificationConsumer(); + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + TestConfiguration testConfiguration = new TestConfiguration(); + testConfiguration.setFilterInEmptyResources(true); + when(distributionClient.getConfiguration()).thenReturn(testConfiguration); + NotificationDataImpl notification = gson.fromJson(getNotificationWithMultipleResources(), NotificationDataImpl.class); + NotificationDataImpl notificationBuiltInClient = consumer.buildCallbackNotificationLogic(0, notification); + assertTrue(notificationBuiltInClient.getResources().size() == 2); + } + + private void simulateNotificationFromUEB(final String notificationFromUEB) throws InterruptedException { + ScheduledExecutorService executorPool = Executors.newScheduledThreadPool(DistributionClientConstants.POOL_SIZE); + executorPool.scheduleAtFixedRate(createNotificationConsumer(), 0, 100, TimeUnit.MILLISECONDS); + + Thread.sleep(200); + + List nonHeatNotification = Arrays.asList(notificationFromUEB); + notificationsQueue.add(nonHeatNotification); + Thread.sleep(800); + executorPool.shutdown(); + } + + private String getAsdcServiceNotificationWithHeatArtifact() { + return "{\"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + " \"serviceName\" : \"Testnotificationser1\",\r\n" + " \"serviceVersion\" : \"1.0\",\r\n" + + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" + " \"resources\" : [{\r\n" + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" + + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + " \"resourceVersion\" : \"1.0\",\r\n" + " \"resoucreType\" : \"VF\",\r\n" + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" + + " \"artifacts\" : [{\r\n" + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" + " \"artifactType\" : \"YANG_XML\",\r\n" + + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" + + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" + " \"artifactDescription\" : \"MyYang\",\r\n" + " \"artifactTimeout\" : 0,\r\n" + + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" + + " \"artifactType\" : \"HEAT\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" + + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" + + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.env\",\r\n" + + " \"artifactType\" : \"HEAT_ENV\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" + + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" + + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" + + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ]\r\n" + " }\r\n" + " ]}"; + } + + private String getNotificationWithMultipleResources(){ + return "{\"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + + " \"serviceName\" : \"Testnotificationser1\",\r\n" + + " \"serviceVersion\" : \"1.0\",\r\n" + + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" + + " \"resources\" : [{\r\n" + + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" + + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + + " \"resourceVersion\" : \"1.0\",\r\n" + + " \"resoucreType\" : \"VF\",\r\n" + + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" + + " \"artifacts\" : [{\r\n" + + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" + + " \"artifactType\" : \"YANG_XML\",\r\n" + + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" + + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" + + " \"artifactDescription\" : \"MyYang\",\r\n" + + " \"artifactTimeout\" : 0,\r\n" + + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + + " \"artifactVersion\" : \"1\"\r\n" + + " }" + + " ]\r\n" + + " },\r\n" + + " {\r\n" + + " \"resourceInstanceName\" : \"testnotificationvf12\",\r\n" + + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + + " \"resourceVersion\" : \"1.0\",\r\n" + + " \"resoucreType\" : \"VF\",\r\n" + + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2e\",\r\n" + + " \"artifacts\" : [{\r\n" + + " \"artifactName\" : \"heat.yaml\",\r\n" + + " \"artifactType\" : \"HEAT\",\r\n" + + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" + + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + + " \"artifactDescription\" : \"heat\",\r\n" + + " \"artifactTimeout\" : 60,\r\n" + + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + + " \"artifactVersion\" : \"1\"\r\n" + + " }" + + " ]\r\n" + + " }\r\n" + + " ]}"; + } + + + private String getAsdcNotificationWithNonExistentArtifact() { + return "{\"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + " \"serviceName\" : \"Testnotificationser1\",\r\n" + " \"serviceVersion\" : \"1.0\",\r\n" + + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" + " \"bugabuga\" : \"xyz\",\r\n" + " \"resources\" : [{\r\n" + + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + " \"resourceVersion\" : \"1.0\",\r\n" + " \"resoucreType\" : \"VF\",\r\n" + + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" + " \"artifacts\" : [{\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" + " \"artifactType\" : \"HEAT\",\r\n" + + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" + + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" + + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactBuga\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + + " }, {\r\n" + " \"artifactName\" : \"buga.bug\",\r\n" + " \"artifactType\" : \"BUGA_BUGA\",\r\n" + + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" + + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" + + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" + + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ]\r\n" + " }\r\n" + " ]}"; + } + + private String getAsdcServiceNotificationWithRelatedArtifacts() { + return "{\"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + " \"serviceName\" : \"Testnotificationser1\",\r\n" + " \"serviceVersion\" : \"1.0\",\r\n" + + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" + " \"resources\" : [{\r\n" + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" + + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + " \"resourceVersion\" : \"1.0\",\r\n" + " \"resoucreType\" : \"VF\",\r\n" + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" + + " \"artifacts\" : [{\r\n" + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" + " \"artifactType\" : \"YANG_XML\",\r\n" + + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" + + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" + " \"artifactDescription\" : \"MyYang\",\r\n" + " \"artifactTimeout\" : 0,\r\n" + + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" + " \"relatedArtifacts\" : [\r\n" + + " \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\"\r\n" + " ]" + " }, {\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" + + " \"artifactType\" : \"HEAT\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" + + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" + + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\", \r\n" + " \"relatedArtifacts\" : [\r\n" + + " \"0005bc4a-2c19-452e-be6d-d574a56be4d0\", \r\n" + " \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\"\r\n" + " ]" + " }, {\r\n" + + " \"artifactName\" : \"heat.env\",\r\n" + " \"artifactType\" : \"HEAT_ENV\",\r\n" + + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" + + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" + + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" + + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ]\r\n" + " }\r\n" + " ]}"; + } + + private String getAsdcServiceNotificationWithoutHeatArtifact() { + return "{" + " \"distributionID\" : \"5v1234d8-5b6d-42c4-7t54-47v95n58qb7\"," + " \"serviceName\" : \"srv1\"," + " \"serviceVersion\": \"2.0\"," + " \"serviceUUID\" : \"4e0697d8-5b6d-42c4-8c74-46c33d46624c\"," + + " \"serviceArtifacts\":[" + " {" + " \"artifactName\" : \"ddd.yml\"," + " \"artifactType\" : \"DG_XML\"," + " \"artifactTimeout\" : \"65\"," + + " \"artifactDescription\" : \"description\"," + " \"artifactURL\" :" + " \"/sdc/v1/catalog/services/srv1/2.0/resources/ddd/3.0/artifacts/ddd.xml\" ," + + " \"resourceUUID\" : \"4e5874d8-5b6d-42c4-8c74-46c33d90drw\" ," + " \"checksum\" : \"15e389rnrp58hsw==\"" + " }" + " ]" + "}"; + } + + private String getNotificationWithServiceArtifatcs() { + return "{\r\n" + " \"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + " \"serviceName\" : \"Testnotificationser1\",\r\n" + " \"serviceVersion\" : \"1.0\",\r\n" + + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" + " \"serviceArtifacts\" : [{\r\n" + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" + + " \"artifactType\" : \"YANG_XML\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" + + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" + " \"artifactDescription\" : \"MyYang\",\r\n" + " \"artifactTimeout\" : 0,\r\n" + + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" + + " \"artifactType\" : \"HEAT\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" + + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" + + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.env\",\r\n" + + " \"artifactType\" : \"HEAT_ENV\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" + + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" + + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" + + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ],\r\n" + " \"resources\" : [{\r\n" + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" + + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + " \"resourceVersion\" : \"1.0\",\r\n" + " \"resoucreType\" : \"VF\",\r\n" + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" + + " \"artifacts\" : [{\r\n" + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" + " \"artifactType\" : \"YANG_XML\",\r\n" + + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" + + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" + " \"artifactDescription\" : \"MyYang\",\r\n" + " \"artifactTimeout\" : 0,\r\n" + + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" + + " \"artifactType\" : \"HEAT\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" + + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" + + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.env\",\r\n" + + " \"artifactType\" : \"HEAT_ENV\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" + + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" + + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" + + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ]\r\n" + " }\r\n" + " ]\r\n" + "}"; + } + + private int countInstances(List list, T element) { + int count = 0; + for (T curr : list) { + if (curr.equals(element)) { + count++; + } + } + return count; + } +} diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/utils/ArtifactsUtils.java b/sdc-distribution-client/src/test/java/org/onap/sdc/utils/ArtifactsUtils.java new file mode 100644 index 0000000..b562ab7 --- /dev/null +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/utils/ArtifactsUtils.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.utils; + + + +import org.apache.commons.codec.binary.Base64; +import org.onap.sdc.impl.mock.DistributionClientDownloadResultStubImpl; + + +public class ArtifactsUtils { + static DistributionClientDownloadResultStubImpl distributionClientDownloadResultStubImpl = new DistributionClientDownloadResultStubImpl(); + + public static byte [] getArtifactPayload(){ + return distributionClientDownloadResultStubImpl.getArtifactPayload(); + } + + public static String getValidChecksum(){ + + String payloadStr = new String(distributionClientDownloadResultStubImpl.getArtifactPayload()); + + byte[] decodedPayload = Base64.decodeBase64(payloadStr); + String checkSum = GeneralUtils.calculateMD5 (new String(decodedPayload)); + + return checkSum; + } + +} diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/utils/TestConfiguration.java b/sdc-distribution-client/src/test/java/org/onap/sdc/utils/TestConfiguration.java new file mode 100644 index 0000000..0aa314e --- /dev/null +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/utils/TestConfiguration.java @@ -0,0 +1,299 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.utils; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.sdc.api.consumer.IConfiguration; + +public class TestConfiguration implements IConfiguration { + + private String asdcAddress; + private String user; + private String password; + private int pollingInterval = DistributionClientConstants.MIN_POLLING_INTERVAL_SEC; + private int pollingTimeout = DistributionClientConstants.POLLING_TIMEOUT_SEC; + private List relevantArtifactTypes; + private String consumerGroup; + private String environmentName; + private String comsumerID; + private String keyStorePath; + private String keyStorePassword; + private boolean activateServerTLSAuth; + private boolean isFilterInEmptyResources; + private boolean useHttpsWithDmaap; + private List msgBusAddress; + + public TestConfiguration(IConfiguration other) { + this.asdcAddress = other.getAsdcAddress(); + this.comsumerID = other.getConsumerID(); + this.consumerGroup = other.getConsumerGroup(); + this.environmentName = other.getEnvironmentName(); + this.password = other.getPassword(); + this.pollingInterval = other.getPollingInterval(); + this.pollingTimeout = other.getPollingTimeout(); + this.relevantArtifactTypes = other.getRelevantArtifactTypes(); + this.user = other.getUser(); + this.keyStorePath = other.getKeyStorePath(); + this.keyStorePassword = other.getKeyStorePassword(); + this.activateServerTLSAuth = other.activateServerTLSAuth(); + this.isFilterInEmptyResources = other.isFilterInEmptyResources(); + } + + public TestConfiguration() { + this.asdcAddress = "localhost:8443"; + this.comsumerID = "mso-123456"; + this.consumerGroup = "mso-group"; + this.environmentName = "PROD"; + this.password = "password"; + this.pollingInterval = 20; + this.pollingTimeout = 20; + this.relevantArtifactTypes = new ArrayList(); + this.relevantArtifactTypes.add(ArtifactTypeEnum.HEAT.name()); + this.user = "mso-user"; + this.keyStorePath = "etc/asdc-client.jks"; + this.keyStorePassword = "Aa123456"; + this.activateServerTLSAuth = false; + this.isFilterInEmptyResources = false; + msgBusAddress = new ArrayList(); + msgBusAddress.add("www.cnn.com"); + msgBusAddress.add("www.cnn.com"); + msgBusAddress.add("www.cnn.com"); + } + + @Override + public String getAsdcAddress() { + return asdcAddress; + } + + @Override + public List getMsgBusAddress() { + return msgBusAddress; + } + + @Override + public String getUser() { + return user; + } + + @Override + public String getPassword() { + return password; + } + + @Override + public int getPollingInterval() { + return pollingInterval; + } + + @Override + public int getPollingTimeout() { + return pollingTimeout; + } + + @Override + public List getRelevantArtifactTypes() { + return relevantArtifactTypes; + } + + @Override + public String getConsumerGroup() { + return consumerGroup; + } + + @Override + public String getEnvironmentName() { + return environmentName; + } + + @Override + public String getConsumerID() { + return comsumerID; + } + + @Override + public String getKeyStorePath() { + return keyStorePath; + } + + @Override + public String getKeyStorePassword() { + return keyStorePassword; + } + + public String getComsumerID() { + return comsumerID; + } + + public void setComsumerID(String comsumerID) { + this.comsumerID = comsumerID; + } + + public void setAsdcAddress(String asdcAddress) { + this.asdcAddress = asdcAddress; + } + + public void setUser(String user) { + this.user = user; + } + + public void setPassword(String password) { + this.password = password; + } + + public void setPollingInterval(int pollingInterval) { + this.pollingInterval = pollingInterval; + } + + public void setPollingTimeout(int pollingTimeout) { + this.pollingTimeout = pollingTimeout; + } + + public void setRelevantArtifactTypes(List relevantArtifactTypes) { + this.relevantArtifactTypes = relevantArtifactTypes; + } + + public void setConsumerGroup(String consumerGroup) { + this.consumerGroup = consumerGroup; + } + + public void setEnvironmentName(String environmentName) { + this.environmentName = environmentName; + } + + public void setKeyStorePath(String keyStorePath) { + this.keyStorePath = keyStorePath; + } + + public void setKeyStorePassword(String keyStorePassword) { + this.keyStorePassword = keyStorePassword; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((asdcAddress == null) ? 0 : asdcAddress.hashCode()); + result = prime * result + ((comsumerID == null) ? 0 : comsumerID.hashCode()); + result = prime * result + ((consumerGroup == null) ? 0 : consumerGroup.hashCode()); + result = prime * result + ((environmentName == null) ? 0 : environmentName.hashCode()); + result = prime * result + ((password == null) ? 0 : password.hashCode()); + result = prime * result + pollingInterval; + result = prime * result + pollingTimeout; + result = prime * result + ((relevantArtifactTypes == null) ? 0 : relevantArtifactTypes.hashCode()); + result = prime * result + ((user == null) ? 0 : user.hashCode()); + return result; + } + + @Override + public boolean activateServerTLSAuth() { + + return activateServerTLSAuth; + } + + public void setactivateServerTLSAuth(boolean activateServerTLSAuth) { + this.activateServerTLSAuth = activateServerTLSAuth; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + TestConfiguration other = (TestConfiguration) obj; + if (asdcAddress == null) { + if (other.asdcAddress != null) + return false; + } else if (!asdcAddress.equals(other.asdcAddress)) + return false; + if (comsumerID == null) { + if (other.comsumerID != null) + return false; + } else if (!comsumerID.equals(other.comsumerID)) + return false; + if (consumerGroup == null) { + if (other.consumerGroup != null) + return false; + } else if (!consumerGroup.equals(other.consumerGroup)) + return false; + if (environmentName == null) { + if (other.environmentName != null) + return false; + } else if (!environmentName.equals(other.environmentName)) + return false; + if (password == null) { + if (other.password != null) + return false; + } else if (!password.equals(other.password)) + return false; + if (pollingInterval != other.pollingInterval) + return false; + if (pollingTimeout != other.pollingTimeout) + return false; + if (relevantArtifactTypes == null) { + if (other.relevantArtifactTypes != null) + return false; + } else if (!relevantArtifactTypes.equals(other.relevantArtifactTypes)) + return false; + if (user == null) { + if (other.user != null) + return false; + } else if (!user.equals(other.user)) + return false; + if (keyStorePath == null) { + if (other.keyStorePath != null) + return false; + } else if (!keyStorePath.equals(other.keyStorePath)) + return false; + if (keyStorePassword == null) { + if (other.keyStorePassword != null) + return false; + } else if (!keyStorePassword.equals(other.keyStorePassword)) + return false; + + return true; + } + + @Override + public String toString() { + return "TestConfiguration [asdcAddress=" + asdcAddress + ", user=" + user + ", password=" + password + ", pollingInterval=" + pollingInterval + ", pollingTimeout=" + pollingTimeout + ", relevantArtifactTypes=" + relevantArtifactTypes + + ", consumerGroup=" + consumerGroup + ", environmentName=" + environmentName + ", comsumerID=" + comsumerID + "]"; + } + + @Override + public boolean isFilterInEmptyResources() { + return isFilterInEmptyResources; + } + + + public void setFilterInEmptyResources(boolean isFilterInEmptyResources) { + this.isFilterInEmptyResources = isFilterInEmptyResources; + } + + @Override + public Boolean isUseHttpsWithDmaap() { + return this.useHttpsWithDmaap; + } +} diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/utils/TestNotificationCallback.java b/sdc-distribution-client/src/test/java/org/onap/sdc/utils/TestNotificationCallback.java new file mode 100644 index 0000000..32ce405 --- /dev/null +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/utils/TestNotificationCallback.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdc.utils; + +import org.onap.sdc.api.consumer.INotificationCallback; +import org.onap.sdc.api.notification.INotificationData; + +public class TestNotificationCallback implements INotificationCallback{ + + @Override + public void activateCallback(INotificationData data) { + System.out.println("notification callback was called"); + + } + +} diff --git a/sdc-distribution-client/src/test/java/org/openecomp/sdc/http/SdcConnectorClientTest.java b/sdc-distribution-client/src/test/java/org/openecomp/sdc/http/SdcConnectorClientTest.java deleted file mode 100644 index 5ddc915..0000000 --- a/sdc-distribution-client/src/test/java/org/openecomp/sdc/http/SdcConnectorClientTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package org.openecomp.sdc.http; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpEntity; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.openecomp.sdc.api.asdc.RegistrationRequest; -import org.openecomp.sdc.api.consumer.IConfiguration; -import org.openecomp.sdc.impl.DistributionClientResultImpl; -import org.openecomp.sdc.utils.Pair; - -import com.att.nsa.apiClient.credentials.ApiCredential; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import fj.data.Either; - -public class SdcConnectorClientTest { - private Gson gson = new GsonBuilder().create(); - private static final String MOCK_ENV = "MockEnv"; - private static final String MOCK_API_KEY = "MockApikey"; - private static HttpAsdcClient httpClient = Mockito.mock(HttpAsdcClient.class); - private static IConfiguration configuration = Mockito.mock(IConfiguration.class); - private static ApiCredential apiCredential = Mockito.mock(ApiCredential.class); - private static HttpAsdcResponse httpAsdcResponse = Mockito.mock(HttpAsdcResponse.class); - @SuppressWarnings("unchecked") - private static Either mockResponse = Mockito - .mock(Either.class); - private static Map mockHeaders = new HashMap<>(); - Pair mockPair = new Pair<>(httpAsdcResponse, null); - private HttpEntity lastHttpEntity = null; - - private static SdcConnectorClient asdcClient = Mockito.spy(new SdcConnectorClient()); - - @BeforeClass - public static void beforeClass() { - asdcClient.setConfiguration(configuration); - asdcClient.setHttpClient(httpClient); - when(apiCredential.getApiKey()).thenReturn(MOCK_API_KEY); - when(httpAsdcResponse.getStatus()).thenReturn(HttpStatus.SC_OK); - - doReturn(mockHeaders).when(asdcClient).addHeadersToHttpRequest(Mockito.anyString()); - doReturn(mockResponse).when(asdcClient).parseRegistrationResponse(httpAsdcResponse); - } - - @Before - public void beforeMethod() { - Mockito.reset(configuration, httpClient); - lastHttpEntity = null; - when(configuration.getEnvironmentName()).thenReturn(MOCK_ENV); - - - doAnswer(new Answer>() { - @Override - public Pair answer(InvocationOnMock invocation) throws Throwable { - lastHttpEntity = invocation.getArgumentAt(1, HttpEntity.class); - return mockPair; - } - }).when(httpClient).postRequest(Mockito.eq(AsdcUrls.POST_FOR_TOPIC_REGISTRATION), Mockito.any(HttpEntity.class), - Mockito.eq(mockHeaders), Mockito.eq(false)); - } - - @Test - public void testConsumeProduceStatusTopicFalse() throws UnsupportedOperationException, IOException { - - testConsumeProduceStatusTopic(false); - - } - - @Test - public void testConsumeProduceStatusTopicTrue() throws UnsupportedOperationException, IOException { - - testConsumeProduceStatusTopic(true); - - } - - private void testConsumeProduceStatusTopic(final boolean isConsumeProduceStatusFlag) throws IOException { - when(configuration.isConsumeProduceStatusTopic()).thenReturn(isConsumeProduceStatusFlag); - asdcClient.registerAsdcTopics(apiCredential); - verify(httpClient, times(1)).postRequest(Mockito.eq(AsdcUrls.POST_FOR_TOPIC_REGISTRATION), - Mockito.any(HttpEntity.class), Mockito.eq(mockHeaders), Mockito.eq(false)); - assertNotNull(lastHttpEntity); - RegistrationRequest actualRegRequest = gson.fromJson(IOUtils.toString(lastHttpEntity.getContent(), StandardCharsets.UTF_8), RegistrationRequest.class); - RegistrationRequest expectedRegRequest = gson.fromJson(excpectedStringBody(isConsumeProduceStatusFlag), RegistrationRequest.class); - - assertTrue(actualRegRequest.getApiPublicKey().equals(expectedRegRequest.getApiPublicKey())); - assertTrue(actualRegRequest.getDistrEnvName().equals(expectedRegRequest.getDistrEnvName())); - assertTrue(actualRegRequest.getIsConsumerToSdcDistrStatusTopic() - .equals(expectedRegRequest.getIsConsumerToSdcDistrStatusTopic())); - } - - - - private String excpectedStringBody(boolean isConsumeProduceStatusTopic) { - String stringBodyTemplate = "{\r\n" + " \"apiPublicKey\": \"MockApikey\",\r\n" - + " \"distrEnvName\": \"MockEnv\",\r\n" + " \"isConsumerToSdcDistrStatusTopic\": %s\r\n" + "}"; - return String.format(stringBodyTemplate, isConsumeProduceStatusTopic); - - } -} diff --git a/sdc-distribution-client/src/test/java/org/openecomp/sdc/impl/DistributionClientDownloadResultTest.java b/sdc-distribution-client/src/test/java/org/openecomp/sdc/impl/DistributionClientDownloadResultTest.java deleted file mode 100644 index 8f8fca2..0000000 --- a/sdc-distribution-client/src/test/java/org/openecomp/sdc/impl/DistributionClientDownloadResultTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.openecomp.sdc.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.openecomp.sdc.utils.DistributionActionResultEnum; - - -public class DistributionClientDownloadResultTest { - - public static DistributionClientDownloadResultImpl distributionClientDownloadResult; - - @BeforeClass - public static void init(){ - distributionClientDownloadResult = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS, ""); - } - - @Test - public void testNonHeaderFilename(){ - distributionClientDownloadResult.setArtifactName("service-BkPerformanceSrvs-csar.csar"); - assertEquals("service-BkPerformanceSrvs-csar.csar", distributionClientDownloadResult.getArtifactFilename()); - } - - @Test - public void testNullFilename(){ - distributionClientDownloadResult.setArtifactName(null); - assertNull(distributionClientDownloadResult.getArtifactFilename()); - } - - @Test - public void testFilenameFromHeaderNoSpace(){ - distributionClientDownloadResult.setArtifactName("attachment;filename=\"service-BkPerformanceSrvs-csar.csar\""); - assertEquals("service-BkPerformanceSrvs-csar.csar", distributionClientDownloadResult.getArtifactFilename()); - } - - @Test - public void testFilenameFromHeaderOneSpace(){ - distributionClientDownloadResult.setArtifactName("attachment; filename=\"service-BkPerformanceSrvs-csar.csar\""); - assertEquals("service-BkPerformanceSrvs-csar.csar", distributionClientDownloadResult.getArtifactFilename()); - } - - @Test - public void testFilenameFromHeaderManySpaces(){ - distributionClientDownloadResult.setArtifactName("attachment; filename=\"service-BkPerformanceSrvs-csar.csar\""); - assertEquals("service-BkPerformanceSrvs-csar.csar", distributionClientDownloadResult.getArtifactFilename()); - } - - @Test - public void testFilenameEmpty(){ - distributionClientDownloadResult.setArtifactName("attachment; filename=\"\""); - assertEquals("", distributionClientDownloadResult.getArtifactFilename()); - } -} diff --git a/sdc-distribution-client/src/test/java/org/openecomp/sdc/impl/DistributionClientTest.java b/sdc-distribution-client/src/test/java/org/openecomp/sdc/impl/DistributionClientTest.java deleted file mode 100644 index 81f9a17..0000000 --- a/sdc-distribution-client/src/test/java/org/openecomp/sdc/impl/DistributionClientTest.java +++ /dev/null @@ -1,505 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doReturn; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; -import org.mockito.Mockito; -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.consumer.IConfiguration; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.IVfModuleMetadata; -import org.openecomp.sdc.api.results.IDistributionClientResult; -import org.openecomp.sdc.http.SdcConnectorClient; -import org.openecomp.sdc.http.TopicRegistrationResponse; -import org.openecomp.sdc.utils.ArtifactTypeEnum; -import org.openecomp.sdc.utils.ArtifactsUtils; -import org.openecomp.sdc.utils.DistributionActionResultEnum; -import org.openecomp.sdc.utils.TestConfiguration; -import org.openecomp.sdc.utils.TestNotificationCallback; -import org.openecomp.sdc.utils.Wrapper; - -import com.att.nsa.apiClient.credentials.ApiCredential; -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.cambria.client.CambriaClient.CambriaApiException; -import com.att.nsa.cambria.client.CambriaIdentityManager; - -import fj.data.Either; - -public class DistributionClientTest { - - static CambriaIdentityManager cc; - DistributionClientImpl client = Mockito.spy(new DistributionClientImpl()); - IConfiguration testConfiguration = new TestConfiguration(); - SdcConnectorClient connector = Mockito.mock(SdcConnectorClient.class); - - - @After - public void afterTest() { - client.stop(); - } - - @Test - public void validateConfigurationTest() { - DistributionActionResultEnum validationResult = client.validateAndInitConfiguration(new Wrapper(), testConfiguration); - Assert.assertEquals(DistributionActionResultEnum.SUCCESS, validationResult); - Assert.assertEquals(testConfiguration.getPollingInterval(), client.configuration.getPollingInterval()); - Assert.assertEquals(testConfiguration.getPollingTimeout(), client.configuration.getPollingTimeout()); - } - - @Test - public void validateConfigurationToDefaultTest() { - TestConfiguration userConfig = new TestConfiguration(); - userConfig.setPollingInterval(1); - userConfig.setPollingTimeout(2); - DistributionActionResultEnum validationResult = client.validateAndInitConfiguration(new Wrapper(), userConfig); - Assert.assertEquals(DistributionActionResultEnum.SUCCESS, validationResult); - Assert.assertEquals(15, client.configuration.getPollingInterval()); - Assert.assertEquals(15, client.configuration.getPollingTimeout()); - } - - @Test - public void validateConfigurationFqdnTest() { - - String[] validFqdns = { "myHostname", "myHostname:80", "myHostname:8080", "1.1.1.1", "1.1.1.1:8080", "ueb01hydc.it.open.com", "ueb01hydc.it.open.com:8080", "ueb01hydc.it", "my-good.and-simple.fqdn" }; - - String[] invalidFqdns = { "myHostname:808080", /* 70 letters */"abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij", "not**good", "very#not#good#" }; - - boolean validationResult = true; - - for (int i = 0; i < validFqdns.length; i++) { - validationResult = client.isValidFqdn(validFqdns[i]); - assertEquals("assertion failed for FQDN " + validFqdns[i] + " expected to be valid, actual invalid", true, validationResult); - } - - for (int i = 0; i < invalidFqdns.length; i++) { - validationResult = client.isValidFqdn(invalidFqdns[i]); - assertEquals("assertion failed for FQDN " + invalidFqdns[i] + " expected to be invalid, actual valid", false, validationResult); - } - - } - - @Test - public void validateConfigurationPasswordTest() { - Wrapper errorWrapper = new Wrapper<>(); - TestConfiguration testPassword = new TestConfiguration(); - testPassword.setPassword(null); - DistributionActionResultEnum validationResult = client.validateAndInitConfiguration(errorWrapper, testPassword); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_PASSWORD, validationResult); - - testPassword.setPassword(""); - validationResult = client.validateAndInitConfiguration(errorWrapper, testPassword); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_PASSWORD, validationResult); - - } - - @Test - public void validateConfigurationUserTest() { - Wrapper errorWrapper = new Wrapper<>(); - TestConfiguration testUser = new TestConfiguration(); - testUser.setUser(null); - DistributionActionResultEnum validationResult = client.validateAndInitConfiguration(errorWrapper, testUser); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_USERNAME, validationResult); - - testUser.setUser(""); - validationResult = client.validateAndInitConfiguration(errorWrapper, testUser); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_USERNAME, validationResult); - - } - - @Test - public void initWithMocksBadConfigurationTest() throws HttpException, CambriaApiException, IOException { - - - TopicRegistrationResponse topics = new TopicRegistrationResponse(); - topics.setDistrNotificationTopicName("notificationTopic"); - topics.setDistrStatusTopicName("statusTopic"); - Either topicsResult = Either.left(topics); - Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); - - client.asdcConnector = connector; - - // cambriaMock - - CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); - Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))).thenReturn(new ApiCredential("public", "secret")); - client.cambriaIdentityManager = cambriaMock; - - // no password - TestConfiguration testPassword = new TestConfiguration(); - testPassword.setPassword(null); - IDistributionClientResult validationResult = client.init(testPassword, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_PASSWORD, validationResult.getDistributionActionResult()); - - testPassword.setPassword(""); - validationResult = client.init(testPassword, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_PASSWORD, validationResult.getDistributionActionResult()); - - // no username - TestConfiguration testUser = new TestConfiguration(); - testUser.setUser(null); - validationResult = client.init(testUser, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_USERNAME, validationResult.getDistributionActionResult()); - - testUser.setUser(""); - validationResult = client.init(testUser, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_USERNAME, validationResult.getDistributionActionResult()); - - // no ASDC server fqdn - TestConfiguration testServerFqdn = new TestConfiguration(); - testServerFqdn.setAsdcAddress(null); - validationResult = client.init(testServerFqdn, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_ASDC_FQDN, validationResult.getDistributionActionResult()); - - testServerFqdn.setAsdcAddress(""); - validationResult = client.init(testServerFqdn, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_ASDC_FQDN, validationResult.getDistributionActionResult()); - - testServerFqdn.setAsdcAddress("this##is##bad##fqdn"); - validationResult = client.init(testServerFqdn, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_INVALID_ASDC_FQDN, validationResult.getDistributionActionResult()); - - // no consumerId - TestConfiguration testConsumerId = new TestConfiguration(); - testConsumerId.setComsumerID(null); - validationResult = client.init(testConsumerId, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_CONSUMER_ID, validationResult.getDistributionActionResult()); - - testConsumerId.setComsumerID(""); - validationResult = client.init(testConsumerId, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_CONSUMER_ID, validationResult.getDistributionActionResult()); - - // no environmentName - TestConfiguration testEnv = new TestConfiguration(); - testEnv.setEnvironmentName(null); - validationResult = client.init(testEnv, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_ENVIRONMENT_NAME, validationResult.getDistributionActionResult()); - - testEnv.setEnvironmentName(""); - validationResult = client.init(testEnv, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_ENVIRONMENT_NAME, validationResult.getDistributionActionResult()); - - Mockito.verify(client, Mockito.times(0)).getUEBServerList(); - Mockito.verify(cambriaMock, Mockito.times(0)).createApiKey(Mockito.anyString(), Mockito.anyString()); - Mockito.verify(connector, Mockito.times(0)).registerAsdcTopics(Mockito.any(ApiCredential.class)); - } - - @Test - public void initFailedConnectAsdcTest() throws HttpException, CambriaApiException, IOException { - // cambriaMock - - CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); - Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))).thenReturn(new ApiCredential("public", "secret")); - client.cambriaIdentityManager = cambriaMock; - - TestConfiguration badAsdcConfig = new TestConfiguration(); - badAsdcConfig.setAsdcAddress("badhost:8080"); - - IDistributionClientResult init = client.init(badAsdcConfig, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, init.getDistributionActionResult()); - - badAsdcConfig = new TestConfiguration(); - badAsdcConfig.setAsdcAddress("localhost:8181"); - - init = client.init(badAsdcConfig, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, init.getDistributionActionResult()); - - } - - @Test - public void getConfigurationTest() throws HttpException, CambriaApiException, IOException { - // connectorMock - mockArtifactTypeList(); - TopicRegistrationResponse topics = new TopicRegistrationResponse(); - topics.setDistrNotificationTopicName("notificationTopic"); - topics.setDistrStatusTopicName("statusTopic"); - Either topicsResult = Either.left(topics); - Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); - IDistributionClientResult success = initSuccesResult(); - Mockito.when(connector.unregisterTopics(Mockito.any(ApiCredential.class))).thenReturn(success); - - client.asdcConnector = connector; - - // cambriaMock - - CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); - Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))).thenReturn(new ApiCredential("public", "secret")); - client.cambriaIdentityManager = cambriaMock; - - TestConfiguration badAsdcConfig = new TestConfiguration(); - badAsdcConfig.setPollingInterval(-5); - - IDistributionClientResult init = client.init(badAsdcConfig, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.SUCCESS, init.getDistributionActionResult()); - - String confString = client.getConfiguration().toString(); - System.out.println(confString); - - } - - private IDistributionClientResult initSuccesResult() { - return new IDistributionClientResult() { - - @Override - public String getDistributionMessageResult() { - return "success"; - } - - @Override - public DistributionActionResultEnum getDistributionActionResult() { - return DistributionActionResultEnum.SUCCESS; - } - }; - } - - @Test - public void initWithMocksTest() throws HttpException, CambriaApiException, IOException { - - mockArtifactTypeList(); - - TopicRegistrationResponse topics = new TopicRegistrationResponse(); - topics.setDistrNotificationTopicName("notificationTopic"); - topics.setDistrStatusTopicName("statusTopic"); - Either topicsResult = Either.left(topics); - Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); - IDistributionClientResult success = initSuccesResult(); - Mockito.when(connector.unregisterTopics(Mockito.any(ApiCredential.class))).thenReturn(success); - - client.asdcConnector = connector; - - // cambriaMock - - CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); - Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))).thenReturn(new ApiCredential("public", "secret")); - client.cambriaIdentityManager = cambriaMock; - - IDistributionClientResult initResponse = client.init(testConfiguration, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.SUCCESS, initResponse.getDistributionActionResult()); - Mockito.verify(client, Mockito.times(1)).getUEBServerList(); - Mockito.verify(cambriaMock, Mockito.times(1)).createApiKey(Mockito.anyString(), Mockito.anyString()); - Mockito.verify(connector, Mockito.times(1)).registerAsdcTopics(Mockito.any(ApiCredential.class)); - System.out.println(initResponse); - } - - private void mockArtifactTypeList() { - List artifactTypes = new ArrayList<>(); - for (ArtifactTypeEnum artifactType : ArtifactTypeEnum.values()) { - artifactTypes.add(artifactType.name()); - } - - final Either, IDistributionClientResult> eitherArtifactTypes = Either.left(artifactTypes); - Mockito.when(connector.getValidArtifactTypesList()).thenReturn(eitherArtifactTypes); - } - - @Test - public void testAlreadyInitTest() throws HttpException, CambriaApiException, IOException { - initWithMocksTest(); - IDistributionClientResult initResponse = client.init(testConfiguration, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.DISTRIBUTION_CLIENT_ALREADY_INITIALIZED, initResponse.getDistributionActionResult()); - } - - @Test - public void initGetServerFailedTest() throws HttpException, CambriaApiException, IOException { - - // connectorMock - IDistributionClientResult getServersResult = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_SERVER_PROBLEM, "problem"); - Either, IDistributionClientResult> serversResult = Either.right(getServersResult); - doReturn(serversResult).when(client).getUEBServerList(); - - TopicRegistrationResponse topics = new TopicRegistrationResponse(); - topics.setDistrNotificationTopicName("notificationTopic"); - topics.setDistrStatusTopicName("statusTopic"); - Either topicsResult = Either.left(topics); - Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); - - client.asdcConnector = connector; - - // cambriaMock - - CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); - Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))).thenReturn(new ApiCredential("public", "secret")); - client.cambriaIdentityManager = cambriaMock; - - IDistributionClientResult initResponse = client.init(testConfiguration, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.ASDC_SERVER_PROBLEM, initResponse.getDistributionActionResult()); - - Mockito.verify(client, Mockito.times(1)).getUEBServerList(); - Mockito.verify(cambriaMock, Mockito.times(0)).createApiKey(Mockito.anyString(), Mockito.anyString()); - Mockito.verify(connector, Mockito.times(0)).registerAsdcTopics(Mockito.any(ApiCredential.class)); - - System.out.println(initResponse); - } - - @Test - public void initCreateKeysFailedTest() throws HttpException, CambriaApiException, IOException { - - // connectorMock - mockArtifactTypeList(); - - TopicRegistrationResponse topics = new TopicRegistrationResponse(); - topics.setDistrNotificationTopicName("notificationTopic"); - topics.setDistrStatusTopicName("statusTopic"); - Either topicsResult = Either.left(topics); - Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); - - client.asdcConnector = connector; - - // cambriaMock - - CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); - Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))).thenThrow(new CambriaApiException("failure")); - client.cambriaIdentityManager = cambriaMock; - - IDistributionClientResult initResponse = client.init(testConfiguration, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.UEB_KEYS_CREATION_FAILED, initResponse.getDistributionActionResult()); - - Mockito.verify(client, Mockito.times(1)).getUEBServerList(); - Mockito.verify(cambriaMock, Mockito.times(1)).createApiKey(Mockito.anyString(), Mockito.anyString()); - Mockito.verify(connector, Mockito.times(0)).registerAsdcTopics(Mockito.any(ApiCredential.class)); - System.out.println(initResponse); - } - - @Test - public void initRegistrationFailedTest() throws HttpException, CambriaApiException, IOException { - - // connectorMock - mockArtifactTypeList(); - DistributionClientResultImpl failureResult = new DistributionClientResultImpl(DistributionActionResultEnum.BAD_REQUEST, "Bad Request"); - Either topicsResult = Either.right(failureResult); - Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); - - client.asdcConnector = connector; - - // cambriaMock - - CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); - Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))).thenReturn(new ApiCredential("public", "secret")); - client.cambriaIdentityManager = cambriaMock; - - IDistributionClientResult initResponse = client.init(testConfiguration, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.BAD_REQUEST, initResponse.getDistributionActionResult()); - Mockito.verify(client, Mockito.times(1)).getUEBServerList(); - Mockito.verify(cambriaMock, Mockito.times(1)).createApiKey(Mockito.anyString(), Mockito.anyString()); - Mockito.verify(connector, Mockito.times(1)).registerAsdcTopics(Mockito.any(ApiCredential.class)); - System.out.println(initResponse); - } - - @Test - public void testStartWithoutInit() { - IDistributionClientResult result = client.start(); - assertTrue(result.getDistributionActionResult() == DistributionActionResultEnum.DISTRIBUTION_CLIENT_NOT_INITIALIZED); - } - - private IArtifactInfo initArtifactInfo() { - ArtifactInfoImpl artifactInfo = new ArtifactInfoImpl(); - artifactInfo.setArtifactURL("/sdc/v1/services/serviceName/0.1/artifacts/aaa.hh"); - artifactInfo.setArtifactChecksum(ArtifactsUtils.getValidChecksum()); - return artifactInfo; - } - - // ########### TESTS TO ADD TO CI START ########### - /*public void createKeysTestCI() throws MalformedURLException, GeneralSecurityException { - validateConfigurationTest(); - CambriaIdentityManager trueCambria = new CambriaClientBuilders.IdentityManagerBuilder().usingHttps().usingHosts(serverList).build(); - client.cambriaIdentityManager = trueCambria; - DistributionClientResultImpl keysResult = client.createUebKeys(); - Assert.assertEquals(DistributionActionResultEnum.SUCCESS, keysResult.getDistributionActionResult()); - Assert.assertFalse(client.credential.getApiKey().isEmpty()); - Assert.assertFalse(client.credential.getApiSecret().isEmpty()); - - System.out.println(keysResult); - System.out.println("keys: public=" + client.credential.getApiKey() + " | secret=" + client.credential.getApiSecret()); - } -*/ - public void initTestCI() { - IDistributionClient distributionClient = DistributionClientFactory.createDistributionClient(); - IDistributionClientResult init = distributionClient.init(testConfiguration, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.SUCCESS, init.getDistributionActionResult()); - - } - - @Test - public void testDecodeVfModuleArtifact() throws IOException{ - String vfModuleContent = getVFModuleExample(); - List decodeVfModuleArtifact = client.decodeVfModuleArtifact(vfModuleContent.getBytes()); - assertTrue(decodeVfModuleArtifact.size() == 1); - IVfModuleMetadata iVfModuleMetadata = decodeVfModuleArtifact.get(0); - assertTrue(iVfModuleMetadata.getArtifacts().size() == 11); - assertEquals(iVfModuleMetadata.getVfModuleModelName(), "Vccfdb..base_vDB_11032016..module-0"); - } - - private String getVFModuleExample() { - return "[\r\n" + - " {\r\n" + - " \"vfModuleModelName\": \"Vccfdb..base_vDB_11032016..module-0\",\r\n" + - " \"vfModuleModelInvariantUUID\": \"89bcc10e-84f9-475a-b7e3-bdac6cd2b31a\",\r\n" + - " \"vfModuleModelVersion\": \"1\",\r\n" + - " \"vfModuleModelUUID\": \"f7e1c7aa-cc7b-4dfc-b761-237e8063bd96\",\r\n" + - " \"GuguBubu\": true,\r\n" + - " \"isBase\": true,\r\n" + - " \"artifacts\": [\r\n" + - " \"68733000-7656-487c-aecb-040af96df5a5\",\r\n" + - " \"d3519bb4-be98-4c04-8815-4557379fdff3\",\r\n" + - " \"b445d84b-de23-4f0c-a0aa-8d794d85bebe\",\r\n" + - " \"52a6656a-63f4-4ae8-80f4-40febcaa15d6\",\r\n" + - " \"fdcf20b5-1bac-4da7-9e77-b0b565115027\",\r\n" + - " \"d3fcfd98-941c-4627-8b94-386dd3eab1ab\",\r\n" + - " \"bdd6c2b6-793b-49d7-8590-51e7d6998f69\",\r\n" + - " \"554a62b0-3a56-4c29-bc5e-23badf6da67f\",\r\n" + - " \"4b922d87-f2c9-44da-b933-57a91294fb42\",\r\n" + - " \"ad5cceda-0fa4-415e-b319-96f080e4b5c7\",\r\n" + - " \"8f4312f4-7be5-4d64-a3f5-564be7a0f01e\"\r\n" + - " ]\r\n" + - " }\r\n" + - "]"; - } - - - - public void connectorRegisterCI() { - SdcConnectorClient connector = new SdcConnectorClient(); - connector.init(testConfiguration); - - ApiCredential creds = new ApiCredential("publicKey", "secretKey"); - Either topicsFromAsdc = connector.registerAsdcTopics(creds); - assertTrue(topicsFromAsdc.isLeft()); - - } - - public void downloadArtifactTestCI() { - SdcConnectorClient connector = new SdcConnectorClient(); - connector.init(testConfiguration); - IArtifactInfo artifactInfo = initArtifactInfo(); - connector.dowloadArtifact(artifactInfo); - - } - // ########### TESTS TO ADD TO CI END ########### - -} diff --git a/sdc-distribution-client/src/test/java/org/openecomp/sdc/impl/HeatParserTest.java b/sdc-distribution-client/src/test/java/org/openecomp/sdc/impl/HeatParserTest.java deleted file mode 100644 index 3b5b1a1..0000000 --- a/sdc-distribution-client/src/test/java/org/openecomp/sdc/impl/HeatParserTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.net.URL; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Test; -import org.openecomp.sdc.utils.heat.HeatParameter; -import org.openecomp.sdc.utils.heat.HeatParameterConstraint; -import org.openecomp.sdc.utils.heat.HeatParser; - -import com.google.common.base.Charsets; -import com.google.common.io.Resources; - -public class HeatParserTest { - - @Test - public void testParametersParsing() throws IOException{ - String resourceName = "heatExample.yaml"; - URL url = Resources.getResource(resourceName); - String heatFileContents = Resources.toString(url, Charsets.UTF_8); - assertNotNull("Didn't find "+resourceName, heatFileContents); - - HeatParser heatParser = new HeatParser(); - //Flat parameter entry - Map parameters = heatParser.getHeatParameters(heatFileContents); - HeatParameter heatParameter1 = parameters.get("image_name_1"); - validateField("string", heatParameter1.getType(), "type"); - validateField("Image Name", heatParameter1.getLabel(), "label"); - validateField("SCOIMAGE Specify an image name for instance1", heatParameter1.getDescription(), "description"); - validateField("cirros-0.3.1-x86_64", heatParameter1.getDefault(), "default"); - validateField(null, heatParameter1.getConstraints(), "constraints"); - validateField("false", heatParameter1.getHidden(), "hidden"); - - - //Flat parameter entry with constraints - heatParameter1 = parameters.get("network_id"); - validateField("string", heatParameter1.getType(), "type"); - validateField("Network ID", heatParameter1.getLabel(), "label"); - validateField("SCONETWORK Network to be used for the compute instance", heatParameter1.getDescription(), "description"); - validateField(null, heatParameter1.getDefault(), "default"); - validateField("true", heatParameter1.getHidden(), "hidden"); - - //Constraints - List constraints = heatParameter1.getConstraints(); - assertEquals("Number of constraints", 6, constraints.size()); - - //Length - HeatParameterConstraint lengthConstraint = heatParameter1.getLengthConstraint(); - assertNotNull(lengthConstraint); - Map expectedMap = new HashMap<>(); - expectedMap.put("min", "6"); - expectedMap.put("max", "8"); - validateField(expectedMap, lengthConstraint.getLength(), "length"); - validateField("Password length must be between 6 and 8 characters.", lengthConstraint.getDescription(), "length description"); - - //Range - HeatParameterConstraint rangeConstraint = heatParameter1.getRangeConstraint(); - assertNotNull(rangeConstraint); - validateField(expectedMap, rangeConstraint.getRange(), "range"); - validateField("Range description", rangeConstraint.getDescription(), "range description"); - - //Allowed values - HeatParameterConstraint allowedValues = heatParameter1.getAllowedValuesConstraint(); - assertNotNull(allowedValues); - List expectedValues = new ArrayList<>(); - expectedValues.add("m1.small"); - expectedValues.add("m1.medium"); - expectedValues.add("m1.large"); - validateField(expectedValues, allowedValues.getAllowed_values(), "allowed_values"); - validateField("Allowed values description", allowedValues.getDescription(), "allowed_values description"); - - //Allowed pattern - List allowedPatternList = heatParameter1.getAllowedPatternConstraint(); - assertNotNull(allowedPatternList); - assertEquals("Allowed pattern list", 2, allowedPatternList.size()); - HeatParameterConstraint allowedPattern = allowedPatternList.get(0); - validateField("[a-zA-Z0-9]+", allowedPattern.getAllowed_pattern(), "allowed_pattern"); - validateField("Password must consist of characters and numbers only.", allowedPattern.getDescription(), "allowed_pattern description"); - allowedPattern = allowedPatternList.get(1); - validateField("[A-Z]+[a-zA-Z0-9]*", allowedPattern.getAllowed_pattern(), "allowed_pattern"); - validateField("Password must start with an uppercase character.", allowedPattern.getDescription(), "allowed_pattern description"); - - //Custom constraint - List customConstraintList = heatParameter1.getCustomConstraintConstraint(); - assertNotNull(customConstraintList); - assertEquals("Custom constraint list", 1, customConstraintList.size()); - HeatParameterConstraint customConstraint = customConstraintList.get(0); - validateField("nova.keypair", customConstraint.getCustom_constraint(), "custom_constraint"); - validateField("Custom description", customConstraint.getDescription(), "custom_constraint description"); - } - - @Test - public void testParametersParsingInvalidYaml() throws IOException{ - String invalidHeatFileContents = "just text"; - HeatParser heatParser = new HeatParser(); - //Flat parameter entry - Map parameters = heatParser.getHeatParameters(invalidHeatFileContents); - assertNull(parameters); - } - - @Test - public void testParametersParsingNoParamteresSection() throws IOException{ - String heatFileContentsNoParams = "heat_template_version: 2013-05-23\r\n\r\ndescription: Simple template to deploy a stack with two virtual machine instances"; - HeatParser heatParser = new HeatParser(); - //Flat parameter entry - Map parameters = heatParser.getHeatParameters(heatFileContentsNoParams); - assertNull(parameters); - } - - private void validateField(Object expected, Object actual, String type){ - assertEquals("Field of type "+type+":", expected, actual); - } -} diff --git a/sdc-distribution-client/src/test/java/org/openecomp/sdc/impl/NotificationConsumerTest.java b/sdc-distribution-client/src/test/java/org/openecomp/sdc/impl/NotificationConsumerTest.java deleted file mode 100644 index 7fe125b..0000000 --- a/sdc-distribution-client/src/test/java/org/openecomp/sdc/impl/NotificationConsumerTest.java +++ /dev/null @@ -1,352 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.impl; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import org.eclipse.jetty.util.ArrayQueue; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.openecomp.sdc.api.consumer.INotificationCallback; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.results.IDistributionClientResult; -import org.openecomp.sdc.utils.ArtifactTypeEnum; -import org.openecomp.sdc.utils.DistributionActionResultEnum; -import org.openecomp.sdc.utils.DistributionClientConstants; -import org.openecomp.sdc.utils.TestConfiguration; - -import com.att.nsa.cambria.client.CambriaConsumer; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -public class NotificationConsumerTest { - private CambriaConsumer cambriaConsumer = mock(CambriaConsumer.class); - private INotificationCallback clientCallback = spy(INotificationCallback.class); - private Queue> notificationsQueue = new ArrayQueue<>(100); - private DistributionClientImpl distributionClient = spy(DistributionClientImpl.class); - private List artifactsTypes = Arrays.asList(ArtifactTypeEnum.HEAT.name()); - private List notificationStatusResults = new ArrayList<>(); - final static IDistributionClientResult DISTRIBUTION_SUCCESS_RESULT = buildSuccessResult(); - - private NotificationConsumer createNotificationConsumer() { - return new NotificationConsumer(cambriaConsumer, clientCallback, artifactsTypes, distributionClient); - } - - @Before - public void beforeTest() throws IOException { - Mockito.reset(clientCallback, distributionClient); - when(cambriaConsumer.fetch()).then(new Answer>() { - @Override - public Iterable answer(InvocationOnMock invocation) throws Throwable { - if (!notificationsQueue.isEmpty()) { - return notificationsQueue.remove(); - } else { - return new ArrayList<>(); - } - } - }); - when(distributionClient.sendNotificationStatus(Mockito.anyLong(), Mockito.anyString(), Mockito.any(ArtifactInfoImpl.class), Mockito.anyBoolean())).then(new Answer() { - @Override - public IDistributionClientResult answer(InvocationOnMock invocation) throws Throwable { - boolean isNotified = (boolean) invocation.getArguments()[3]; - notificationStatusResults.add(Boolean.valueOf(isNotified)); - return DISTRIBUTION_SUCCESS_RESULT; - } - }); - - } - - private static IDistributionClientResult buildSuccessResult() { - return new IDistributionClientResult() { - - @Override - public String getDistributionMessageResult() { - return ""; - } - - @Override - public DistributionActionResultEnum getDistributionActionResult() { - return DistributionActionResultEnum.SUCCESS; - } - }; - } - - @Test - public void testNoNotifiactionsSent() throws InterruptedException { - - ScheduledExecutorService executorPool = Executors.newScheduledThreadPool(DistributionClientConstants.POOL_SIZE); - executorPool.scheduleAtFixedRate(createNotificationConsumer(), 0, 100, TimeUnit.MILLISECONDS); - - Thread.sleep(1000); - executorPool.shutdown(); - - Mockito.verify(clientCallback, Mockito.times(0)).activateCallback(Mockito.any(INotificationData.class)); - - } - - @Test - public void testNonRelevantNotificationSent() throws InterruptedException { - - simulateNotificationFromUEB(getAsdcServiceNotificationWithoutHeatArtifact()); - Mockito.verify(clientCallback, Mockito.times(0)).activateCallback(Mockito.any(INotificationData.class)); - - } - - @Test - public void testRelevantNotificationSent() throws InterruptedException { - simulateNotificationFromUEB(getAsdcServiceNotificationWithHeatArtifact()); - Mockito.verify(clientCallback, Mockito.times(1)).activateCallback(Mockito.any(INotificationData.class)); - - } - - @Test - public void testNonExistingArtifactsNotificationSent() throws InterruptedException { - simulateNotificationFromUEB(getAsdcNotificationWithNonExistentArtifact()); - Mockito.verify(clientCallback, Mockito.times(1)).activateCallback(Mockito.any(INotificationData.class)); - - } - - @Test - public void testNotificationStatusSent() throws InterruptedException { - simulateNotificationFromUEB(getAsdcServiceNotificationWithHeatArtifact()); - - Mockito.verify(distributionClient, Mockito.times(3)).sendNotificationStatus(Mockito.anyLong(), Mockito.anyString(), Mockito.any(ArtifactInfoImpl.class), Mockito.anyBoolean()); - assertTrue(countInstances(notificationStatusResults, Boolean.TRUE) == 1); - assertTrue(countInstances(notificationStatusResults, Boolean.FALSE) == 2); - } - - @Test - public void testNotificationRelatedArtifacts() throws InterruptedException { - List artifactTypesTmp = new ArrayList<>(); - for (ArtifactTypeEnum artifactTypeEnum : ArtifactTypeEnum.values()) { - artifactTypesTmp.add(artifactTypeEnum.name()); - } - artifactsTypes = artifactTypesTmp; - simulateNotificationFromUEB(getAsdcServiceNotificationWithRelatedArtifacts()); - - Mockito.verify(distributionClient, Mockito.times(3)).sendNotificationStatus(Mockito.anyLong(), Mockito.anyString(), Mockito.any(ArtifactInfoImpl.class), Mockito.anyBoolean()); - assertTrue(countInstances(notificationStatusResults, Boolean.TRUE) == 3); - assertTrue(countInstances(notificationStatusResults, Boolean.FALSE) == 0); - } - - @Test - public void testNotificationStatusWithServiceArtifatcs() throws InterruptedException { - simulateNotificationFromUEB(getNotificationWithServiceArtifatcs()); - Mockito.verify(distributionClient, Mockito.times(6)).sendNotificationStatus(Mockito.anyLong(), Mockito.anyString(), Mockito.any(ArtifactInfoImpl.class), Mockito.anyBoolean()); - assertTrue(countInstances(notificationStatusResults, Boolean.TRUE) == 2); - assertTrue(countInstances(notificationStatusResults, Boolean.FALSE) == 4); - - } - - @Test - public final void testBuildCallbackNotificationLogicFlagIsFalse() { - NotificationConsumer consumer = createNotificationConsumer(); - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - TestConfiguration testConfiguration = new TestConfiguration(); - testConfiguration.setFilterInEmptyResources(false); - when(distributionClient.getConfiguration()).thenReturn(testConfiguration); - NotificationDataImpl notification = gson.fromJson(getNotificationWithMultipleResources(), NotificationDataImpl.class); - NotificationDataImpl notificationBuiltInClient = consumer.buildCallbackNotificationLogic(0, notification); - assertTrue(notificationBuiltInClient.getResources().size() == 1); - } - - @Test - public final void testBuildCallbackNotificationLogicFlagIsTrue() { - NotificationConsumer consumer = createNotificationConsumer(); - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - TestConfiguration testConfiguration = new TestConfiguration(); - testConfiguration.setFilterInEmptyResources(true); - when(distributionClient.getConfiguration()).thenReturn(testConfiguration); - NotificationDataImpl notification = gson.fromJson(getNotificationWithMultipleResources(), NotificationDataImpl.class); - NotificationDataImpl notificationBuiltInClient = consumer.buildCallbackNotificationLogic(0, notification); - assertTrue(notificationBuiltInClient.getResources().size() == 2); - } - - private void simulateNotificationFromUEB(final String notificationFromUEB) throws InterruptedException { - ScheduledExecutorService executorPool = Executors.newScheduledThreadPool(DistributionClientConstants.POOL_SIZE); - executorPool.scheduleAtFixedRate(createNotificationConsumer(), 0, 100, TimeUnit.MILLISECONDS); - - Thread.sleep(200); - - List nonHeatNotification = Arrays.asList(notificationFromUEB); - notificationsQueue.add(nonHeatNotification); - Thread.sleep(800); - executorPool.shutdown(); - } - - private String getAsdcServiceNotificationWithHeatArtifact() { - return "{\"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + " \"serviceName\" : \"Testnotificationser1\",\r\n" + " \"serviceVersion\" : \"1.0\",\r\n" - + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" + " \"resources\" : [{\r\n" + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" - + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + " \"resourceVersion\" : \"1.0\",\r\n" + " \"resoucreType\" : \"VF\",\r\n" + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" - + " \"artifacts\" : [{\r\n" + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" + " \"artifactType\" : \"YANG_XML\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" - + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" + " \"artifactDescription\" : \"MyYang\",\r\n" + " \"artifactTimeout\" : 0,\r\n" - + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" - + " \"artifactType\" : \"HEAT\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" - + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" - + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.env\",\r\n" - + " \"artifactType\" : \"HEAT_ENV\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" - + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" - + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" - + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ]\r\n" + " }\r\n" + " ]}"; - } - - private String getNotificationWithMultipleResources(){ - return "{\"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + - " \"serviceName\" : \"Testnotificationser1\",\r\n" + - " \"serviceVersion\" : \"1.0\",\r\n" + - " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + - " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" + - " \"resources\" : [{\r\n" + - " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" + - " \"resourceName\" : \"TestNotificationVF1\",\r\n" + - " \"resourceVersion\" : \"1.0\",\r\n" + - " \"resoucreType\" : \"VF\",\r\n" + - " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" + - " \"artifacts\" : [{\r\n" + - " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" + - " \"artifactType\" : \"YANG_XML\",\r\n" + - " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" + - " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" + - " \"artifactDescription\" : \"MyYang\",\r\n" + - " \"artifactTimeout\" : 0,\r\n" + - " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + - " \"artifactVersion\" : \"1\"\r\n" + - " }" + - " ]\r\n" + - " },\r\n" + - " {\r\n" + - " \"resourceInstanceName\" : \"testnotificationvf12\",\r\n" + - " \"resourceName\" : \"TestNotificationVF1\",\r\n" + - " \"resourceVersion\" : \"1.0\",\r\n" + - " \"resoucreType\" : \"VF\",\r\n" + - " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2e\",\r\n" + - " \"artifacts\" : [{\r\n" + - " \"artifactName\" : \"heat.yaml\",\r\n" + - " \"artifactType\" : \"HEAT\",\r\n" + - " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" + - " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + - " \"artifactDescription\" : \"heat\",\r\n" + - " \"artifactTimeout\" : 60,\r\n" + - " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + - " \"artifactVersion\" : \"1\"\r\n" + - " }" + - " ]\r\n" + - " }\r\n" + - " ]}"; - } - - - private String getAsdcNotificationWithNonExistentArtifact() { - return "{\"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + " \"serviceName\" : \"Testnotificationser1\",\r\n" + " \"serviceVersion\" : \"1.0\",\r\n" - + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" + " \"bugabuga\" : \"xyz\",\r\n" + " \"resources\" : [{\r\n" - + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + " \"resourceVersion\" : \"1.0\",\r\n" + " \"resoucreType\" : \"VF\",\r\n" - + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" + " \"artifacts\" : [{\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" + " \"artifactType\" : \"HEAT\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" - + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" - + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactBuga\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" - + " }, {\r\n" + " \"artifactName\" : \"buga.bug\",\r\n" + " \"artifactType\" : \"BUGA_BUGA\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" - + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" - + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" - + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ]\r\n" + " }\r\n" + " ]}"; - } - - private String getAsdcServiceNotificationWithRelatedArtifacts() { - return "{\"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + " \"serviceName\" : \"Testnotificationser1\",\r\n" + " \"serviceVersion\" : \"1.0\",\r\n" - + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" + " \"resources\" : [{\r\n" + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" - + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + " \"resourceVersion\" : \"1.0\",\r\n" + " \"resoucreType\" : \"VF\",\r\n" + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" - + " \"artifacts\" : [{\r\n" + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" + " \"artifactType\" : \"YANG_XML\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" - + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" + " \"artifactDescription\" : \"MyYang\",\r\n" + " \"artifactTimeout\" : 0,\r\n" - + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" + " \"relatedArtifacts\" : [\r\n" - + " \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\"\r\n" + " ]" + " }, {\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" - + " \"artifactType\" : \"HEAT\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" - + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" - + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\", \r\n" + " \"relatedArtifacts\" : [\r\n" - + " \"0005bc4a-2c19-452e-be6d-d574a56be4d0\", \r\n" + " \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\"\r\n" + " ]" + " }, {\r\n" - + " \"artifactName\" : \"heat.env\",\r\n" + " \"artifactType\" : \"HEAT_ENV\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" - + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" - + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" - + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ]\r\n" + " }\r\n" + " ]}"; - } - - private String getAsdcServiceNotificationWithoutHeatArtifact() { - return "{" + " \"distributionID\" : \"5v1234d8-5b6d-42c4-7t54-47v95n58qb7\"," + " \"serviceName\" : \"srv1\"," + " \"serviceVersion\": \"2.0\"," + " \"serviceUUID\" : \"4e0697d8-5b6d-42c4-8c74-46c33d46624c\"," - + " \"serviceArtifacts\":[" + " {" + " \"artifactName\" : \"ddd.yml\"," + " \"artifactType\" : \"DG_XML\"," + " \"artifactTimeout\" : \"65\"," - + " \"artifactDescription\" : \"description\"," + " \"artifactURL\" :" + " \"/sdc/v1/catalog/services/srv1/2.0/resources/ddd/3.0/artifacts/ddd.xml\" ," - + " \"resourceUUID\" : \"4e5874d8-5b6d-42c4-8c74-46c33d90drw\" ," + " \"checksum\" : \"15e389rnrp58hsw==\"" + " }" + " ]" + "}"; - } - - private String getNotificationWithServiceArtifatcs() { - return "{\r\n" + " \"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + " \"serviceName\" : \"Testnotificationser1\",\r\n" + " \"serviceVersion\" : \"1.0\",\r\n" - + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" + " \"serviceArtifacts\" : [{\r\n" + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" - + " \"artifactType\" : \"YANG_XML\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" - + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" + " \"artifactDescription\" : \"MyYang\",\r\n" + " \"artifactTimeout\" : 0,\r\n" - + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" - + " \"artifactType\" : \"HEAT\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" - + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" - + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.env\",\r\n" - + " \"artifactType\" : \"HEAT_ENV\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" - + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" - + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" - + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ],\r\n" + " \"resources\" : [{\r\n" + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" - + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + " \"resourceVersion\" : \"1.0\",\r\n" + " \"resoucreType\" : \"VF\",\r\n" + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" - + " \"artifacts\" : [{\r\n" + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" + " \"artifactType\" : \"YANG_XML\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" - + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" + " \"artifactDescription\" : \"MyYang\",\r\n" + " \"artifactTimeout\" : 0,\r\n" - + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" - + " \"artifactType\" : \"HEAT\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" - + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" - + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.env\",\r\n" - + " \"artifactType\" : \"HEAT_ENV\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" - + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" - + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" - + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ]\r\n" + " }\r\n" + " ]\r\n" + "}"; - } - - private int countInstances(List list, T element) { - int count = 0; - for (T curr : list) { - if (curr.equals(element)) { - count++; - } - } - return count; - } -} diff --git a/sdc-distribution-client/src/test/java/org/openecomp/sdc/utils/ArtifactsUtils.java b/sdc-distribution-client/src/test/java/org/openecomp/sdc/utils/ArtifactsUtils.java deleted file mode 100644 index 5a24849..0000000 --- a/sdc-distribution-client/src/test/java/org/openecomp/sdc/utils/ArtifactsUtils.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.utils; - - - -import org.apache.commons.codec.binary.Base64; -import org.openecomp.sdc.impl.mock.DistributionClientDownloadResultStubImpl; -import org.openecomp.sdc.utils.GeneralUtils; - - - -public class ArtifactsUtils { - static DistributionClientDownloadResultStubImpl distributionClientDownloadResultStubImpl = new DistributionClientDownloadResultStubImpl(); - - public static byte [] getArtifactPayload(){ - return distributionClientDownloadResultStubImpl.getArtifactPayload(); - } - - public static String getValidChecksum(){ - - String payloadStr = new String(distributionClientDownloadResultStubImpl.getArtifactPayload()); - - byte[] decodedPayload = Base64.decodeBase64(payloadStr); - String checkSum = GeneralUtils.calculateMD5 (new String(decodedPayload)); - - return checkSum; - } - -} diff --git a/sdc-distribution-client/src/test/java/org/openecomp/sdc/utils/TestConfiguration.java b/sdc-distribution-client/src/test/java/org/openecomp/sdc/utils/TestConfiguration.java deleted file mode 100644 index 22814f4..0000000 --- a/sdc-distribution-client/src/test/java/org/openecomp/sdc/utils/TestConfiguration.java +++ /dev/null @@ -1,299 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.utils; - -import java.util.ArrayList; -import java.util.List; - -import org.openecomp.sdc.api.consumer.IConfiguration; - -public class TestConfiguration implements IConfiguration { - - private String asdcAddress; - private String user; - private String password; - private int pollingInterval = DistributionClientConstants.MIN_POLLING_INTERVAL_SEC; - private int pollingTimeout = DistributionClientConstants.POLLING_TIMEOUT_SEC; - private List relevantArtifactTypes; - private String consumerGroup; - private String environmentName; - private String comsumerID; - private String keyStorePath; - private String keyStorePassword; - private boolean activateServerTLSAuth; - private boolean isFilterInEmptyResources; - private boolean useHttpsWithDmaap; - private List msgBusAddress; - - public TestConfiguration(IConfiguration other) { - this.asdcAddress = other.getAsdcAddress(); - this.comsumerID = other.getConsumerID(); - this.consumerGroup = other.getConsumerGroup(); - this.environmentName = other.getEnvironmentName(); - this.password = other.getPassword(); - this.pollingInterval = other.getPollingInterval(); - this.pollingTimeout = other.getPollingTimeout(); - this.relevantArtifactTypes = other.getRelevantArtifactTypes(); - this.user = other.getUser(); - this.keyStorePath = other.getKeyStorePath(); - this.keyStorePassword = other.getKeyStorePassword(); - this.activateServerTLSAuth = other.activateServerTLSAuth(); - this.isFilterInEmptyResources = other.isFilterInEmptyResources(); - } - - public TestConfiguration() { - this.asdcAddress = "localhost:8443"; - this.comsumerID = "mso-123456"; - this.consumerGroup = "mso-group"; - this.environmentName = "PROD"; - this.password = "password"; - this.pollingInterval = 20; - this.pollingTimeout = 20; - this.relevantArtifactTypes = new ArrayList(); - this.relevantArtifactTypes.add(ArtifactTypeEnum.HEAT.name()); - this.user = "mso-user"; - this.keyStorePath = "etc/asdc-client.jks"; - this.keyStorePassword = "Aa123456"; - this.activateServerTLSAuth = false; - this.isFilterInEmptyResources = false; - msgBusAddress = new ArrayList(); - msgBusAddress.add("www.cnn.com"); - msgBusAddress.add("www.cnn.com"); - msgBusAddress.add("www.cnn.com"); - } - - @Override - public String getAsdcAddress() { - return asdcAddress; - } - - @Override - public List getMsgBusAddress() { - return msgBusAddress; - } - - @Override - public String getUser() { - return user; - } - - @Override - public String getPassword() { - return password; - } - - @Override - public int getPollingInterval() { - return pollingInterval; - } - - @Override - public int getPollingTimeout() { - return pollingTimeout; - } - - @Override - public List getRelevantArtifactTypes() { - return relevantArtifactTypes; - } - - @Override - public String getConsumerGroup() { - return consumerGroup; - } - - @Override - public String getEnvironmentName() { - return environmentName; - } - - @Override - public String getConsumerID() { - return comsumerID; - } - - @Override - public String getKeyStorePath() { - return keyStorePath; - } - - @Override - public String getKeyStorePassword() { - return keyStorePassword; - } - - public String getComsumerID() { - return comsumerID; - } - - public void setComsumerID(String comsumerID) { - this.comsumerID = comsumerID; - } - - public void setAsdcAddress(String asdcAddress) { - this.asdcAddress = asdcAddress; - } - - public void setUser(String user) { - this.user = user; - } - - public void setPassword(String password) { - this.password = password; - } - - public void setPollingInterval(int pollingInterval) { - this.pollingInterval = pollingInterval; - } - - public void setPollingTimeout(int pollingTimeout) { - this.pollingTimeout = pollingTimeout; - } - - public void setRelevantArtifactTypes(List relevantArtifactTypes) { - this.relevantArtifactTypes = relevantArtifactTypes; - } - - public void setConsumerGroup(String consumerGroup) { - this.consumerGroup = consumerGroup; - } - - public void setEnvironmentName(String environmentName) { - this.environmentName = environmentName; - } - - public void setKeyStorePath(String keyStorePath) { - this.keyStorePath = keyStorePath; - } - - public void setKeyStorePassword(String keyStorePassword) { - this.keyStorePassword = keyStorePassword; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((asdcAddress == null) ? 0 : asdcAddress.hashCode()); - result = prime * result + ((comsumerID == null) ? 0 : comsumerID.hashCode()); - result = prime * result + ((consumerGroup == null) ? 0 : consumerGroup.hashCode()); - result = prime * result + ((environmentName == null) ? 0 : environmentName.hashCode()); - result = prime * result + ((password == null) ? 0 : password.hashCode()); - result = prime * result + pollingInterval; - result = prime * result + pollingTimeout; - result = prime * result + ((relevantArtifactTypes == null) ? 0 : relevantArtifactTypes.hashCode()); - result = prime * result + ((user == null) ? 0 : user.hashCode()); - return result; - } - - @Override - public boolean activateServerTLSAuth() { - - return activateServerTLSAuth; - } - - public void setactivateServerTLSAuth(boolean activateServerTLSAuth) { - this.activateServerTLSAuth = activateServerTLSAuth; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - TestConfiguration other = (TestConfiguration) obj; - if (asdcAddress == null) { - if (other.asdcAddress != null) - return false; - } else if (!asdcAddress.equals(other.asdcAddress)) - return false; - if (comsumerID == null) { - if (other.comsumerID != null) - return false; - } else if (!comsumerID.equals(other.comsumerID)) - return false; - if (consumerGroup == null) { - if (other.consumerGroup != null) - return false; - } else if (!consumerGroup.equals(other.consumerGroup)) - return false; - if (environmentName == null) { - if (other.environmentName != null) - return false; - } else if (!environmentName.equals(other.environmentName)) - return false; - if (password == null) { - if (other.password != null) - return false; - } else if (!password.equals(other.password)) - return false; - if (pollingInterval != other.pollingInterval) - return false; - if (pollingTimeout != other.pollingTimeout) - return false; - if (relevantArtifactTypes == null) { - if (other.relevantArtifactTypes != null) - return false; - } else if (!relevantArtifactTypes.equals(other.relevantArtifactTypes)) - return false; - if (user == null) { - if (other.user != null) - return false; - } else if (!user.equals(other.user)) - return false; - if (keyStorePath == null) { - if (other.keyStorePath != null) - return false; - } else if (!keyStorePath.equals(other.keyStorePath)) - return false; - if (keyStorePassword == null) { - if (other.keyStorePassword != null) - return false; - } else if (!keyStorePassword.equals(other.keyStorePassword)) - return false; - - return true; - } - - @Override - public String toString() { - return "TestConfiguration [asdcAddress=" + asdcAddress + ", user=" + user + ", password=" + password + ", pollingInterval=" + pollingInterval + ", pollingTimeout=" + pollingTimeout + ", relevantArtifactTypes=" + relevantArtifactTypes - + ", consumerGroup=" + consumerGroup + ", environmentName=" + environmentName + ", comsumerID=" + comsumerID + "]"; - } - - @Override - public boolean isFilterInEmptyResources() { - return isFilterInEmptyResources; - } - - - public void setFilterInEmptyResources(boolean isFilterInEmptyResources) { - this.isFilterInEmptyResources = isFilterInEmptyResources; - } - - @Override - public Boolean isUseHttpsWithDmaap() { - return this.useHttpsWithDmaap; - } -} diff --git a/sdc-distribution-client/src/test/java/org/openecomp/sdc/utils/TestNotificationCallback.java b/sdc-distribution-client/src/test/java/org/openecomp/sdc/utils/TestNotificationCallback.java deleted file mode 100644 index bef643a..0000000 --- a/sdc-distribution-client/src/test/java/org/openecomp/sdc/utils/TestNotificationCallback.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdc-distribution-client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.utils; - -import org.openecomp.sdc.api.consumer.INotificationCallback; -import org.openecomp.sdc.api.notification.INotificationData; - -public class TestNotificationCallback implements INotificationCallback{ - - @Override - public void activateCallback(INotificationData data) { - System.out.println("notification callback was called"); - - } - -} diff --git a/version.properties b/version.properties index 4d0ed8b..235314e 100644 --- a/version.properties +++ b/version.properties @@ -4,8 +4,8 @@ # because they are used in Jenkins, whose plug-in doesn't support major=1 -minor=2 -patch=3 +minor=3 +patch=0 base_version=${major}.${minor}.${patch} -- cgit 1.2.3-korg