From ed64b5edff15e702493df21aa3230b81593e6133 Mon Sep 17 00:00:00 2001 From: Michael Lando Date: Fri, 9 Jun 2017 03:19:04 +0300 Subject: [SDC-29] catalog 1707 rebase commit. Change-Id: I43c3dc5cf44abf5da817649bc738938a3e8388c1 Signed-off-by: Michael Lando --- .../auditing/impl/AuditingLogFormatConstants.java | 50 +- .../be/auditing/impl/AuditingLogFormatUtil.java | 25 +- .../distribution/engine/CambriaHandler.java | 192 +- .../distribution/engine/DistributionEngine.java | 22 +- .../engine/DistributionEngineClusterHealth.java | 9 +- .../engine/DistributionNotificationSender.java | 10 +- .../engine/JsonContainerResourceInstance.java | 37 +- .../engine/PublishNotificationRunnable.java | 4 +- .../ServiceDistributionArtifactsBuilder.java | 137 +- .../components/distribution/engine/TestQueue.java | 4 - .../engine/VfModuleArtifactPayload.java | 65 +- .../impl/AdditionalInformationBusinessLogic.java | 14 +- .../be/components/impl/ArtifactsBusinessLogic.java | 2271 ++++++++++------ .../be/components/impl/AttributeBusinessLogic.java | 53 +- .../sdc/be/components/impl/BaseBusinessLogic.java | 504 +++- .../components/impl/CategoriesImportManager.java | 24 +- .../be/components/impl/CommonImportManager.java | 6 +- .../be/components/impl/ComponentBusinessLogic.java | 724 +++-- .../impl/ComponentInstanceBusinessLogic.java | 1416 +++++----- .../components/impl/CompositionBusinessLogic.java | 3 + .../be/components/impl/ConsumerBusinessLogic.java | 6 +- .../be/components/impl/CsarValidationUtils.java | 100 +- .../be/components/impl/ElementBusinessLogic.java | 486 +++- .../sdc/be/components/impl/GroupBusinessLogic.java | 1523 +++++++++-- .../components/impl/HealthCheckBusinessLogic.java | 3 +- .../impl/IDeploymentArtifactTypeConfigGetter.java | 4 +- .../sdc/be/components/impl/ImportUtils.java | 24 +- .../InformationDeployedArtifactsBusinessLogic.java | 4 +- .../be/components/impl/InputsBusinessLogic.java | 1190 ++++++-- .../impl/InterfaceLifecycleTypeImportManager.java | 2 +- .../be/components/impl/ProductBusinessLogic.java | 53 +- .../ProductComponentInstanceBusinessLogic.java | 13 +- .../be/components/impl/PropertyBusinessLogic.java | 279 +- .../be/components/impl/ResourceBusinessLogic.java | 2845 ++++++++++++++------ .../be/components/impl/ResourceImportManager.java | 67 +- .../be/components/impl/ServiceBusinessLogic.java | 509 +++- .../ServiceComponentInstanceBusinessLogic.java | 10 - .../impl/VFComponentInstanceBusinessLogic.java | 11 - .../lifecycle/CertificationChangeTransition.java | 75 +- .../lifecycle/CertificationRequestTransition.java | 180 +- .../be/components/lifecycle/CheckinTransition.java | 67 +- .../components/lifecycle/CheckoutTransition.java | 96 +- .../components/lifecycle/LifeCycleTransition.java | 75 +- .../lifecycle/LifecycleBusinessLogic.java | 404 +-- .../lifecycle/StartCertificationTransition.java | 64 +- .../lifecycle/UndoCheckoutTransition.java | 59 +- .../sdc/be/datamodel/api/CategoryTypeEnum.java | 2 +- .../datamodel/utils/UiComponentDataConverter.java | 218 ++ .../org/openecomp/sdc/be/ecomp/EcompIntImpl.java | 39 +- .../be/ecomp/converters/EcompRoleConverter.java | 3 +- .../be/ecomp/converters/EcompUserConverter.java | 12 +- .../servlet/ArtifactExternalServlet.java | 307 +-- .../servlet/AssetMetadataConverter.java | 105 +- .../be/externalapi/servlet/AssetsDataServlet.java | 507 +++- .../servlet/representation/ArtifactMetadata.java | 20 +- .../ResourceAssetDetailedMetadata.java | 10 + .../representation/ResourceInstanceMetadata.java | 10 +- .../sdc/be/filters/BasicAuthenticationFilter.java | 2 +- .../openecomp/sdc/be/filters/BeServletFilter.java | 20 +- .../org/openecomp/sdc/be/impl/ComponentsUtils.java | 33 +- .../sdc/be/impl/DownloadArtifactLogic.java | 9 +- .../sdc/be/info/ArtifactTemplateInfo.java | 12 +- .../openecomp/sdc/be/info/GroupDefinitionInfo.java | 57 +- .../openecomp/sdc/be/info/GroupTemplateInfo.java | 4 - .../openecomp/sdc/be/info/MergedArtifactInfo.java | 22 +- .../sdc/be/listen/BEAppContextListener.java | 9 +- .../be/servlets/AbstractValidationsServlet.java | 236 +- .../be/servlets/AdditionalInformationServlet.java | 12 +- .../openecomp/sdc/be/servlets/ArtifactServlet.java | 188 +- .../sdc/be/servlets/AttributeServlet.java | 10 +- .../sdc/be/servlets/BeGenericServlet.java | 58 +- .../sdc/be/servlets/BeMonitoringServlet.java | 14 +- .../sdc/be/servlets/ComponentInstanceServlet.java | 248 +- .../sdc/be/servlets/ComponentServlet.java | 200 +- .../openecomp/sdc/be/servlets/ConfigServlet.java | 4 +- .../openecomp/sdc/be/servlets/ConsumerServlet.java | 2 +- .../sdc/be/servlets/CsarBuildServlet.java | 142 - .../openecomp/sdc/be/servlets/ElementServlet.java | 32 +- .../openecomp/sdc/be/servlets/GroupServlet.java | 115 +- .../openecomp/sdc/be/servlets/InputsServlet.java | 161 +- .../sdc/be/servlets/LifecycleServlet.java | 69 +- .../openecomp/sdc/be/servlets/PropertyServlet.java | 140 +- .../sdc/be/servlets/RepresentationUtils.java | 11 +- .../servlets/ResourceArtifactDownloadServlet.java | 37 +- .../sdc/be/servlets/ResourceUploadServlet.java | 9 +- .../sdc/be/servlets/ResourcesServlet.java | 47 +- .../openecomp/sdc/be/servlets/ServiceServlet.java | 100 +- .../sdc/be/servlets/TypesFetchServlet.java | 5 +- .../sdc/be/servlets/TypesUploadServlet.java | 43 +- .../sdc/be/servlets/UserAdminServlet.java | 18 +- .../be/switchover/detector/SwitchoverDetector.java | 16 +- .../org/openecomp/sdc/be/tosca/ArtifactTypes.java | 1 + .../be/tosca/CapabiltyRequirementConvertor.java | 89 +- .../java/org/openecomp/sdc/be/tosca/CsarUtils.java | 1255 +++++++-- .../openecomp/sdc/be/tosca/PropertyConvertor.java | 5 +- .../openecomp/sdc/be/tosca/ToscaExportHandler.java | 593 +++- .../org/openecomp/sdc/be/tosca/ToscaUtils.java | 4 +- .../sdc/be/tosca/model/IToscaMetadata.java | 3 +- .../sdc/be/tosca/model/SubstitutionMapping.java | 14 +- .../sdc/be/tosca/model/ToscaMetadata.java | 36 +- .../sdc/be/tosca/model/ToscaTopolgyTemplate.java | 8 +- .../sdc/be/tosca/model/VfModuleToscaMetadata.java | 9 + .../openecomp/sdc/be/user/IUserBusinessLogic.java | 5 + .../openecomp/sdc/be/user/UserAdminValidator.java | 3 +- .../openecomp/sdc/be/user/UserBusinessLogic.java | 33 +- .../src/main/resources/application-context.xml | 8 +- .../resources/config/Artifact-Generator.properties | 264 ++ catalog-be/src/main/resources/config/SDC.zip | Bin 0 -> 29236 bytes .../src/main/resources/config/configuration.yaml | 254 +- .../config/distribution-engine-configuration.yaml | 6 +- .../main/resources/config/error-configuration.yaml | 116 +- catalog-be/src/main/resources/config/logback.xml | 106 +- .../src/main/resources/config/titan.properties | 1 + catalog-be/src/main/resources/elasticsearch.yml | 16 +- .../tosca/capability-types/capabilityTypes.yml | 2 + .../tosca/capability-types/capabilityTypes.zip | Bin 1385 -> 1402 bytes .../import/tosca/categories/categoryTypes.yml | 33 +- .../import/tosca/categories/categoryTypes.zip | Bin 848 -> 1061 bytes .../import/tosca/data-types/dataTypes.yml | 409 ++- .../import/tosca/data-types/dataTypes.zip | Bin 3456 -> 5243 bytes .../import/tosca/group-types/groupTypes.yml | 55 + .../import/tosca/group-types/groupTypes.zip | Bin 523 -> 1088 bytes .../src/main/resources/import/tosca/heat-types.zip | Bin 0 -> 72549 bytes .../Generic_Service/Generic_Service.json | 21 + .../heat-types/Generic_Service/Generic_Service.yml | 5 + .../heat-types/Generic_Service/Generic_Service.zip | Bin 0 -> 289 bytes .../tosca/heat-types/Generic_VF/Generic_VF.json | 21 + .../tosca/heat-types/Generic_VF/Generic_VF.yml | 27 + .../tosca/heat-types/Generic_VF/Generic_VF.zip | Bin 0 -> 436 bytes .../tosca/heat-types/Generic_VFC/Generic_VFC.json | 21 + .../tosca/heat-types/Generic_VFC/Generic_VFC.yml | 50 + .../tosca/heat-types/Generic_VFC/Generic_VFC.zip | Bin 0 -> 577 bytes .../abstractSubstitute/abstractSubstitute.yml | 7 - .../abstractSubstitute/abstractSubstitute.zip | Bin 469 -> 469 bytes .../tosca/heat-types/cinderVolume/cinderVolume.yml | 118 +- .../tosca/heat-types/cinderVolume/cinderVolume.zip | Bin 1425 -> 1229 bytes .../contrailAbstractSubstitute.yml | 7 - .../contrailAbstractSubstitute.zip | Bin 1017 -> 1017 bytes .../heat-types/contrailCompute/contrailCompute.yml | 11 +- .../heat-types/contrailCompute/contrailCompute.zip | Bin 781 -> 786 bytes .../contrailNetworkRules/contrailNetworkRules.yml | 7 - .../contrailNetworkRules/contrailNetworkRules.zip | Bin 675 -> 675 bytes .../tosca/heat-types/contrailPort/contrailPort.yml | 9 +- .../tosca/heat-types/contrailPort/contrailPort.zip | Bin 720 -> 727 bytes .../contrailV2NetworkRules.yml | 7 - .../contrailV2NetworkRules.zip | Bin 638 -> 638 bytes .../contrailV2VLANSubInterface.json | 15 + .../contrailV2VLANSubInterface.yml | 70 + .../contrailV2VLANSubInterface.zip | Bin 0 -> 746 bytes .../contrailV2VirtualMachineInterface.yml | 58 +- .../contrailV2VirtualMachineInterface.zip | Bin 718 -> 740 bytes .../contrailV2VirtualNetwork.yml | 9 +- .../contrailV2VirtualNetwork.zip | Bin 764 -> 1014 bytes .../contrailVirtualNetwork.yml | 11 +- .../contrailVirtualNetwork.zip | Bin 826 -> 833 bytes .../import/tosca/heat-types/eline/eline.yml | 1 - .../import/tosca/heat-types/eline/eline.zip | Bin 321 -> 683 bytes .../import/tosca/heat-types/extCp/extCp.json | 21 + .../import/tosca/heat-types/extCp/extCp.yml | 53 + .../import/tosca/heat-types/extCp/extCp.zip | Bin 0 -> 790 bytes .../import/tosca/heat-types/extVl/extVl.json | 21 + .../import/tosca/heat-types/extVl/extVl.yml | 50 + .../import/tosca/heat-types/extVl/extVl.zip | Bin 0 -> 767 bytes .../heat-types/globalCompute/globalCompute.json | 20 + .../heat-types/globalCompute/globalCompute.yml | 1300 +++++++++ .../heat-types/globalCompute/globalCompute.zip | Bin 0 -> 3932 bytes .../heat-types/globalNetwork/globalNetwork.json | 21 + .../heat-types/globalNetwork/globalNetwork.yml | 14 + .../heat-types/globalNetwork/globalNetwork.zip | Bin 0 -> 353 bytes .../tosca/heat-types/globalPort/globalPort.json | 15 + .../tosca/heat-types/globalPort/globalPort.yml | 334 +++ .../tosca/heat-types/globalPort/globalPort.zip | Bin 0 -> 1245 bytes .../tosca/heat-types/internalVl/internalVl.json | 21 + .../tosca/heat-types/internalVl/internalVl.yml | 6 + .../tosca/heat-types/internalVl/internalVl.zip | Bin 0 -> 284 bytes .../tosca/heat-types/neutronNet/neutronNet.yml | 9 +- .../tosca/heat-types/neutronNet/neutronNet.zip | Bin 972 -> 979 bytes .../tosca/heat-types/neutronPort/neutronPort.yml | 16 +- .../tosca/heat-types/neutronPort/neutronPort.zip | Bin 1192 -> 1320 bytes .../tosca/heat-types/novaServer/novaServer.json | 6 +- .../tosca/heat-types/novaServer/novaServer.yml | 72 +- .../tosca/heat-types/novaServer/novaServer.zip | Bin 1840 -> 1848 bytes .../heat-types/securityRules/securityRules.yml | 9 +- .../heat-types/securityRules/securityRules.zip | Bin 692 -> 690 bytes .../heat-types/subInterface/subInterface.json | 15 + .../tosca/heat-types/subInterface/subInterface.yml | 4 + .../tosca/heat-types/subInterface/subInterface.zip | Bin 0 -> 384 bytes .../resources/import/tosca/heat-types/vl/vl.zip | Bin 355 -> 355 bytes .../import/tosca/heat-types/volume/volume.json | 20 + .../import/tosca/heat-types/volume/volume.yml | 7 + .../import/tosca/heat-types/volume/volume.zip | Bin 0 -> 308 bytes .../tosca/normative-types/compute/compute.json | 6 +- .../import/tosca/policy-types/policyTypes.zip | Bin 673 -> 673 bytes .../resources/import/tosca/users/importUsers.yaml | 4 +- catalog-be/src/main/resources/portal.properties | 6 +- .../scripts/import/tosca/importHeatTypes.py | 32 +- .../scripts/import/tosca/importHeatTypes1.py | 97 + .../scripts/import/tosca/importNormativeAll1.py | 118 + .../importNormativeNoHeatAndNormativeTypes.py | 135 + .../scripts/import/tosca/importNormativeTypes.py | 2 +- .../scripts/import/tosca/upgradeHeatTypes1707.py | 113 + .../scripts/import/tosca/upgradeNormative.py | 18 +- .../import/tosca/upgradeNormativeVersion.py | 42 +- .../tosca/upgradeNormativeVersionProd1702_3537.py | 129 + .../src/main/resources/swagger/lib/backbone-min.js | 22 +- .../main/resources/swagger/lib/handlebars-2.0.0.js | 22 +- .../resources/swagger/lib/highlight.7.3.pack.js | 22 +- .../main/resources/swagger/lib/jquery-1.8.0.min.js | 22 +- .../resources/swagger/lib/jquery.ba-bbq.min.js | 22 +- .../resources/swagger/lib/jquery.slideto.min.js | 20 - .../resources/swagger/lib/jquery.wiggle.min.js | 22 +- .../src/main/resources/swagger/lib/marked.js | 22 +- .../main/resources/swagger/lib/swagger-oauth.js | 22 +- .../main/resources/swagger/lib/underscore-min.js | 22 +- .../src/main/resources/swagger/swagger-ui.js | 22 +- .../src/main/resources/swagger/swagger-ui.min.js | 22 +- catalog-be/src/main/webapp/WEB-INF/web.xml | 20 +- 217 files changed, 17559 insertions(+), 6299 deletions(-) create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java create mode 100644 catalog-be/src/main/resources/config/Artifact-Generator.properties create mode 100644 catalog-be/src/main/resources/config/SDC.zip create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types.zip create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.json create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.yml create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.zip create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.json create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.yml create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.zip create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.json create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.yml create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.zip create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.json create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.yml create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.zip create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.json create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.yml create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.zip create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.json create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.yml create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.zip create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.json create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.yml create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.zip create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.json create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.yml create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.zip create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.json create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.yml create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.zip create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.json create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.yml create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.zip create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.json create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.yml create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.zip create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.json create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.yml create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.zip create mode 100644 catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes1.py create mode 100644 catalog-be/src/main/resources/scripts/import/tosca/importNormativeAll1.py create mode 100644 catalog-be/src/main/resources/scripts/import/tosca/importNormativeNoHeatAndNormativeTypes.py create mode 100644 catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py create mode 100644 catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionProd1702_3537.py (limited to 'catalog-be/src/main') diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java index eb14b5afe7..8ff3fca4f8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java @@ -20,6 +20,9 @@ package org.openecomp.sdc.be.auditing.impl; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.components.impl.ImportUtils; +import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; public interface AuditingLogFormatConstants { @@ -148,7 +151,8 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE + }; static AuditingFieldsKeysEnum[] USER_ACCESS_TEMPLATE_ARRAY = { @@ -234,9 +238,6 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_DESC }; static AuditingFieldsKeysEnum[] EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, AuditingFieldsKeysEnum.AUDIT_STATUS, @@ -255,4 +256,45 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_STATUS, AuditingFieldsKeysEnum.AUDIT_DESC }; + + static AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + + AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, + + AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, + AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static AuditingFieldsKeysEnum[] EXTERNAL_LYFECYCLE_API_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + + AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, + + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java index 5fec39bbdb..b965516df8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java @@ -24,7 +24,9 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.EnumMap; import java.util.Formatter; +import java.util.HashSet; import java.util.Locale; +import java.util.Set; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.api.Constants; @@ -43,7 +45,7 @@ public class AuditingLogFormatUtil { // This is the key by which audit marker is recognized in logback.xml private static String AUDIT_MARKER_STR = "AUDIT_MARKER"; - public static Marker auditMarker = MarkerFactory.getMarker(AUDIT_MARKER_STR); + public static final Marker auditMarker = MarkerFactory.getMarker(AUDIT_MARKER_STR); protected static void logAuditEvent(EnumMap auditingFields) { @@ -77,7 +79,7 @@ public class AuditingLogFormatUtil { log.info(auditMarker, formattedString); } } catch (Exception e) { - log.debug("unexpected error occurred: {} {}", e.getMessage(), e); + log.debug("unexpected error occurred: {}", e.getMessage(), e); } finally { formatter.close(); @@ -144,14 +146,13 @@ public class AuditingLogFormatUtil { case ARTIFACT_METADATA_UPDATE: case ARTIFACT_PAYLOAD_UPDATE: case ARTIFACT_DOWNLOAD: - ArrayList artifactFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY)); - artifactFieldsList.add(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID); - artifactFieldsList.add(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID); - artifactFieldsList.add(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA); - artifactFieldsList.addAll(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY)); - artifactFieldsList.addAll(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY)); + ArrayList artifactFieldsSet = new ArrayList<>(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY)) ; + artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID); + artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID); + artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA); + artifactFieldsSet.addAll(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY)); AuditingFieldsKeysEnum[] artifactFieldsArray = new AuditingFieldsKeysEnum[100]; - artifactFieldsArray = artifactFieldsList.toArray(artifactFieldsArray); + artifactFieldsArray = artifactFieldsSet.toArray(artifactFieldsArray); formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields); break; case DOWNLOAD_ARTIFACT: @@ -225,6 +226,12 @@ public class AuditingLogFormatUtil { artifactFieldsArray = uploadArtifactFieldsList.toArray(uploadArtifactFieldsArray); formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields); break; + case CREATE_RESOURCE_BY_API: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_CRUD_API_ARRAY, auditingFields); + break; + case CHANGE_LIFECYCLE_BY_API: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_LYFECYCLE_API_ARRAY, auditingFields); + break; default: break; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java index 3528ed9be3..6738b87853 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java @@ -21,7 +21,6 @@ package org.openecomp.sdc.be.components.distribution.engine; import java.io.IOException; -import java.net.MalformedURLException; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Collection; @@ -54,6 +53,7 @@ import com.att.nsa.cambria.client.CambriaTopicManager; import com.google.gson.Gson; import fj.data.Either; +import jline.internal.Log; public class CambriaHandler { @@ -63,6 +63,169 @@ public class CambriaHandler { private Gson gson = new Gson(); + public static void main(String[] args) { + + // String userBodyJson ="{\"artifactName\":\"myartifact\", + // \"artifactType\":\"MURANO-PKG\", + // \"artifactDescription\":\"description\", + // \"payloadData\":\"UEsDBAoAAAAIAAeLb0bDQz\", \"Content-MD5\": + // \"YTg2Mjg4MWJhNmI5NzBiNzdDFkMWI=\" }"; + // System.out.println(userBodyJson); + // String encodeBase64Str = GeneralUtililty.calculateMD5 (userBodyJson); + // System.out.println(encodeBase64Str); + + CambriaTopicManager createTopicManager = null; + try { + List servers = new ArrayList(); + // servers.add("uebsb91kcdc.it.sdc.com:3904"); + // servers.add("uebsb92kcdc.it.sdc.com:3904"); + // servers.add("uebsb93kcdc.it.sdc.com:3904"); + servers.add("uebsb91sfdc.it.att.com:3904"); + servers.add("uebsb92sfdc.it.att.com:3904"); + + String key = "sSJc5qiBnKy2qrlc"; + String secret = "4ZRPzNJfEUK0sSNBvccd2m7X"; + + createTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(servers).authenticatedBy(key, secret).build(); + + String topicName = "ASDC-DISTR-NOTIF-TOPIC-PRODesofer"; + + String clientKey1 = "CGGoorrGPXPx2B1C"; + String clientSecret1 = "OTHk2mcCSbskEtHhDw8h5oUa"; + + CambriaTopicManager createStatusTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(servers).authenticatedBy(key, secret).build(); + String reportTopic = "ASDC-DISTR-STATUS-TOPIC-PRODESOFER"; + createStatusTopicManager.allowProducer(reportTopic, clientKey1); + + CambriaBatchingPublisher createSimplePublisher = new PublisherBuilder().onTopic(reportTopic).usingHttps().usingHosts(servers).build(); + createSimplePublisher.setApiCredentials(clientKey1, clientSecret1); + + DistributionStatusNotification distributionStatusNotification = new DistributionStatusNotification(); + distributionStatusNotification.setStatus(DistributionStatusNotificationEnum.DEPLOY_OK); + distributionStatusNotification.setArtifactURL("Ssssssss url"); + distributionStatusNotification.setDistributionID("idddddddddddddd"); + distributionStatusNotification.setTimestamp(System.currentTimeMillis()); + distributionStatusNotification.setConsumerID("my consumer id"); + + Gson gson = new Gson(); + int result = createSimplePublisher.send(PARTITION_KEY, gson.toJson(distributionStatusNotification)); + + List messagesInQ = createSimplePublisher.close(20, TimeUnit.SECONDS); + System.out.println(messagesInQ == null ? 0 : messagesInQ.size()); + + // createTopicManager.createTopic(topicName, "my test topic", 1, 1); + + /* + * + * { "secret": "OTHk2mcCSbskEtHhDw8h5oUa", "aux": { "email": "esofer@intl.sdc.com", "description": "test-keys" }, "key": "CGGoorrGPXPx2B1C" } + * + * + * { "secret": "FSlNJbmGWWBvBLJetQMYxPP6", "aux": { "email": "esofer@intl.sdc.com", "description": "test-keys" }, "key": "TAIEPO0aDU4VzM0G" } + * + */ + + String clientKey2 = "TAIEPO0aDU4VzM0G"; + + CambriaConsumer createConsumer1 = new ConsumerBuilder().authenticatedBy("asdc1", "consumerId1").onTopic(topicName).usingHttps().usingHosts(servers).build(); + createConsumer1.setApiCredentials(clientKey1, "OTHk2mcCSbskEtHhDw8h5oUa"); + + createTopicManager.allowConsumer(topicName, clientKey1); + + CambriaConsumer createConsumer2 = null; + if (true) { + createConsumer2 = new ConsumerBuilder().authenticatedBy("asdc2", "consumerId3").onTopic(topicName).usingHttps().usingHosts(servers).build(); + createConsumer2.setApiCredentials(clientKey2, "FSlNJbmGWWBvBLJetQMYxPP6"); + + createTopicManager.allowConsumer(topicName, clientKey2); + } + + createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHttps().usingHosts(servers).build(); + createSimplePublisher.setApiCredentials(key, secret); + createTopicManager.allowProducer(topicName, key); + + createSimplePublisher.send("aaaa", "{ my testttttttttttttttt }"); + + while (true) { + + Iterable fetch1 = createConsumer1.fetch(); + + Iterator iterator1 = fetch1.iterator(); + while (iterator1.hasNext()) { + System.out.println("***********************************************"); + System.out.println("client 1" + iterator1.next()); + System.out.println("***********************************************"); + } + + if (createConsumer2 != null) { + Iterable fetch2 = createConsumer2.fetch(); + + Iterator iterator2 = fetch2.iterator(); + while (iterator2.hasNext()) { + System.out.println("***********************************************"); + System.out.println("client 2" + iterator2.next()); + System.out.println("***********************************************"); + } + } + Thread.sleep(1000 * 20); + } + + // createTopicManager = CambriaClientFactory.createTopicManager( + // servers, "8F3MDAtMSBwwpSMy", "gzFmsTxSCtO5RQfAccM6PqqX"); + + // createTopicManager.deleteTopic("ASDC-DISTR-NOTIF-TOPIC-PROD"); + // createTopicManager.deleteTopic("ASDC-DISTR-NOTIF-TOPIC-PROD1"); + + // CambriaIdentityManager createIdentityManager = + // CambriaClientFactory.createIdentityManager(null, null, null); + // createIdentityManager.setApiCredentials(arg0, arg1); + // createIdentityManager.cl + + // String topicName = " "; + // createTopicManager.createTopic(topicName, + // "ASDC distribution notification topic", 1, 1); + // + // Thread.sleep(10 * 1000); + // + // for (int i = 0; i < 5; i++) { + // try { + // boolean openForProducing = createTopicManager + // .isOpenForProducing(topicName); + // + // System.out.println("openForProducing=" + openForProducing); + // createTopicManager.allowProducer(topicName, + // "8F3MDAtMSBwwpSMy"); + // Set allowedProducers = createTopicManager + // .getAllowedProducers(topicName); + // System.out.println(allowedProducers); + // + // } catch (Exception e) { + // e.printStackTrace(); + // } + // } + + // createTopicManager.createTopic("", "", 0, 0); + // createTopicManager.allowProducer(arg0, arg1); + // createTopicManager.getTopics(); + // createTopicManager.close(); + // CambriaClientFactory. + // CambriaBatchingPublisher createSimplePublisher = + // CambriaClientFactory.createSimplePublisher("hostlist", "topic"); + + // CambriaIdentityManager createIdentityManager = + // CambriaClientFactory.createIdentityManager(null, "apiKey", + // "apiSecret"); + // createIdentityManager. + + } catch (Exception e) { + Log.debug("Exception in main test of Cambria Handler: {}", e.getMessage(), e); + e.printStackTrace(); + } finally { + if (createTopicManager != null) { + createTopicManager.close(); + } + } + } + /** * process the response error from Cambria client * @@ -121,7 +284,8 @@ public class CambriaHandler { CambriaTopicManager createTopicManager = null; try { - createTopicManager = new TopicManagerBuilder().usingHosts(hostSet).build(); + createTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(hostSet).build(); + Set topics = createTopicManager.getTopics(); if (topics == null || true == topics.isEmpty()) { @@ -263,10 +427,13 @@ public class CambriaHandler { CambriaTopicManager createTopicManager = null; try { - createTopicManager = new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(apiKey, secretKey).build(); + + createTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(hostSet).authenticatedBy(apiKey, secretKey).build(); + createTopicManager.createTopic(topicName, "ASDC distribution notification topic", partitionCount, replicationCount); - } catch (GeneralSecurityException | HttpException | IOException e) { + } catch (HttpException | IOException | GeneralSecurityException e) { + logger.debug("Failed to create topic {}", topicName, e); String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); @@ -285,12 +452,13 @@ public class CambriaHandler { } } return new CambriaErrorResponse(CambriaOperationStatus.OK); + } public CambriaErrorResponse unRegisterFromTopic(Collection hostSet, String topicName, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum) { CambriaTopicManager createTopicManager = null; try { - createTopicManager = new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey).build(); + createTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey).build(); if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) { createTopicManager.revokeProducer(topicName, subscriberApiKey); @@ -345,7 +513,7 @@ public class CambriaHandler { CambriaTopicManager createTopicManager = null; try { - createTopicManager = new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey).build(); + createTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey).build(); if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) { createTopicManager.allowProducer(topicName, subscriberApiKey); @@ -395,11 +563,11 @@ public class CambriaHandler { * @param consumerGroup * @param timeoutMS * @return - * @throws Exception + * @throws Exception */ public CambriaConsumer createConsumer(Collection hostSet, String topicName, String apiKey, String secretKey, String consumerId, String consumerGroup, int timeoutMS) throws Exception { - CambriaConsumer consumer = new ConsumerBuilder().authenticatedBy(apiKey, secretKey).knownAs(consumerGroup, consumerId).onTopic(topicName).usingHosts(hostSet).withSocketTimeout(timeoutMS).build(); + CambriaConsumer consumer = new ConsumerBuilder().authenticatedBy(apiKey, secretKey).knownAs(consumerGroup, consumerId).onTopic(topicName).usingHttps().usingHosts(hostSet).withSocketTimeout(timeoutMS).build(); consumer.setApiCredentials(apiKey, secretKey); return consumer; } @@ -470,7 +638,7 @@ public class CambriaHandler { String json = gson.toJson(data); logger.trace("Before sending notification data {} to topic {}", json, topicName); - createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHosts(uebServers).build(); + createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHttps().usingHosts(uebServers).build(); createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey); int result = createSimplePublisher.send(PARTITION_KEY, json); @@ -532,7 +700,7 @@ public class CambriaHandler { String json = gson.toJson(data); logger.debug("Before sending notification data {} to topic {}", json, topicName); - createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHosts(uebServers).build(); + createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHttps().usingHosts(uebServers).build(); createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey); int result = createSimplePublisher.send(PARTITION_KEY, json); @@ -559,7 +727,7 @@ public class CambriaHandler { } - logger.debug("Before closing publisher. Maximum timeout is {} seconds.", waitBeforeCloseTimeout); + logger.debug("Before closing publisher. Maximum timeout is {} seconds", waitBeforeCloseTimeout); try { List messagesInQ = createSimplePublisher.close(waitBeforeCloseTimeout, TimeUnit.SECONDS); if (messagesInQ != null && false == messagesInQ.isEmpty()) { @@ -593,7 +761,7 @@ public class CambriaHandler { hostSet.add(server); CambriaIdentityManager createIdentityManager = null; try { - createIdentityManager = new IdentityManagerBuilder().usingHosts(hostSet).build(); + createIdentityManager = new IdentityManagerBuilder().usingHttps().usingHosts(hostSet).build(); createIdentityManager.getApiKey(apiKey); response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java index 6cb31c8cf2..d3d04ea735 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java @@ -51,6 +51,22 @@ public class DistributionEngine implements IDistributionEngine { 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 void main(String[] args) { + + List servers = new ArrayList<>(); + + servers.add("uebsb91kcdc.it.att.com:3904"); + servers.add("uebsb91kcdc.it.att.com:3904"); + servers.add("uebsb91kcdc.it.att.com:3904"); + + YamlToObjectConverter converter = new YamlToObjectConverter(); + DistributionEngineConfiguration distributionEngineConfiguration = converter.convert("src/test/resources/config/catalog-be/distribEngine1/distribution-engine-configuration.yaml", DistributionEngineConfiguration.class); + + DistributionEngineInitTask distributionEngineInitTask = new DistributionEngineInitTask(2l, distributionEngineConfiguration, "PROD", new AtomicBoolean(false), null, null); + distributionEngineInitTask.startTask(); + + } + @javax.annotation.Resource private ComponentsUtils componentUtils; @@ -319,10 +335,8 @@ public class DistributionEngine implements IDistributionEngine { @Override public StorageOperationStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName) { - - if (logger.isDebugEnabled()) { - logger.debug("Received notify service request. distributionId = {}, serviceUuid = {}, serviceUid = {}, envName = {}, userId = {}, modifierName {}", distributionId, service.getUUID(), service.getUniqueId(), envName, userId, modifierName); - } + + logger.debug("Received notify service request. distributionId = {}, serviceUuid = {} serviceUid = {}, envName = {}, userId = {}, modifierName {}", distributionId, service.getUUID(), service.getUniqueId(), envName, userId, modifierName); DistributionEngineConfiguration deConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java index a3d0362c61..1b868951c5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java @@ -72,10 +72,10 @@ public class DistributionEngineClusterHealth { public enum HealthCheckInfoResult { - OK(new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UP, null, ClusterStatusDescription.OK.getDescription())), UNAVAILABLE( - new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.UNAVAILABLE.getDescription())), NOT_CONFIGURED( - new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.NOT_CONFIGURED.getDescription())), DISABLED( - new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.DISABLED.getDescription())); + OK(new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UP, null, ClusterStatusDescription.OK.getDescription())), + UNAVAILABLE(new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.UNAVAILABLE.getDescription())), + NOT_CONFIGURED(new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.NOT_CONFIGURED.getDescription())), + DISABLED(new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.DISABLED.getDescription())); private HealthCheckInfo healthCheckInfo; @@ -237,6 +237,7 @@ public class DistributionEngineClusterHealth { message = e.getClass().getName(); } healthLogger.debug("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message); + healthLogger.trace("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message, e); } retryNumber++; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java index 667276db2c..16a0a1dc31 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java @@ -30,10 +30,8 @@ import org.openecomp.sdc.be.config.DistributionEngineConfiguration; import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionNotificationTopicConfig; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.operations.api.IServiceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.util.ThreadLocalsHolder; import org.slf4j.Logger; @@ -47,7 +45,7 @@ public class DistributionNotificationSender { private static Logger logger = LoggerFactory.getLogger(DistributionNotificationSender.class.getName()); - // final String BASE_ARTIFACT_URL = "/asdc/v1/catalog/services/%s/%s/"; + // final String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/"; // final String RESOURCE_ARTIFACT_URL = BASE_ARTIFACT_URL // + "resources/%s/%s/artifacts/%s"; // final String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s"; @@ -55,12 +53,6 @@ public class DistributionNotificationSender { @javax.annotation.Resource InterfaceLifecycleOperation interfaceLifecycleOperation; - @javax.annotation.Resource - protected IServiceOperation serviceOperation; - - @javax.annotation.Resource - protected ResourceOperation resourceOperation; - @javax.annotation.Resource protected ComponentsUtils componentUtils; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java index 25a6f46c90..d1b445b065 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java @@ -25,7 +25,7 @@ import java.util.List; import org.openecomp.sdc.be.model.ComponentInstance; public class JsonContainerResourceInstance { - private String resourceInstanceName, resourceName, resourceVersion, resoucreType, resourceUUID, resourceInvariantUUID; + private String resourceInstanceName, resourceName, resourceVersion, resoucreType, resourceUUID, resourceInvariantUUID, resourceCustomizationUUID, category, subcategory; private List artifacts; public JsonContainerResourceInstance(ComponentInstance resourceInstance, String resourceType, List artifacts) { @@ -36,17 +36,7 @@ public class JsonContainerResourceInstance { this.resoucreType = resourceType; this.resourceUUID = resourceInstance.getComponentUid(); this.artifacts = artifacts; - } - - public JsonContainerResourceInstance(ComponentInstance resourceInstance, String resourceInvariantUUID, String resourceType, List artifacts) { - super(); - this.resourceInstanceName = resourceInstance.getName(); - this.resourceName = resourceInstance.getComponentName(); - this.resourceVersion = resourceInstance.getComponentVersion(); - this.resoucreType = resourceType; - this.resourceUUID = resourceInstance.getComponentUid(); - this.resourceInvariantUUID = resourceInvariantUUID; - this.artifacts = artifacts; + this.resourceCustomizationUUID = resourceInstance.getCustomizationUUID(); } public String getResourceInstanceName() { @@ -105,4 +95,27 @@ public class JsonContainerResourceInstance { this.resourceInvariantUUID = resourceInvariantUUID; } + public String getResourceCustomizationUUID() { + return resourceCustomizationUUID; + } + + public void setResourceCustomizationUUID(String customizationUUID) { + this.resourceCustomizationUUID = customizationUUID; + } + + 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/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java index 362f3948ed..c283ecc92b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java @@ -108,13 +108,13 @@ public class PublishNotificationRunnable implements Runnable { ThreadLocalsHolder.setUuid(this.requestId); CambriaErrorResponse status = cambriaHandler.sendNotificationAndClose(topicName, deConfiguration.getUebPublicKey(), deConfiguration.getUebSecretKey(), deConfiguration.getUebServers(), data, - deConfiguration.getDistributionNotificationTopic().getMaxWaitingAfterSendingSeconds().longValue()); + deConfiguration.getDistributionNotificationTopic().getMaxWaitingAfterSendingSeconds()); logger.info("After publishing service {} of version {}. Status is {}", service.getName(), service.getVersion(), status.getHttpCode()); auditDistributionNotification(topicName, status, service, distributionId, envName, userId, modifierName); long endTime = System.currentTimeMillis(); - logger.debug("After building and publishing artifacts object. Total took {} milliseconds.", (endTime - startTime)); + logger.debug("After building and publishing artifacts object. Total took {} milliseconds", (endTime - startTime)); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java index 6e67e38c15..90120288bc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java @@ -24,22 +24,27 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; import javax.annotation.PostConstruct; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IArtifactOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; -import org.openecomp.sdc.be.model.operations.impl.ServiceOperation; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import fj.data.Either; @@ -51,47 +56,31 @@ public class ServiceDistributionArtifactsBuilder { private static Logger logger = LoggerFactory.getLogger(ServiceDistributionArtifactsBuilder.class.getName()); - final static String BASE_ARTIFACT_URL = "/asdc/v1/catalog/services/%s/%s/"; + final static String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/"; final static String RESOURCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resources/%s/%s/artifacts/%s"; final static String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s"; final static String RESOURCE_INSTANCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resourceInstances/%s/artifacts/%s"; - @javax.annotation.Resource - ServiceOperation serviceOperation; - - @javax.annotation.Resource - ResourceOperation resourceOperation; - @javax.annotation.Resource InterfaceLifecycleOperation interfaceLifecycleOperation; @javax.annotation.Resource IArtifactOperation artifactOperation; + + @Autowired + ToscaOperationFacade toscaOperationFacade; /* - * @javax.annotation.Resource private InformationDeployedArtifactsBusinessLogic informationDeployedArtifactsBusinessLogic; + * @javax.annotation.Resource private + * InformationDeployedArtifactsBusinessLogic + * informationDeployedArtifactsBusinessLogic; */ @PostConstruct private void init() { - defaultArtifactInstallTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes(); - } - - public ServiceOperation getServiceOperation() { - return serviceOperation; - } - - public void setServiceOperation(ServiceOperation serviceOperation) { - this.serviceOperation = serviceOperation; - } - - public ResourceOperation getResourceOperation() { - return resourceOperation; - } - - public void setResourceOperation(ResourceOperation resourceOperation) { - this.resourceOperation = resourceOperation; + defaultArtifactInstallTimeout = ConfigurationManager.getConfigurationManager().getConfiguration() + .getDefaultHeatArtifactTimeoutMinutes(); } public InterfaceLifecycleOperation getInterfaceLifecycleOperation() { @@ -130,37 +119,91 @@ public class ServiceDistributionArtifactsBuilder { } private List convertServiceArtifactsToArtifactInfo(Service service) { - + Map serviceArtifactsMap = service.getDeploymentArtifacts(); - List ret = new ArrayList(); - - for (ArtifactDefinition artifactDef : serviceArtifactsMap.values()) { - if (artifactDef.checkEsIdExist()) { - ret.add(artifactDef); - } + List extractedServiceArtifacts = serviceArtifactsMap.values().stream() + //filters all artifacts with existing EsId + .filter(artifactDef -> artifactDef.checkEsIdExist()) + //collects all filtered artifacts with existing EsId to List + .collect(Collectors.toList()); + + Optional toscaTemplateArtifactOptl = exrtactToscaTemplateArtifact(service); + if(toscaTemplateArtifactOptl.isPresent()){ + extractedServiceArtifacts.add(toscaTemplateArtifactOptl.get()); } - List artifacts = ArtifactInfoImpl.convertServiceArtifactToArtifactInfoImpl(service, ret); + + Optional toscaCsarArtifactOptl = exrtactToscaCsarArtifact(service); + if(toscaCsarArtifactOptl.isPresent()){ + extractedServiceArtifacts.add(toscaCsarArtifactOptl.get()); + } + + List artifacts = ArtifactInfoImpl.convertServiceArtifactToArtifactInfoImpl(service, extractedServiceArtifacts); return artifacts; } + private Optional exrtactToscaTemplateArtifact(Service service) { + return service.getToscaArtifacts().values().stream() + //filters TOSCA_TEMPLATE artifact + .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny(); + } + + private Optional exrtactToscaCsarArtifact(Service service) { + return service.getToscaArtifacts().values().stream() + //filters TOSCA_CSAR artifact + .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny(); + } + private List convertRIToJsonContanier(Service service) { List ret = new ArrayList(); if (service.getComponentInstances() != null) { for (ComponentInstance resourceInstance : service.getComponentInstances()) { - String resourceType = "VF"; + String resoucreType = resourceInstance.getOriginType().getValue(); List artifactsDefList = getArtifactsWithPayload(resourceInstance); - List artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance, artifactsDefList); - Either responseResult = resourceOperation.getInvariantUUID(NodeTypeEnum.Resource, resourceInstance.getComponentUid(), false); + List artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance, + artifactsDefList); + String resourceInvariantUUID = null; - if (responseResult.isRight()) { - logger.debug("Resource {} Invariant UUID retrieving failed", resourceInstance.getComponentUid()); + String resourceCategory = null; + String resourceSubcategory = null; + + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreCategories(false); + Either componentResponse = toscaOperationFacade + .getToscaElement(resourceInstance.getComponentUid(), componentParametersView); + + if (componentResponse.isRight()) { + logger.debug("Resource {} Invariant UUID & Categories retrieving failed", resourceInstance.getComponentUid()); } else { - resourceInvariantUUID = responseResult.left().value(); + Resource resource = componentResponse.left().value(); + resourceInvariantUUID = resource.getInvariantUUID(); + + List categories = resource.getCategories(); + + if (categories != null) { + CategoryDefinition categoryDefinition = categories.get(0); + + if (categoryDefinition != null) { + resourceCategory = categoryDefinition.getName(); + List subcategories = categoryDefinition.getSubcategories(); + if (null != subcategories) { + SubCategoryDefinition subCategoryDefinition = subcategories.get(0); + + if (subCategoryDefinition != null) { + resourceSubcategory = subCategoryDefinition.getName(); + } + } + } + } } - JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(resourceInstance, resourceInvariantUUID, resourceType, artifacts); + + JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(resourceInstance, resoucreType, + artifacts); + jsonContainer.setResourceInvariantUUID(resourceInvariantUUID); + jsonContainer.setCategory(resourceCategory); + jsonContainer.setSubcategory(resourceSubcategory); ret.add(jsonContainer); } - } return ret; } @@ -193,9 +236,11 @@ public class ServiceDistributionArtifactsBuilder { * @param artifactName * @return */ - public static String buildResourceInstanceArtifactUrl(Service service, ComponentInstance resourceInstance, String artifactName) { + public static String buildResourceInstanceArtifactUrl(Service service, ComponentInstance resourceInstance, + String artifactName) { - String url = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), resourceInstance.getNormalizedName(), artifactName); + String url = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), + resourceInstance.getNormalizedName(), artifactName); logger.debug("After building artifact url {}", url); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/TestQueue.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/TestQueue.java index c9e3c4e34d..d9cd6ef51f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/TestQueue.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/TestQueue.java @@ -64,13 +64,11 @@ public class TestQueue { @Override public void run() { - // TODO Auto-generated method stub try { System.out.println("iN SLEEP" + Thread.currentThread()); Thread.sleep(10 * 1000); System.out.println("OUT SLEEP"); } catch (InterruptedException e) { - // TODO Auto-generated catch block e.printStackTrace(); } } @@ -98,7 +96,6 @@ public class TestQueue { try { queue.put("message " + i); } catch (InterruptedException e) { - // TODO Auto-generated catch block e.printStackTrace(); } } @@ -175,7 +172,6 @@ public class TestQueue { try { Thread.sleep(1 * 1000); } catch (InterruptedException e) { - // TODO Auto-generated catch block for (int i = 0; i < 10; i++) { System.out.println("*************************************************"); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java index 89cb6d91ee..71593fa99a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java @@ -20,14 +20,26 @@ package org.openecomp.sdc.be.components.distribution.engine; +import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Optional; +import java.util.stream.Collectors; +import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupInstance; +import org.openecomp.sdc.be.model.GroupInstanceProperty; import org.openecomp.sdc.be.model.GroupProperty; import org.openecomp.sdc.common.api.Constants; public class VfModuleArtifactPayload { + + private String vfModuleModelName, vfModuleModelInvariantUUID, vfModuleModelVersion, vfModuleModelUUID, vfModuleModelCustomizationUUID, vfModuleModelDescription; + private Boolean isBase; + private List artifacts; + private Map< String, Object> properties; + public VfModuleArtifactPayload(GroupDefinition group) { vfModuleModelName = group.getName(); vfModuleModelInvariantUUID = group.getInvariantUUID(); @@ -40,10 +52,38 @@ public class VfModuleArtifactPayload { setBaseValue(group); } + + public VfModuleArtifactPayload(GroupInstance group) { + vfModuleModelName = group.getGroupName(); + vfModuleModelInvariantUUID = group.getInvariantUUID(); + vfModuleModelVersion = group.getVersion(); + vfModuleModelUUID = group.getGroupUUID(); + vfModuleModelCustomizationUUID = group.getCustomizationUUID(); + vfModuleModelDescription = group.getDescription(); + artifacts = group.getArtifactsUuid(); + // Base Value is set from properties + setBaseValue(group); + + if(group.convertToGroupInstancesProperties() != null) + setProperties(group.convertToGroupInstancesProperties()); + //converts List of GroupInstanceProperties to Map propertyName : GroupInstanceProperty () + //setProperties(group.getGroupInstancesProperties().stream().collect(Collectors.toMap(p->p.getName(), p->p))); + + } + + private void setBaseValue(GroupInstance group) { + if (group.convertToGroupInstancesProperties() != null) { + Optional findBaseProperty = group.convertToGroupInstancesProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); + if (findBaseProperty.isPresent()) { + isBase = Boolean.valueOf(findBaseProperty.get().getValue()); + } + + } + } private void setBaseValue(GroupDefinition group) { if (group.getProperties() != null) { - Optional findBaseProperty = group.getProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); + Optional findBaseProperty = group.convertToGroupProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); if (findBaseProperty.isPresent()) { isBase = Boolean.valueOf(findBaseProperty.get().getValue()); } @@ -51,9 +91,7 @@ public class VfModuleArtifactPayload { } } - private String vfModuleModelName, vfModuleModelInvariantUUID, vfModuleModelVersion, vfModuleModelUUID, vfModuleModelDescription; - private Boolean isBase; - private List artifacts; + public List getArtifacts() { return artifacts; @@ -62,10 +100,25 @@ public class VfModuleArtifactPayload { public void setArtifacts(List artifacts) { this.artifacts = artifacts; } + + + + public Map getProperties() { + return properties; + } + + /*public void setProperties(Map properties) { + this.properties = properties; + }*/ + + public void setProperties(List properties) { + this.properties = properties.stream().filter(p -> !p.getName().equals(Constants.IS_BASE)).collect( + Collectors.toMap(x -> x.getName(), x -> x.getValue() == null? "":x.getValue() )); + } public static int compareByGroupName(VfModuleArtifactPayload art1, VfModuleArtifactPayload art2) { - Integer thisCounter = Integer.parseInt(art1.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1]); - Integer otherCounter = Integer.parseInt(art2.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1]); + Float thisCounter = Float.parseFloat(art1.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.')); + Float otherCounter = Float.parseFloat(art2.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.')); return thisCounter.compareTo(otherCounter); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java index e01d4c238c..51b5679ffa 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java @@ -29,17 +29,15 @@ import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.graph.datatype.AdditionalInformationEnum; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; -import org.openecomp.sdc.be.model.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.model.AdditionalInformationDefinition; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; -import org.openecomp.sdc.be.model.operations.api.IResourceOperation; -import org.openecomp.sdc.be.model.operations.api.IServiceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; @@ -72,12 +70,6 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { @javax.annotation.Resource private IAdditionalInformationOperation additionalInformationOperation = null; - @javax.annotation.Resource - private IResourceOperation resourceOperation; - - @javax.annotation.Resource - private IServiceOperation serviceOperation; - @javax.annotation.Resource private IGraphLockOperation graphLockOperation; @@ -551,7 +543,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { // verify that resource is checked-out and the user is the last // updater - if (!ComponentValidationUtils.canWorkOnResource(resourceId, resourceOperation, userId)) { + if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) { return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); } break; @@ -559,7 +551,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { // verify that resource is checked-out and the user is the last // updater - if (!ComponentValidationUtils.canWorkOnService(resourceId, serviceOperation, userId)) { + if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) { return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); } break; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java index 16ed4a1868..6739d28bd4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java @@ -24,13 +24,13 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Collection; import java.util.Comparator; import java.util.EnumMap; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.function.Supplier; @@ -39,6 +39,9 @@ import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import org.apache.commons.codec.binary.Base64; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; @@ -46,14 +49,15 @@ import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum; import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.Configuration.DeploymentArtifactTypeConfig; +import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; @@ -61,6 +65,9 @@ import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.ArtifactType; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupInstance; import org.openecomp.sdc.be.model.HeatParameterDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; @@ -70,19 +77,14 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.heat.HeatParameterType; -import org.openecomp.sdc.be.model.operations.api.IArtifactOperation; -import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation; import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; -import org.openecomp.sdc.be.model.operations.api.IResourceOperation; import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.ComponentOperation; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; -import org.openecomp.sdc.be.resources.data.ArtifactData; import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -98,7 +100,6 @@ import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.util.GeneralUtility; @@ -132,25 +133,21 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName"; private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description"; - private static Integer defaultHeatTimeout; - private static final Integer NON_HEAT_TIMEOUT = 0; + public static final String HEAT_ENV_NAME = "heatEnv"; + public static final String HEAT_VF_ENV_NAME = "VfHeatEnv"; + public static final String HEAT_ENV_SUFFIX = "env"; + private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension"; + + // private static Integer defaultHeatTimeout; + // private static final Integer NON_HEAT_TIMEOUT = 0; private static Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class.getName()); private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - @javax.annotation.Resource - private IArtifactOperation artifactOperation; - - // @javax.annotation.Resource - // private IResourceUploader daoUploader; - @javax.annotation.Resource private IInterfaceLifecycleOperation interfaceLifecycleOperation; @javax.annotation.Resource private IUserAdminOperation userOperaton; - // @javax.annotation.Resource - // private ESCatalogDAO esCatalogDao; - @javax.annotation.Resource private IElementOperation elementOperation; @@ -166,9 +163,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { @javax.annotation.Resource private IHeatParametersOperation heatParametersOperation; - @javax.annotation.Resource - private IComponentInstanceOperation resourceInstanceOperation; - @Autowired private ArtifactCassandraDao artifactCassandraDao; @@ -183,62 +177,71 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { @Autowired private IUserBusinessLogic userBusinessLogic; + @Autowired + NodeTemplateOperation nodeTemplateOperation; public ArtifactsBusinessLogic() { - defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes(); - if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) { - defaultHeatTimeout = 60; - } + // defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes(); + // if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) { + // defaultHeatTimeout = 60; + // } } - public static enum ArtifactOperation { + public static enum ArtifactOperationEnum { + Create(), Update(), Delete(), Download(); + } - Create(false), Update(false), Delete(false), Download(false); + public class ArtifactOperationInfo { + private ArtifactOperationEnum artifactOperationEnum; private boolean isExternalApi; + private boolean ignoreLifecycleState; - ArtifactOperation(boolean isExternalApi) { + public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) { + this.artifactOperationEnum = artifactOperationEnum; this.isExternalApi = isExternalApi; + this.ignoreLifecycleState = ignoreLifecycleState; } public boolean isExternalApi() { return isExternalApi; } - public void setExternalApi(boolean isExternalApi) { - this.isExternalApi = isExternalApi; + public boolean ignoreLifecycleState() { + return ignoreLifecycleState; } + + public ArtifactOperationEnum getArtifactOperationEnum() { + return artifactOperationEnum; + } + } // new flow US556184 - public Either, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo, + public Either, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) { return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false); } - public Either, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo, + public Either, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) { - // step 1 - // detect auditing type + + // step 1 - detect auditing type AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5); - Wrapper errorWrapper = new Wrapper<>(); - // step 2 - // check header + // step 2 - check header if (userId == null) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId); handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null); return Either.right(responseFormat); } - // step 3 - // check user existence - // step 4 - // check user's role + // step 3 - check user existence Either userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction); if (userResult.isRight()) { return Either.right(userResult.right().value()); } + // step 4 - check user's role User user = userResult.left().value(); Either validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation); if (validateUserRole.isRight()) { @@ -271,17 +274,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { /** * This Method validates only the Artifact and does not validate user / role / component ect...
* For regular usage use
- * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperation, String, ArtifactDefinition, String, String, String, String, String, String)} + * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)} * * @return */ - public Either, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperation operation, String artifactUniqueId, ArtifactDefinition artifactDefinition, - String origMd5, String originData, String interfaceName, String operationName, String parentId, User user, Component component, boolean shouldLock, boolean inTransaction) { + public Either, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId, + ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, String operationName, String parentId, User user, Component component, boolean shouldLock, boolean inTransaction) { Component parent = component; Wrapper errorWrapper = new Wrapper<>(); AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5); - artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, parentId, auditingAction, user, component, parent, shouldLock, errorWrapper); + artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, parentId, auditingAction, user, component, parent, shouldLock, errorWrapper, inTransaction); Either, ResponseFormat> result; if (errorWrapper.isEmpty()) { @@ -293,43 +296,53 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return result; } - private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo, String parentId, AuditingActionEnum auditingAction, User user, - org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, Wrapper errorWrapper) { - if (operation == ArtifactOperation.Update || operation == ArtifactOperation.Delete || operation == ArtifactOperation.Download) { - Either validateArtifact = validateArtifact(componentId, componentType, artifactId, component, auditingAction, parentId); + private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String parentId, AuditingActionEnum auditingAction, User user, + org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, Wrapper errorWrapper, boolean inTransaction) { + if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) { + Either validateArtifact = validateArtifact(componentId, componentType, artifactId, component, auditingAction, parentId, inTransaction); if (validateArtifact.isRight()) { ResponseFormat responseFormat = validateArtifact.right().value(); handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); errorWrapper.setInnerElement(validateArtifact.right().value()); - } else if (operation == ArtifactOperation.Download) { - artifactInfo = validateArtifact.left().value(); - handleHeatEnvDownload(componentId, user, component, validateArtifact, shouldLock, errorWrapper); + } else { + if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) { + artifactInfo = validateArtifact.left().value(); + handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, shouldLock, errorWrapper); + } } } return artifactInfo; } - private void handleHeatEnvDownload(String componentId, User user, org.openecomp.sdc.be.model.Component component, Either validateArtifact, boolean shouldLock, Wrapper errorWrapper) { + private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either validateArtifact, boolean shouldLock, + Wrapper errorWrapper) { ArtifactDefinition validatedArtifact = validateArtifact.left().value(); if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) { - ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findAny().get(); - ArtifactDefinition heatEnvWithHeatParams = componentInstance.getDeploymentArtifacts().values().stream().filter(p -> p.getUniqueId().equals(validatedArtifact.getUniqueId())).findAny().get(); - Either eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, component, componentInstance.getName(), user, shouldLock); - if (eitherGenerated.isRight()) { - errorWrapper.setInnerElement(eitherGenerated.right().value()); + if (ComponentTypeEnum.SERVICE == component.getComponentType()) { + ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findAny().get(); + Map deploymentArtifacts = componentInstance.getDeploymentArtifacts(); + + ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(validatedArtifact.getUniqueId())).findAny().get(); + Either eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance.getName(), user, shouldLock, componentId); + if (eitherGenerated.isRight()) { + errorWrapper.setInnerElement(eitherGenerated.right().value()); + } } } } private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) { - return artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + boolean needGenerate; + needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && artifactInfo.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())); + return needGenerate; } public Either, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest, boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) { - Either, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB, shouldLock, inTransaction); + Either, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB); if (generated.isRight()) { return generated; } @@ -341,11 +354,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } - private Either, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB, boolean shouldLock, - boolean inTransaction) { + private Either, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) { log.debug("tosca artifact generation"); if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) { - Either generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest, shouldLock, inTransaction); + Either generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest); if (generated.isRight()) { log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right().value()); @@ -370,16 +382,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(Either.left(artifactInfo)); } - private Either, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5, + private Either, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5, String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) { if (interfaceName != null && operationName != null) { interfaceName = interfaceName.toLowerCase(); operationName = operationName.toLowerCase(); } - switch (operation) { + switch (operation.getArtifactOperationEnum()) { case Download: if (artifactGenerationRequired(parent, artifactInfo)) { - return generateToscaArtifact(parent, artifactInfo, false, false, shouldLock, inTransaction); + return generateNotSavedArtifact(parent, artifactInfo, shouldLock, inTransaction); } return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction); case Delete: @@ -389,6 +401,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE) && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) { return handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction); + } else { + if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) { + return handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction); + } } return handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction); case Create: @@ -397,6 +413,87 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return null; } + Either, ResponseFormat> generateNotSavedArtifact(org.openecomp.sdc.be.model.Component parent, ArtifactDefinition artifactInfo, boolean shouldLock, boolean inTransaction) { + Either, ResponseFormat> result; + if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) { + result = generateToscaArtifact(parent, artifactInfo, false, false); + } else { + String heatArtifactId = artifactInfo.getGeneratedFromId(); + Either heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId); + if (heatRes.isRight()) { + log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes.right().value()), ""); + return Either.right(responseFormat); + } + String generatedPayload = generateHeatEnvPayload(heatRes.left().value()); + artifactInfo.setPayloadData(generatedPayload); + result = Either.left(Either.left(artifactInfo)); + } + return result; + } + + private Either, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, + ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { + convertParentType(componentType); + String parentId = parent.getUniqueId(); + Either artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo.getGeneratedFromId()); + ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value(); + + if (origMd5 != null) { + Either validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); + if (validateMd5.isRight()) { + ResponseFormat responseFormat = validateMd5.right().value(); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + + if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) { + + Either payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); + if (payloadEither.isRight()) { + ResponseFormat responseFormat = payloadEither.right().value(); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + } else { // duplicate + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + } + + // lock resource + if (shouldLock) { + Either lockComponent = lockComponent(parent, "Update Artifact - lock "); + if (lockComponent.isRight()) { + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null); + return Either.right(lockComponent.right().value()); + } + } + Either, ResponseFormat> resultOp = null; + try { + resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, origMd5); + return resultOp; + + } finally { + // unlock resource + if (resultOp == null || resultOp.isRight()) { + log.debug("all changes rollback"); + if (false == inTransaction) + titanDao.rollback(); + } else { + log.debug("all changes committed"); + if (false == inTransaction) + titanDao.commit(); + } + if (shouldLock) + componentType = parent.getComponentType(); + NodeTypeEnum nodeType = componentType.getNodeType(); + graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType); + // graphLockOperation.unlockComponent(parentId, parentType); + } + } + /** * * @param componentId @@ -404,13 +501,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param userId * @param componentType * @param parentId - * TODO * @return */ - public Either, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact, boolean shouldLock, boolean inTransaction) { + public Either, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) { if (artifactGenerationRequired(component, csarArtifact)) { - Either generated = csarUtils.createCsar(component, false, false, shouldLock, inTransaction); + Either generated = csarUtils.createCsar(component, false, false); if (generated.isRight()) { log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value()); @@ -424,7 +520,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { public Either, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) { // perform all validation in common flow - Either, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, ArtifactOperation.Download, artifactId, null, null, null, null, null, parentId, containerComponentType); + Either, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Download), artifactId, null, null, null, null, + null, parentId, containerComponentType); if (result.isRight()) { return Either.right(result.right().value()); } @@ -433,19 +530,134 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (insideValue.isLeft()) { artifactDefinition = insideValue.left().value(); } else { - artifactDefinition = insideValue.right().value().getImplementation(); + artifactDefinition = insideValue.right().value().getImplementationArtifact(); } - // for tosca artifacts generated on download without saving - if (artifactDefinition.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactDefinition.getPayloadData() != null) { + // for tosca artifacts and heat env on VF level generated on download without saving + if (artifactDefinition.getPayloadData() != null) { return Either.left(new ImmutablePair(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData())); } return downloadArtifact(artifactDefinition); } - private Either validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId) { + public Either, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) { + // step 1 + // detect auditing type + Map resMap = null; + Either, ResponseFormat> resultOp = null; + + new Wrapper<>(); + // step 2 + // check header + if (userId == null) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId); + + resultOp = Either.right(responseFormat); + return resultOp; + } + // step 3 + // check user existence + // step 4 + // check user's role + + Either userResult = validateUserExists(userId, "get artifacts", false); + if (userResult.isRight()) { + + resultOp = Either.right(userResult.right().value()); + return resultOp; + } + + userResult.left().value(); + + // steps 5 - 6 - 7 + // 5. check service/resource existence + // 6. check service/resource check out + // 7. user is owner of checkout state + org.openecomp.sdc.be.model.Component component = null; + // ComponentInstance resourceInstance = null; + String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; + ComponentParametersView componentFilter = new ComponentParametersView(); + componentFilter.disableAll(); + componentFilter.setIgnoreArtifacts(false); + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) + componentFilter.setIgnoreComponentInstances(false); + + Either validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum.findByParamName(containerComponentType), componentFilter, false); + + if (validateComponent.isRight()) { + resultOp = Either.right(validateComponent.right().value()); + return resultOp; + } + component = validateComponent.left().value(); + Either lockComponent = lockComponent(component, "Update Artifact - lock "); + if (lockComponent.isRight()) { + + resultOp = Either.right(lockComponent.right().value()); + return resultOp; + } + + try { + ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType); + + if (groupType == null) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId); + + resultOp = Either.right(responseFormat); + return resultOp; + + } + if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) { + List list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId); + if (list != null && !list.isEmpty()){ + resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a)); + }else{ + resMap = new HashMap<>(); + } + resultOp = Either.left(resMap); + return resultOp; + } else { + + Either, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType.getNodeType(), false, groupType, componentId ); + if (artifactsMapStatus.isRight()) { + if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId); + resultOp = Either.right(responseFormat); + }else{ + resMap = new HashMap<>(); + resultOp = Either.left(resMap); + } + } else { + resMap = artifactsMapStatus.left().value(); + resultOp = Either.left(resMap); + } + return resultOp; + } + } finally { + // unlock resource + if (resultOp == null || resultOp.isRight()) { + log.debug("all changes rollback"); + titanDao.rollback(); + } else { + log.debug("all changes committed"); + + titanDao.commit(); + } + + componentType = component.getComponentType(); + NodeTypeEnum nodeType = componentType.getNodeType(); + graphLockOperation.unlockComponent(component.getUniqueId(), nodeType); + // graphLockOperation.unlockComponent(parentId, parentType); + } + + } + + private Either validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId, + boolean inTransaction) { // step 9 // check artifact existence - Either artifactResult = artifactOperation.getArtifactById(artifactId, false); + Either artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component.getUniqueId()); if (artifactResult.isRight()) { if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""); @@ -484,7 +696,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(artifactResult.left().value()); } - private Either, ResponseFormat> handleCreate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperation operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType, + private Either, ResponseFormat> handleCreate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { String artifactId = null; @@ -495,8 +707,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.right(payloadEither.right().value()); } byte[] decodedPayload = payloadEither.left().value(); - NodeTypeEnum parentType = convertParentType(componentType); - // lock resource + convertParentType(componentType); if (shouldLock) { Either lockComponent = lockComponent(parent, "Upload Artifact - lock "); @@ -522,11 +733,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private Either, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { - NodeTypeEnum parentType = convertParentType(componentType); + convertParentType(componentType); // lock resource if (shouldLock) { Either lockComponent = lockComponent(parent, "Update Artifact - lock "); + if (lockComponent.isRight()) { handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null); return Either.right(lockComponent.right().value()); @@ -545,7 +757,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - private Either, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperation operation, AuditingActionEnum auditingAction, String artifactId, User user, + private Either, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { Either payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction); @@ -558,7 +770,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction); } - private Either validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperation operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, + private Either validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean inTransaction) { // Md5 validations Either validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); @@ -688,7 +900,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return sb.toString(); } - private Either validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperation operation) { + private Either validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) { if (origMd5 != null) { String encodeBase64Str = GeneralUtility.calculateMD5ByString(originData); @@ -698,7 +910,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5)); } } else { - if (operation == ArtifactOperation.Create) { + if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) { log.debug("Missing md5 header during artifact create"); return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5)); } @@ -711,14 +923,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(true); } - private Either validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperation operation, String artifactId, User user, String interfaceName, String operationName, + private Either validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName, ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) { + Either validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent); + if (validateInformationalArtifactRes.isRight()) { + return Either.right(validateInformationalArtifactRes.right().value()); + } Either validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo); if (validateAndSetArtifactname.isRight()) { return Either.right(validateAndSetArtifactname.right().value()); } - Either artifactById = fetchCurrentArtifact(operation, artifactId); + Either artifactById = findArtifactOnParentComponent(parentComponent, parentId, operation, artifactId); if (artifactById.isRight()) { return Either.right(artifactById.right().value()); } @@ -734,7 +950,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { // This is a patch to block possibility of updating service api fields // through other artifacts flow - if (!operation.equals(ArtifactOperation.Create)) { + if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) { checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL)); } else { checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL)); @@ -746,7 +962,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } // artifactGroupType is not allowed to be updated - if (!operation.equals(ArtifactOperation.Create)) { + if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) { Either validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo); if (validateGroupType.isRight()) { return Either.right(validateGroupType.right().value()); @@ -756,7 +972,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { NodeTypeEnum parentType = convertParentType(componentType); // TODO TEMP !!! - boolean isCreate = operation.equals(ArtifactOperation.Create); + boolean isCreate = operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create; if (isDeploymentArtifact(artifactInfo)) { Either deploymentValidationResult = validateDeploymentArtifact(parentComponent, parentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType); @@ -764,7 +980,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.right(deploymentValidationResult.right().value()); } } else { - artifactInfo.setTimeout(NON_HEAT_TIMEOUT); + artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); /* * if (informationDeployedArtifactsBusinessLogic. isInformationDeployedArtifact(artifactInfo)) { Either validationResult = informationDeployedArtifactsBusinessLogic.validateArtifact( isCreate, artifactInfo, @@ -817,6 +1033,66 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(artifactInfo); } + private Either findArtifactOnParentComponent(Component parentComponent, String parentId, ArtifactOperationInfo operation, String artifactId) { + + Either result = null; + ArtifactDefinition foundArtifact = null; + if (StringUtils.isNotEmpty(artifactId)) { + if (parentComponent.getUniqueId().equals(parentId)) { + if (parentComponent.getDeploymentArtifacts() != null) { + foundArtifact = parentComponent.getDeploymentArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null); + } + if (foundArtifact == null && parentComponent.getArtifacts() != null) { + foundArtifact = parentComponent.getArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null); + } + } else { + ComponentInstance instance = findComponentInstance(parentId, parentComponent); + if (instance.getDeploymentArtifacts() != null) { + foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null); + } + if (foundArtifact == null && instance.getArtifacts() != null) { + foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null); + } + } + } + if (foundArtifact != null && operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) { + log.debug("Artifact {} already exist", artifactId); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel())); + } + if (foundArtifact == null && operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) { + log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "")); + } + if (result == null) { + result = Either.left(foundArtifact); + } + return result; + } + + private Either validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) { + ComponentTypeEnum parentComponentType = parentComponent.getComponentType(); + ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); + Either validationResult = Either.left(true); + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); + if (artifactType == null) { + validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType())); + } else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) { + String artifactTypeName = artifactType.getType(); + ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType(); + Map resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInformationalArtifacts(); + Set validArtifactTypes = resourceInformationalArtifacts.keySet(); + if (!validArtifactTypes.contains(artifactTypeName)) { + validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName)); + } else { + List validResourceType = resourceInformationalArtifacts.get(artifactTypeName).getValidForResourceTypes(); + if (!validResourceType.contains(parentResourceType.name())) { + validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName)); + } + } + } + return validationResult; + } + private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) { if (componentType.equals(ComponentTypeEnum.RESOURCE)) { return NodeTypeEnum.Resource; @@ -829,128 +1105,303 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { public Either, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { + NodeTypeEnum parentType = convertParentType(componentType); - // lock resource - if (shouldLock) { - Either lockComponent = lockComponent(parent, "Delete Artifact - lock resource: "); - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null); - return Either.right(lockComponent.right().value()); - } - } Either, ResponseFormat> resultOp = null; - Either insideEither = null; - StorageOperationStatus error = null; - boolean isLeft = false; - ArtifactDefinition artifactDefinition = null; - Integer artifactParentsCount = 1; + Either, ActionStatus> getArtifactRes = null; + ArtifactDefinition foundArtifact = null; + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + Either getContainerRes = null; + org.openecomp.sdc.be.model.Component fetchedContainerComponent = null; + boolean isDuplicated = false; + String esId = null; + Either needCloneRes = null; try { - if (interfaceType != null && operationName != null) { - log.debug("Try to delete inteface lifecycle artifact {}", artifactId); - - Either result = interfaceLifecycleOperation.deleteInterfaceOperation(parentId, interfaceType, UniqueIdBuilder.buildOperationByInterfaceUniqueId(parentId, interfaceType, operationName), - inTransaction); - isLeft = result.isLeft(); - if (isLeft) { - artifactDefinition = result.left().value().getImplementation(); - insideEither = Either.right(result.left().value()); + if (shouldLock) { + Either lockComponent = lockComponent(parent, "Delete Artifact - lock resource: "); + if (lockComponent.isRight()) { + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null); + resultOp = Either.right(lockComponent.right().value()); } - } else { - log.debug("Try to delete artifact, get parents {}", artifactId); - - Either parentsOfArtifact = artifactOperation.getParentsOfArtifact(artifactId, parentType); - if (parentsOfArtifact.isRight()) { - log.debug("Failed to delete entry on graph for artifact {}", artifactId); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(parentsOfArtifact.right().value()), ""); + } + if (resultOp == null) { + log.debug("Going to fetch the container component {}. ", parent.getUniqueId()); + getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId()); + if (getContainerRes.isRight()) { + log.debug("Failed to fetch the container component {}. ", parentId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()), artifactId); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + } + if (resultOp == null) { + fetchedContainerComponent = getContainerRes.left().value(); + log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId()); + getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType); + if (getArtifactRes.isRight()) { + log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent.getUniqueId()); + responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right().value(), artifactId); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); resultOp = Either.right(responseFormat); } else { - - artifactParentsCount = parentsOfArtifact.left().value(); - log.debug("Number of parents nodes on graph for artifact {} is {}", artifactId, artifactParentsCount); - - Either result = artifactOperation.removeArifactFromResource(parentId, artifactId, parentType, false, true); - isLeft = result.isLeft(); - if (isLeft) { - log.debug("Artifact removed from graph {}", artifactId); - - artifactDefinition = result.left().value(); - insideEither = Either.left(result.left().value()); - } else { - error = result.right().value(); - } + foundArtifact = getArtifactRes.left().value().getLeft(); + esId = foundArtifact.getEsId(); } } - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - if (isLeft) { - StorageOperationStatus deleteIfNotOnGraph = StorageOperationStatus.OK; - if (artifactParentsCount < 2) { - log.debug("Number of parent nodes is 1. Need to delete from ES {}", artifactId); - deleteIfNotOnGraph = deleteIfNotOnGraph(artifactId, artifactDefinition.getEsId(), true); + if (resultOp == null && StringUtils.isNotEmpty(esId)) { + needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent.getComponentType())); + if (needCloneRes.isRight()) { + log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes.right().value()), foundArtifact.getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); } - if (deleteIfNotOnGraph.equals(StorageOperationStatus.OK)) { - if (artifactDefinition.getMandatory() || artifactDefinition.getServiceApi()) { - log.debug("Artifact is mandatory or service API. Clean all fields for {}", artifactId); - artifactDefinition.setEsId(""); - artifactDefinition.setArtifactName(""); - artifactDefinition.setDescription(""); - artifactDefinition.setApiUrl(""); - artifactDefinition.setArtifactChecksum(""); - setDefaultArtifactTimeout(artifactDefinition.getArtifactGroupType(), artifactDefinition); - artifactDefinition.setArtifactUUID(""); - long time = System.currentTimeMillis(); - artifactDefinition.setPayloadUpdateDate(time); - artifactDefinition.setHeatParameters(null); - artifactDefinition.setHeatParamsUpdateDate(null); - Either resStatus = null; - if (artifactParentsCount < 2) { - log.debug("Only one parent , clean existing placeholder for {}", artifactId); - resStatus = artifactOperation.updateArifactOnResource(artifactDefinition, parentId, artifactId, parentType, true); - } else { - log.debug("more than one parent , create new placeholder for {}", artifactId); - artifactDefinition.setUniqueId(null); - resStatus = artifactOperation.addArifactToComponent(artifactDefinition, parentId, parentType, true, true); - } - if (resStatus.isRight()) { - log.debug("Failed to clean placeholder for {}", artifactId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(resStatus.right().value()), artifactDefinition.getArtifactDisplayName()); - resultOp = Either.right(responseFormat); - } else { - log.debug("Placeholder was cleaned for {}", artifactId); + } + if (resultOp == null) { + Either updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes.left().value()); + if (updatedArtifactRes.isRight()) { + log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes.right().value()), foundArtifact.getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } else { + isDuplicated = updatedArtifactRes.left().value().getDuplicated(); + } + } - ArtifactDefinition artifactUfterChange = resStatus.left().value(); + if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated)) { + log.debug("Going to delete the artifact {} from the database. ", artifactId); + CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId); + if (cassandraStatus != CassandraOperationStatus.OK) { + log.debug("Failed to delete the artifact {} from the database. ", artifactId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(convertToStorageOperationStatus(cassandraStatus)), foundArtifact.getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + } + if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { - insideEither = Either.left(artifactUfterChange); - resultOp = Either.left(insideEither); - } - } else { - log.debug("Artifact isn't mandatory/service API. Removed. {}", artifactId); - resultOp = Either.left(insideEither); + List updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes.left().value().getRight().getGroupInstances()); + if (CollectionUtils.isNotEmpty(updatedGroupInstances)) { + Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances); + if (status.isRight()) { + log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId()); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); } - - } else { - log.debug("failed to delete artifact from ES {} status {}", artifactId, deleteIfNotOnGraph); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(deleteIfNotOnGraph), artifactDefinition.getArtifactDisplayName()); + } + } + if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType); + if (status != StorageOperationStatus.OK) { + log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact.getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); resultOp = Either.right(responseFormat); } - } else { - log.debug("Failed to delete entry on graph for artifact {}", artifactId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), ""); - resultOp = Either.right(responseFormat); } - handleAuditing(auditingAction, parent, parentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null); + if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) { + List updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent.getGroups()); + if (CollectionUtils.isNotEmpty(updatedGroups)) { + Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, componentType, updatedGroups); + if (status.isRight()) { + log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId()); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + } + } + if (resultOp == null) { + resultOp = Either.left(Either.left(foundArtifact)); + handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null); + } return resultOp; } finally { if (shouldLock) { unlockComponent(resultOp, parent, inTransaction); } } + } + + private List getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List groups) { + List updatedGroups = new ArrayList<>(); + boolean isUpdated = false; + if (groups != null) { + for (GroupDefinition group : groups) { + isUpdated = false; + if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) { + group.getArtifacts().remove(artifactId); + isUpdated = true; + } + if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(foundArtifact.getArtifactUUID())) { + group.getArtifacts().remove(foundArtifact.getArtifactUUID()); + isUpdated = true; + } + if (isUpdated) { + updatedGroups.add(group); + } + } + } + return updatedGroups; + } + + private List getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List groupInstances) { + List updatedGroupInstances = new ArrayList<>(); + if (CollectionUtils.isNotEmpty(groupInstances)) { + boolean isUpdated = false; + for (GroupInstance groupInstance : groupInstances) { + isUpdated = false; + if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactId)) { + groupInstance.getArtifacts().remove(artifactId); + isUpdated = true; + } + if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(foundArtifact.getArtifactUUID())) { + groupInstance.getArtifacts().remove(foundArtifact.getArtifactUUID()); + isUpdated = true; + } + if (isUpdated) { + updatedGroupInstances.add(groupInstance); + } + } + } + return updatedGroupInstances; + } + + private Either deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) { + + Either result; + boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi(); + String componentId = component.getUniqueId(); + String instanceId = componentId.equals(parentId) ? null : parentId; + if (isMandatory) { + log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId); + resetMandatoryArtifactFields(foundArtifact); + result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId); + } else if (cloneIsNeeded) { + log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId); + result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false); + } else { + log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId); + result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false); + } + return result; + } + + private Either, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) { + + Either, ActionStatus> result = null; + Map artifacts = new HashMap<>(); + ComponentInstance foundInstance = null; + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) { + Optional componentInstanceOpt = fetchedContainerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(parentId)).findFirst(); + if (!componentInstanceOpt.isPresent()) { + result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER); + } else { + foundInstance = componentInstanceOpt.get(); + fetchArtifactsFromInstance(artifactId, artifacts, foundInstance); + } + } else { + fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts); + } + if (result == null) { + if (artifacts.containsKey(artifactId)) { + result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance)); + } else { + result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND); + } + } + return result; + } + + private void fetchArtifactsFromComponent(String artifactId, Component component, Map artifacts) { + Map currArtifacts; + if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) { + currArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + if (MapUtils.isNotEmpty(currArtifacts)) { + artifacts.putAll(currArtifacts); + } + } + if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) { + currArtifacts = component.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + if (MapUtils.isNotEmpty(currArtifacts)) { + artifacts.putAll(currArtifacts); + } + } + if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) { + currArtifacts = component.getToscaArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + if (MapUtils.isNotEmpty(currArtifacts)) { + artifacts.putAll(currArtifacts); + } + } + } + + private void fetchArtifactsFromInstance(String artifactId, Map artifacts, ComponentInstance instance) { + Map currArtifacts; + if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) { + currArtifacts = instance.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + if (MapUtils.isNotEmpty(currArtifacts)) { + artifacts.putAll(currArtifacts); + } + } + if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) { + currArtifacts = instance.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + if (MapUtils.isNotEmpty(currArtifacts)) { + artifacts.putAll(currArtifacts); + } + } + } + + private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) { + StorageOperationStatus result; + switch (cassandraStatus) { + case OK: + result = StorageOperationStatus.OK; + break; + case NOT_FOUND: + result = StorageOperationStatus.NOT_FOUND; + break; + case CLUSTER_NOT_CONNECTED: + case KEYSPACE_NOT_CONNECTED: + result = StorageOperationStatus.CONNECTION_FAILURE; + break; + default: + result = StorageOperationStatus.GENERAL_ERROR; + break; + } + return result; + } + private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) { + if (fetchedArtifact != null) { + log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId()); + fetchedArtifact.setEsId(""); + fetchedArtifact.setArtifactName(""); + fetchedArtifact.setDescription(""); + fetchedArtifact.setApiUrl(""); + fetchedArtifact.setArtifactChecksum(""); + nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact); + fetchedArtifact.setArtifactUUID(""); + long time = System.currentTimeMillis(); + fetchedArtifact.setPayloadUpdateDate(time); + fetchedArtifact.setHeatParameters(null); + fetchedArtifact.setHeatParamsUpdateDate(null); + } + } + + private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) { + StorageOperationStatus error = StorageOperationStatus.OK; + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + log.debug("Need to re-generate customization UUID for instance {}", instanceId); + error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId); + } + return error; } private Either, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) { - Either artifactById = artifactOperation.getArtifactById(artifactId, false); + Either artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent.getUniqueId()); if (artifactById.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value()); log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus.name()); @@ -971,16 +1422,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(insideEither); } - private Either fetchCurrentArtifact(ArtifactOperation operation, String artifactId) { - Either artifactById = artifactOperation.getArtifactById(artifactId, true); - if (!operation.equals(ArtifactOperation.Create) && artifactById.isRight()) { + private Either fetchCurrentArtifact(String parentId, ArtifactOperationInfo operation, String artifactId) { + Either artifactById = artifactToscaOperation.getArtifactById(parentId, artifactId); + if (!(operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) && artifactById.isRight()) { // in case of update artifact must be - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId); BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); } - if (operation.equals(ArtifactOperation.Create) && artifactById.isLeft()) { + if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && artifactById.isLeft()) { log.debug("Artifact {} already exist", artifactId); return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); } @@ -992,17 +1442,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(currentArtifactInfo); } - private Either handleArtifactLabel(String componentId, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName, + private Either handleArtifactLabel(String componentId, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName, ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType, boolean inTransaction) { String artifactLabel = artifactInfo.getArtifactLabel(); if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingArtifactInformationError, "Artifact Update / Upload", "artifactLabel"); BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel"); log.debug("missing artifact logical name for component {}", componentId); return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL)); } - if (operation.equals(ArtifactOperation.Create) && !artifactInfo.getMandatory()) { + if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && !artifactInfo.getMandatory()) { if (operationName != null) { if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) { @@ -1016,6 +1465,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (displayName == null || displayName.isEmpty()) displayName = artifactLabel; displayName = ValidationUtils.cleanArtifactDisplayName(displayName); + // if (!ValidationUtils.validateArtifactDisplayName(displayName)) { + // log.debug("Invalid format form Artifact displayName : {}", displayName); + // return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + // } artifactInfo.setArtifactDisplayName(displayName); if (!ValidationUtils.validateArtifactLabel(artifactLabel)) { @@ -1033,7 +1486,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { log.debug("Invalid lenght form Artifact label : {}", artifactLabel); return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH))); } - if (!validateLabelUniqueness(componentId, artifactLabel, componentType, inTransaction)) { + if (!validateLabelUniqueness(componentId, artifactLabel, componentType)) { log.debug("Non unique Artifact label : {}", artifactLabel); return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel)); } @@ -1041,21 +1494,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { artifactInfo.setArtifactLabel(artifactLabel); if (currentArtifactInfo != null && !currentArtifactInfo.getArtifactLabel().equals(artifactInfo.getArtifactLabel())) { - log.info("Logical artifact's name cannot be changed {}", artifactId); + log.info("Logical artifact's name cannot be changed {}", artifactId); return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED)); } return Either.left(ActionStatus.OK); } - private boolean validateLabelUniqueness(String parentId, String artifactLabel, ComponentTypeEnum componentType, boolean inTransaction) { + private boolean validateLabelUniqueness(String parentId, String artifactLabel, ComponentTypeEnum componentType) { boolean isUnique = true; - NodeTypeEnum parentType; if (componentType.equals(ComponentTypeEnum.RESOURCE)) { - parentType = NodeTypeEnum.Resource; } else { - parentType = NodeTypeEnum.Service; } - Either, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(parentId, parentType, inTransaction); + // Either, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(parentId, parentType, inTransaction); + Either, StorageOperationStatus> artifacts = artifactToscaOperation.getArtifacts(parentId); if (artifacts.isLeft()) { for (String label : artifacts.left().value().keySet()) { if (label.equals(artifactLabel)) { @@ -1065,10 +1516,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } if (componentType.equals(ComponentTypeEnum.RESOURCE)) { - Either, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(parentId, true, inTransaction); + Either, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(parentId, true, true); if (allInterfacesOfResource.isLeft()) { for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) { - for (Operation operation : interace.getOperations().values()) { + for (Operation operation : interace.getOperationsMap().values()) { if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) { isUnique = false; break; @@ -1088,9 +1539,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload); Either, ResponseFormat> resultOp = null; Either insideEither = null; - + ComponentInstance foundInstance = findComponentInstance(parentId, parent); + String instanceId = null; + String instanceName = null; + if (foundInstance != null) { + instanceId = foundInstance.getUniqueId(); + instanceName = foundInstance.getName(); + } if (artifactData == null) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Upload Artifact"); BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact"); log.debug("Failed to create artifact object for ES."); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); @@ -1104,7 +1560,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { boolean isLeft = false; String artifactUniqueId = null; - ArtifactDefinition artifactDefinition = null; StorageOperationStatus error = null; if (interfaceType != null && operationName != null) { // lifecycle artifact @@ -1115,7 +1570,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { isLeft = result.isLeft(); if (isLeft) { artifactUniqueId = result.left().value().getImplementation().getUniqueId(); - artifactDefinition = result.left().value().getImplementation(); + result.left().value().getImplementation(); insideEither = Either.right(result.left().value()); resultOp = Either.left(insideEither); @@ -1124,17 +1579,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } else { // information/deployment/api aritfacts - log.debug("Try to create entry on graph"); + log.trace("Try to create entry on graph"); NodeTypeEnum nodeType = convertParentType(componentTypeEnum); - Either result = artifactOperation.addArifactToComponent(artifactInfo, parentId, nodeType, true, true); + Either result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId); isLeft = result.isLeft(); if (isLeft) { artifactUniqueId = result.left().value().getUniqueId(); - artifactDefinition = result.left().value(); + result.left().value(); insideEither = Either.left(result.left().value()); resultOp = Either.left(insideEither); + + error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum); + if (error != StorageOperationStatus.OK) { + isLeft = false; + } + } else { error = result.right().value(); } @@ -1147,14 +1608,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { log.debug("Artifact saved into ES - {}", artifactUniqueId); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, null); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); return resultOp; } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Upload Artifact"); BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact"); log.debug("Failed to save the artifact."); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, null); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); resultOp = Either.right(responseFormat); return resultOp; @@ -1162,13 +1622,21 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } else { log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName()); ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName()); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName); resultOp = Either.right(responseFormat); return resultOp; } } + private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) { + ComponentInstance foundInstance = null; + if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) { + foundInstance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null); + } + return foundInstance; + } + private Either validateDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) { Either result = Either.left(true); @@ -1178,7 +1646,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); - Map resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType); + Map resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType); if (responseWrapper.isEmpty()) { validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts); @@ -1199,7 +1667,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { // if (parentComponent instanceof Resource) { Resource resource = (Resource) parentComponent; ResourceTypeEnum resourceType = resource.getResourceType(); - DeploymentArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType()); + ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType()); if (config == null) { responseWrapper.setInnerElement(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType())); } else { @@ -1232,7 +1700,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } case HEAT_ENV: { result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, userId, isCreate, artifactInfo, parentType); - artifactInfo.setTimeout(NON_HEAT_TIMEOUT); + artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); break; } case DCAE_INVENTORY_TOSCA: @@ -1244,7 +1712,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { case DCAE_INVENTORY_EVENT: // No specific validation default: { - artifactInfo.setTimeout(NON_HEAT_TIMEOUT); + artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); } } @@ -1256,7 +1724,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return result; } - private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper responseWrapper, ArtifactTypeEnum artifactType, Map resourceDeploymentArtifacts) { + private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper responseWrapper, ArtifactTypeEnum artifactType, Map resourceDeploymentArtifacts) { if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) { ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()); responseWrapper.setInnerElement(responseFormat); @@ -1264,8 +1732,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - private Map fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) { - Map resourceDeploymentArtifacts = null; + private Map fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) { + Map resourceDeploymentArtifacts = null; if (parentType.equals(NodeTypeEnum.Resource)) { resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) { @@ -1279,14 +1747,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { public void validateArtifactTypeExists(Wrapper responseWrapper, ArtifactDefinition artifactInfo) { ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); if (artifactType == null) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.GENERAL_ERROR); + ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()); responseWrapper.setInnerElement(responseFormat); log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType()); } } - private DeploymentArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) { - DeploymentArtifactTypeConfig retConfig = null; + private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) { + ArtifactTypeConfig retConfig = null; String fileType = artifactType.getType(); if (parentType.equals(NodeTypeEnum.Resource)) { retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts().get(fileType); @@ -1301,14 +1769,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private Either extractHeatParameters(ArtifactDefinition artifactInfo) { // extract heat parameters if (artifactInfo.getPayloadData() != null) { - String heatDecodedPayload = GeneralUtility.isBase64Encoded(artifactInfo.getPayloadData()) ? new String(Base64.decodeBase64(artifactInfo.getPayloadData())) : new String(artifactInfo.getPayloadData()); + String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData())); Either, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType()); if (heatParameters.isRight() && (!heatParameters.right().value().equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) { log.info("failed to parse heat parameters "); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType()); return Either.right(responseFormat); } else if (heatParameters.isLeft() && heatParameters.left().value() != null) { - artifactInfo.setHeatParameters(heatParameters.left().value()); + artifactInfo.setListHeatParameters(heatParameters.left().value()); } } return Either.left(true); @@ -1319,7 +1787,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { public void validateFileExtension(Wrapper responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) { String fileType = artifactType.getType(); List acceptedTypes = null; - DeploymentArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig(); + ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig(); if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) { log.debug("parent type of artifact can be either resource or service"); responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -1365,13 +1833,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (errorWrapper.isEmpty()) { // Validate Heat Exist - validateHeatExist(artifactInfo.getUniqueId(), errorWrapper, heatMDWrapper, getDeploymentArtifacts(parentComponent, parentType, parentId)); + validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent.getComponentType()); } - if (errorWrapper.isEmpty() && isCreate) { - // Validate Only Single HeatEnv Artifact - validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId); - } + // if (errorWrapper.isEmpty() && isCreate) { + // // Validate Only Single HeatEnv Artifact + // validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId); + // } if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) { fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement()); @@ -1406,13 +1874,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { public Either fillArtifactPayload(Wrapper payloadWrapper, ArtifactDefinition artifactMD) { Either result = Either.left(true); Either eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD.getEsId()); - // Either eitherArtifactData = - // esCatalogDao.getArtifact(artifactMD.getEsId()); if (eitherArtifactData.isLeft()) { byte[] data = eitherArtifactData.left().value().getDataAsArray(); - if (!GeneralUtility.isBase64Encoded(data)) { - data = Base64.encodeBase64(data); - } + data = Base64.encodeBase64(data); payloadWrapper.setInnerElement(data); } else { StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value()); @@ -1425,11 +1889,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { @SuppressWarnings("unchecked") private void validateEnvVsHeat(Wrapper errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) { - - String envPayload = (GeneralUtility.isBase64Encoded(envArtifact.getPayloadData())) ? new String(Base64.decodeBase64(envArtifact.getPayloadData())) : new String(envArtifact.getPayloadData()); + String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData())); Map heatEnvToscaJson = (Map) new Yaml().load(envPayload); - - String heatDecodedPayload = (GeneralUtility.isBase64Encoded(heatPayloadData)) ? new String(Base64.decodeBase64(heatPayloadData)) : new String(heatPayloadData); + String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData)); Map heatToscaJson = (Map) new Yaml().load(heatDecodedPayload); Either, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS); @@ -1455,7 +1917,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private void validateValidYaml(Wrapper errorWrapper, ArtifactDefinition artifactInfo) { YamlToObjectConverter yamlConvertor = new YamlToObjectConverter(); - boolean isYamlValid = yamlConvertor.isValidYaml(artifactInfo.getPayloadData()); + boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData()); if (!isYamlValid) { ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType()); errorWrapper.setInnerElement(responseFormat); @@ -1463,12 +1925,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } + @SuppressWarnings("restriction") public boolean isValidXml(byte[] xmlToParse) { XMLReader parser = new SAXParser(); boolean isXmlValid = true; try { parser.parse(new InputSource(new ByteArrayInputStream(xmlToParse))); } catch (IOException | SAXException e) { + log.debug("Xml is invalid : {}", e.getMessage(), e); isXmlValid = false; } return isXmlValid; @@ -1479,6 +1943,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { try { gson.fromJson(parsed, Object.class); } catch (Exception e) { + log.debug("Json is invalid : {}", e.getMessage(), e); return false; } return true; @@ -1531,31 +1996,40 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - private void validateHeatExist(String heatEnvId, Wrapper errorWrapper, Wrapper heatArtifactMDWrapper, Collection parentDeploymentArtifacts) { - boolean heatFound = false; - Either res = artifactOperation.getHeatArtifactByHeatEnvId(heatEnvId, true); + private void validateHeatExist(String componentId, String parentRiId, Wrapper errorWrapper, Wrapper heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType, + ComponentTypeEnum componentType) { + Either res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType); if (res.isRight()) { + ResponseFormat responseFormat; + if (res.right().value() == StorageOperationStatus.NOT_FOUND) { + responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT); + } else { + responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT); + } + errorWrapper.setInnerElement(responseFormat); + return; } ArtifactDefinition heatArtifact = res.left().value(); - Iterator parentArtifactsItr = parentDeploymentArtifacts.iterator(); - while (!heatFound && parentArtifactsItr.hasNext()) { - ArtifactDefinition currArtifact = parentArtifactsItr.next(); - if (heatArtifact.getUniqueId().equals(currArtifact.getUniqueId())) { - heatFound = true; - heatArtifactMDWrapper.setInnerElement(currArtifact); - log.trace("In validateHeatExist found artifact {}", currArtifact); - /* - * ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(currArtifact.getArtifactType()); if(artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET){ - * heatFound = true; } if (heatFound) { heatArtifactMDWrapper.setInnerElement(currArtifact); } - */ - } - } - if (!heatFound) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT); - errorWrapper.setInnerElement(responseFormat); - log.debug("Can't create heat env artifact because No heat Artifact exist."); - } + heatArtifactMDWrapper.setInnerElement(heatArtifact); + // Iterator parentArtifactsItr = parentDeploymentArtifacts.iterator(); + // while (!heatFound && parentArtifactsItr.hasNext()) { + // ArtifactDefinition currArtifact = parentArtifactsItr.next(); + // if (heatArtifact.getUniqueId().equals(currArtifact.getUniqueId())) { + // heatFound = true; + // heatArtifactMDWrapper.setInnerElement(currArtifact); + // log.trace("In validateHeatExist found artifact {}", currArtifact); + // /* + // * ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(currArtifact.getArtifactType()); if(artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET){ + // * heatFound = true; } if (heatFound) { heatArtifactMDWrapper.setInnerElement(currArtifact); } + // */ + // } + // } + // if (!heatFound) { + // ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT); + // errorWrapper.setInnerElement(responseFormat); + // log.debug("Can't create heat env artifact because No heat Artifact exist."); + // } } @@ -1563,7 +2037,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel()); // timeout > 0 for HEAT artifacts Integer timeout = artifactInfo.getTimeout(); - Integer defaultTimeout = (isCreate) ? defaultHeatTimeout : currentArtifact.getTimeout(); + Integer defaultTimeout = (isCreate) ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout(); if (timeout == null) { artifactInfo.setTimeout(defaultTimeout); // HEAT artifact but timeout is invalid @@ -1594,7 +2068,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private Either validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) { if (artifactInfo.getHeatParameters() != null) { - for (HeatParameterDefinition heatParam : artifactInfo.getHeatParameters()) { + for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) { String parameterType = heatParam.getType(); HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType); String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType(); @@ -1605,7 +2079,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam); if (validateAndUpdateProperty != StorageOperationStatus.OK) { - log.debug("Heat parameter {} is invalid. Status is: {}", heatParam.getName(), validateAndUpdateProperty); + log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty); ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE; ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName()); return Either.right(responseFormat); @@ -1617,16 +2091,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { public List getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) { List deploymentArtifacts = new ArrayList<>(); - if (parentComponent.getDeploymentArtifacts() != null && ciId != null) { - if (NodeTypeEnum.ResourceInstance == parentType) { + if (parentComponent.getDeploymentArtifacts() != null) { + if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) { Either getRI = getRIFromComponent(parentComponent, ciId, null, null, null); if (getRI.isRight()) { return deploymentArtifacts; } ComponentInstance ri = getRI.left().value(); - deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values()); - } else { - deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values()); + if(ri.getDeploymentArtifacts() != null){ + deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values()); + } + } else if(parentComponent.getDeploymentArtifacts() !=null){ + deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values()); } } return deploymentArtifacts; @@ -1691,105 +2167,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } - private Either fetchCurrentArtifact(boolean isCreate, String artifactId) { - Either artifactById = artifactOperation.getArtifactById(artifactId, true); - if (isCreate == false && artifactById.isRight()) { - // in case of update artifact must be - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId); - BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); - log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); - } - if (isCreate && artifactById.isLeft()) { - log.debug("Artifact {} already exist", artifactId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); - } - ArtifactDefinition currentArtifactInfo = null; - if (artifactById.isLeft()) { - // get previous value - currentArtifactInfo = artifactById.left().value(); - } - return Either.left(currentArtifactInfo); - } - - private Either handleArtifactLabel(String resourceId, boolean isCreate, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName, ArtifactDefinition currentArtifactInfo, - NodeTypeEnum parentType) { - String artifactLabel = artifactInfo.getArtifactLabel(); - - if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingArtifactInformationError, "Artifact Update / Upload", "artifactLabel"); - BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel"); - log.debug("missing artifact logical name for component {}", resourceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL)); - } - if (isCreate && !artifactInfo.getMandatory()) { - - if (operationName != null) { - if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) { - log.debug("artifact label cannot be set {}", artifactLabel); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED)); - } else { - artifactLabel = operationName; - } - } - String displayName = ValidationUtils.cleanArtifactDisplayName(artifactLabel); - artifactInfo.setArtifactDisplayName(displayName); - - if (!ValidationUtils.validateArtifactLabel(artifactLabel)) { - log.debug("Invalid format form Artifact label : {}", artifactLabel); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel); - - if (artifactLabel.isEmpty()) { - log.debug("missing normalized artifact logical name for component {}", resourceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL)); - } - - if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) { - log.debug("Invalid lenght form Artifact label : {}", artifactLabel); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH))); - } - if (!validateLabelUniqueness(resourceId, artifactLabel, parentType)) { - log.debug("Non unique Artifact label : {}", artifactLabel); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel)); - } - } - artifactInfo.setArtifactLabel(artifactLabel); - - if (currentArtifactInfo != null && !currentArtifactInfo.getArtifactLabel().equals(artifactInfo.getArtifactLabel())) { - log.info("Logical artifact's name cannot be changed {}", artifactId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED)); - } - return Either.left(ActionStatus.OK); - } - - private boolean validateLabelUniqueness(String parentId, String artifactLabel, NodeTypeEnum parentType) { - boolean isUnique = true; - Either, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(parentId, parentType, true); - if (artifacts.isLeft()) { - for (String label : artifacts.left().value().keySet()) { - if (label.equals(artifactLabel)) { - isUnique = false; - break; - } - } - } - if (parentType.equals(NodeTypeEnum.Resource)) { - Either, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(parentId, true); - if (allInterfacesOfResource.isLeft()) { - for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) { - for (Operation operation : interace.getOperations().values()) { - if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) { - isUnique = false; - break; - } - } - } - } - } - return isUnique; - } + /* + * private Either fetchCurrentArtifact(boolean isCreate, String artifactId) { Either artifactById = artifactToscaOperation.getArtifactById(artifactId); if (isCreate + * == false && artifactById.isRight()) { // in case of update artifact must be BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId); + * BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); return + * Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); } if (isCreate && artifactById.isLeft()) { log.debug("Artifact {} already exist", artifactId); return + * Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); } ArtifactDefinition currentArtifactInfo = null; if (artifactById.isLeft()) { // get previous value + * currentArtifactInfo = artifactById.left().value(); } return Either.left(currentArtifactInfo); } + */ private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) { String id = artifactId; @@ -1812,7 +2197,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private Either validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) { if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingArtifactInformationError, "Artifact Upload / Update"); BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel"); log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE)); @@ -1829,7 +2213,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { allArtifactTypes = elementOperation.getAllArtifactTypes(); } if (allArtifactTypes.isRight()) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidConfigurationError, "Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name()); BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name()); log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right().value()); return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId)); @@ -1844,7 +2227,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } if (!artifactTypeExist) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidTypeError, "Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName()); BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName()); log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType())); @@ -1855,7 +2237,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private Either, ActionStatus> getDeploymentArtifactTypes(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) { - Map deploymentArtifacts = null; + Map deploymentArtifacts = null; List artifactTypes = new ArrayList(); if (parentType.equals(NodeTypeEnum.Service)) { @@ -2016,7 +2398,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID()); if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) { - checkAndSetUnupdatableHeatParams(artifactInfo.getHeatParameters(), currentArtifact.getHeatParameters()); + checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters()); } } @@ -2110,7 +2492,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { Either insideEither = null; if (artifactData == null) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Update Artifact"); BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact"); log.debug("Failed to create artifact object for ES."); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); @@ -2118,111 +2499,96 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { resultOp = Either.right(responseFormat); return resultOp; } - log.debug("Try to update entry on graph"); + log.trace("Try to update entry on graph"); String artifactUniqueId = null; - ArtifactDefinition artifactDefinition = null; + ArtifactDefinition artifactDefinition = artifactInfo; StorageOperationStatus error = null; boolean isLeft = false; if (interfaceType != null && operationName != null) { // lifecycle artifact - Operation operation = convertToOperation(artifactInfo, operationName); - - Either result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation); + /* + * Operation operation = convertToOperation(artifactInfo, operationName); + * + * Either result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation); + * + * isLeft = result.isLeft(); if (isLeft) { artifactUniqueId = result.left().value().getUniqueId(); artifactDefinition = result.left().value().getImplementation(); + * + * insideEither = Either.right(result.left().value()); resultOp = Either.left(insideEither); } else { error = result.right().value(); } + */ + } else { + log.debug("Enty on graph is updated. Update artifact in ES"); + boolean res = true; + // Changing previous and current artifactId for auditing + prevArtifactId = currArtifactId; + currArtifactId = artifactDefinition.getUniqueId(); - isLeft = result.isLeft(); - if (isLeft) { - artifactUniqueId = result.left().value().getUniqueId(); - artifactDefinition = result.left().value().getImplementation(); + NodeTypeEnum convertParentType = convertParentType(componentType); - insideEither = Either.right(result.left().value()); - resultOp = Either.left(insideEither); + if (decodedPayload == null) { + if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) { + Either artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition.getEsId()); + // Either + // artifactfromES = daoUploader.getArtifact(artifactId); + if (artifactFromCassandra.isRight()) { + log.debug("Failed to get artifact data from ES for artifact id {}", artifactId); + error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error)); + handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + return resultOp; + } + // clone data to new artifact + artifactData.setData(artifactFromCassandra.left().value().getData()); + artifactData.setId(artifactFromCassandra.left().value().getId()); + } } else { - error = result.right().value(); + if (artifactDefinition.getEsId() == null) { + artifactDefinition.setEsId(artifactDefinition.getUniqueId()); + artifactData.setId(artifactDefinition.getUniqueId()); + } } - } else { - NodeTypeEnum convertParentType = convertParentType(componentType); - Either result = artifactOperation.updateArifactOnResource(artifactInfo, parentId, artifactId, convertParentType, true); + Either result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId); isLeft = result.isLeft(); if (isLeft) { artifactUniqueId = result.left().value().getUniqueId(); artifactDefinition = result.left().value(); + String artifactType = artifactInfo.getArtifactType(); + if (NodeTypeEnum.Resource == convertParentType + && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))) { + /* + * if (!artifactUniqueId.equals(artifactId)) { artifactToscaOperation.updateHeatEnvArtifact(parentId, null, artifactId, artifactUniqueId, convertParentType); + * + * } else { if (!artifactInfo.getArtifactChecksum().equals(artifactDefinition.getArtifactChecksum())) { Either heatEnvEither = + * artifactToscaOperation.getHeatEnvByGeneratedFromId(artifactUniqueId); if (heatEnvEither.isLeft()) { artifactToscaOperation.updateHeatEnvPlaceholder(heatEnvEither.left().value(), parentId); + * + * } } } + */ + } + error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType); insideEither = Either.left(result.left().value()); resultOp = Either.left(insideEither); + if (error != StorageOperationStatus.OK) { + isLeft = false; + } + } else { error = result.right().value(); } - } - if (isLeft) { - log.debug("Enty on graph is updated. Update artifact in ES"); - boolean res; - // Changing previous and current artifactId for auditing - prevArtifactId = currArtifactId; - currArtifactId = artifactDefinition.getUniqueId(); + if (isLeft) { - if (!artifactDefinition.getUniqueId().equals(artifactId)) { - // different ids ==> artifact node was cloned . - // if no data in request get from ES - if (decodedPayload == null) { - if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) { - Either artifactFromCassandra = artifactCassandraDao.getArtifact(artifactId); - // Either - // artifactfromES = daoUploader.getArtifact(artifactId); - if (artifactFromCassandra.isRight()) { - log.debug("Failed to get artifact data from ES for artifact id {}", artifactId); - StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus)); - handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - return resultOp; - } - // clone data to new artifact - artifactData.setData(artifactFromCassandra.left().value().getData()); - } - } - artifactData.setId(artifactDefinition.getUniqueId()); // create new entry in ES res = true; if (artifactData.getData() != null) { + if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) + artifactData.setId(artifactDefinition.getEsId()); res = saveArtifacts(artifactData, parentId, false); - // set on graph object id of artifact in ES! - if (res) { - artifactInfo.setEsId(artifactData.getId()); - Either updateArifactRes = artifactOperation.updateArifactDefinition(artifactInfo, true); - if (updateArifactRes.isRight()) { - log.debug("Failed to update artifact on graph - {}", artifactId); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value())); - handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - return resultOp; - - } else { - insideEither = Either.left(updateArifactRes.left().value()); - resultOp = Either.left(insideEither); - } - } - } - } else { - res = true; - if (artifactData.getData() != null) { - // override artifact in ES - res = saveArtifacts(artifactData, parentId, true); - if (res && artifactDefinition.getMandatory()) { - artifactInfo.setEsId(artifactData.getId()); - Either updateArifactRes = artifactOperation.updateArifactDefinition(artifactInfo, true); - if (updateArifactRes.isRight()) { - log.debug("Failed to update artifact on graph - {}", artifactId); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()), artifactId); - handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - return resultOp; - } - } } } + if (res) { log.debug("Artifact saved into ES - {}", artifactUniqueId); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); @@ -2230,7 +2596,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { // resultOp = Either.left(result.left().value()); // return resultOp; } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Update Artifact"); BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact"); log.debug("Failed to save the artifact."); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); @@ -2238,12 +2603,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { resultOp = Either.right(responseFormat); // return resultOp; } - } else { - log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactDisplayName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - // return resultOp; } return resultOp; @@ -2255,8 +2614,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { byte[] decodedPayload = null; if (payload != null && payload.length != 0) { - - decodedPayload = Base64.decodeBase64(payload); + // the generated artifacts were already decoded by the handler + decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload); if (decodedPayload.length == 0) { log.debug("Failed to decode the payload."); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); @@ -2285,7 +2644,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { // else // if(ArtifactTypeEnum.APPC_CONFIG.getType().equalsIgnoreCase(artifactType) // || ){ - } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType().equalsIgnoreCase(artifactType)) { + } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType().equalsIgnoreCase(artifactType) + || ArtifactTypeEnum.VES_EVENTS.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS.getType().equalsIgnoreCase(artifactType)) { String artifactFileName = artifactInfo.getArtifactName(); String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase(); switch (fileExtension) { @@ -2321,17 +2681,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(decodedPayload); } - private Either validateDeploymentHeatPayload(byte[] payload, String artifactType) { + private Either validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) { // Basic YAML validation YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); - if (!yamlToObjectConverter.isValidYaml(payload)) { + if (!yamlToObjectConverter.isValidYaml(decodedPayload)) { log.debug("Invalid YAML format"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType); return Either.right(responseFormat); } if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) { // HEAT specific YAML validation - DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(payload, DeploymentArtifactHeatConfiguration.class); + DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class); if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null || heatConfiguration.getResources() == null) { log.debug("HEAT doesn't contain required \"heat_template_version\" and \"resources\" sections "); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType); @@ -2376,17 +2736,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { public void handleTransaction(Either opState) { if (opState == null || opState.isRight()) { - titanGenericDao.rollback(); + titanDao.rollback(); } else { - titanGenericDao.commit(); + titanDao.commit(); } } - public Either deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userId, String artifactId, ImmutablePair userResourceAuditPair, boolean shouldLock, + public Either deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userUserId, String artifactId, ImmutablePair userResourceAuditPair, boolean shouldLock, boolean inTransaction) { User user = new User(); - user.setUserId(userId); - Either parent = resourceOperation.getResource(resourceId); + user.setUserId(userUserId); + Either parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata); if (parent.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent.right().value())); return Either.right(responseFormat); @@ -2436,28 +2796,28 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return newArtifactName; } - public StorageOperationStatus deleteIfNotOnGraph(String artifactId, String artifactEsId, boolean deleteOnlyPayload) { - log.debug("deleteIfNotOnGraph: delete only payload = {}", deleteOnlyPayload); - Either checkArtifactNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class); - if ((artifactEsId != null && !artifactEsId.isEmpty())) { - boolean isNotExistOnGraph = checkArtifactNode.isRight() && checkArtifactNode.right().value().equals(TitanOperationStatus.NOT_FOUND); - - if ((isNotExistOnGraph) || (checkArtifactNode.left().value().getArtifactDataDefinition().getMandatory() && deleteOnlyPayload) - || (ArtifactGroupTypeEnum.SERVICE_API.equals(checkArtifactNode.left().value().getArtifactDataDefinition().getArtifactGroupType()) && deleteOnlyPayload)) { - // last one. need to delete in ES - log.debug("Entry on graph is deleted. Delete artifact in ES for id = {}", artifactEsId); - artifactCassandraDao.deleteArtifact(artifactEsId); - return StorageOperationStatus.OK; - // return - // componentsUtils.getResponseFormatByResourceId(ActionStatus.OK, - // resourceId); - - } else { - log.debug("Entry on graph is deleted. Exist more connections on this artifact. Don't delete artifact in ES for id = {}", artifactEsId); - return StorageOperationStatus.OK; - } - - } + public StorageOperationStatus deleteIfNotOnGraph(String artifactId, String artifactEsId, boolean deleteOnlyPayload) { + log.debug("deleteIfNotOnGraph: delete only payload = {}", deleteOnlyPayload); + // Either checkArtifactNode = titanDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class); + // if ((artifactEsId != null && !artifactEsId.isEmpty())) { + // boolean isNotExistOnGraph = checkArtifactNode.isRight() && checkArtifactNode.right().value().equals(TitanOperationStatus.NOT_FOUND); + // + // if ((isNotExistOnGraph) || (checkArtifactNode.left().value().getArtifactDataDefinition().getMandatory() && deleteOnlyPayload) + // || (ArtifactGroupTypeEnum.SERVICE_API.equals(checkArtifactNode.left().value().getArtifactDataDefinition().getArtifactGroupType()) && deleteOnlyPayload)) { + // // last one. need to delete in ES + // log.debug("Entry on graph is deleted. Delete artifact in ES for id = {}", artifactEsId); + // artifactCassandraDao.deleteArtifact(artifactEsId); + // return StorageOperationStatus.OK; + // // return + // // componentsUtils.getResponseFormatByResourceId(ActionStatus.OK, + // // resourceId); + // + // } else { + // log.debug("Entry on graph is deleted. Exist more connections on this artifact. Don't delete artifact in ES for id = {}", artifactEsId); + // return StorageOperationStatus.OK; + // } + // + // } return StorageOperationStatus.OK; } @@ -2594,7 +2954,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private Either validateServiceNameAndVersion(String serviceName, String serviceVersion) { - Either, StorageOperationStatus> serviceListBySystemName = serviceOperation.getServiceListBySystemName(serviceName, false); + Either, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName); if (serviceListBySystemName.isRight()) { log.debug("Couldn't fetch any service with name {}", serviceName); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName.right().value(), ComponentTypeEnum.SERVICE), serviceName)); @@ -2622,31 +2982,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } private Either validateResourceNameAndVersion(String resourceName, String resourceVersion) { - Either, StorageOperationStatus> resourceListBySystemName = resourceOperation.getResourceListBySystemName(resourceName, false); + + Either resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata); if (resourceListBySystemName.isRight()) { - log.debug("Couldn't fetch any resource with name {}", resourceName); + log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()), resourceName)); } - List resourceList = resourceListBySystemName.left().value(); - if (resourceList == null || resourceList.isEmpty()) { - log.debug("Couldn't fetch any resource with name {}", resourceName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceName)); - } - - Resource foundResource = null; - for (Resource resource : resourceList) { - if (resource.getVersion().equals(resourceVersion)) { - log.trace("Found resource with version {}", resourceVersion); - foundResource = resource; - break; - } - } - - if (foundResource == null) { - log.debug("Couldn't find version {} for resource {}", resourceVersion, resourceName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.RESOURCE.getValue(), resourceVersion)); - } - return Either.left(foundResource); + return Either.left(resourceListBySystemName.left().value()); } public Either downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) { @@ -2658,7 +3000,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } // Normalizing artifact name - artifactName = ValidationUtils.normalizeFileName(artifactName); + final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName); // Service validation Either validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); @@ -2668,41 +3010,44 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String serviceId = validateServiceNameAndVersion.left().value().getUniqueId(); - // Looking for deployment artifacts + // Looking for deployment or tosca artifacts Service service = validateServiceNameAndVersion.left().value(); - Map artifacts = service.getDeploymentArtifacts(); - if (artifacts == null || artifacts.isEmpty()) { - log.debug("Deployment artifacts of service {} are not found", serviceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); + + if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) { + log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName)); } - ArtifactDefinition deploymentArtifact = null; + Optional foundArtifactOptl = null; - for (ArtifactDefinition artifactDefinition : artifacts.values()) { - if (artifactDefinition.getArtifactName().equals(artifactName)) { - log.debug("Found deployment artifact {}", artifactName); - deploymentArtifact = artifactDefinition; - } + if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) { + foundArtifactOptl = service.getDeploymentArtifacts().values().stream() + // filters artifact by name + .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny(); } - - if (deploymentArtifact == null) { - log.debug("No deployment artifact {} was found for service {}", artifactName, serviceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); + if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) { + foundArtifactOptl = service.getToscaArtifacts().values().stream() + // filters TOSCA artifact by name + .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny(); } - + if (!foundArtifactOptl.isPresent()) { + log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName)); + } + log.debug("Found deployment artifact {}", normalizedArtifactName); // Downloading the artifact - Either, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact); + Either, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get()); if (downloadArtifactEither.isRight()) { - log.debug("Download artifact {} failed", artifactName); + log.debug("Download artifact {} failed", normalizedArtifactName); return Either.right(downloadArtifactEither.right().value()); } - log.trace("Download of service artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId()); + log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId()); return Either.left(downloadArtifactEither.left().value().getRight()); } - public Either, ResponseFormat> downloadArtifact(String artifactUniqueId) { + public Either, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) { log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId); - Either artifactById = artifactOperation.getArtifactById(artifactUniqueId, false); + Either artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId); if (artifactById.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value()); log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus.name()); @@ -2751,7 +3096,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { Map interfaces = ((Resource) component).getInterfaces(); if (!found && interfaces != null) { for (Map.Entry entry : interfaces.entrySet()) { - Map operations = entry.getValue().getOperations(); + Map operations = entry.getValue().getOperationsMap(); for (Map.Entry entryOp : operations.entrySet()) { if (entryOp.getValue().getImplementation() != null && entryOp.getValue().getImplementation().getUniqueId().equals(artifactId)) { found = true; @@ -2800,6 +3145,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } } + if ( !found ){ + artifacts = resourceInstance.getArtifacts(); + if (artifacts != null) { + for (Map.Entry entry : artifacts.entrySet()) { + if (entry.getValue().getUniqueId().equals(artifactId)) { + found = true; + break; + } + } + } + } } return found; } @@ -2807,24 +3163,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private Either validateComponentExists(String componentId, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType, String containerComponentType, boolean inTransaction) { - NodeTypeEnum nodeType = componentType.getNodeType(); - if (containerComponentType != null && NodeTypeEnum.ResourceInstance == nodeType) { - nodeType = (ComponentTypeEnum.findByParamName(containerComponentType)).getNodeType(); - } - ComponentOperation componentOperation = getComponentOperation(nodeType); + ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType); + componentForAudit.getNodeType(); - if (componentOperation == null) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - log.debug("addArtifact - not supported component type {}", componentType); - handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - Either componentResult = componentOperation.getComponent(componentId, inTransaction); + Either componentResult = toscaOperationFacade.getToscaFullElement(componentId); if (componentResult.isRight()) { - ActionStatus status = (componentType.equals(ComponentTypeEnum.RESOURCE)) ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND; - ComponentTypeEnum componentForAudit = (componentType.equals(ComponentTypeEnum.RESOURCE)) ? ComponentTypeEnum.RESOURCE : ComponentTypeEnum.SERVICE; - + ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND; ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId); log.debug("Service not found, serviceId {}", componentId); handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null); @@ -2833,9 +3178,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(componentResult.left().value()); } - private Either validateWorkOnComponent(org.openecomp.sdc.be.model.Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperation operation, + private Either validateWorkOnComponent(org.openecomp.sdc.be.model.Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation, ComponentTypeEnum componentType) { - if (operation != ArtifactOperation.Download) { + if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download && !operation.ignoreLifecycleState()) { Either canWork = validateCanWorkOnComponent(component, userId); if (canWork.isRight()) { String uniqueId = component.getUniqueId(); @@ -2847,22 +3192,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(true); } - private Either validateWorkOnResource(Resource resource, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperation operation) { - if (operation != ArtifactOperation.Download) { - if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { - String uniqueId = resource.getUniqueId(); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - log.debug("Resource status isn't CHECKOUT or user isn't owner, resourceId {}", uniqueId); - handleAuditing(auditingAction, resource, uniqueId, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE, null); - return Either.right(responseFormat); - } - } - return Either.left(true); - } - - private Either validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperation operation) { + private Either validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) { - if (operation != ArtifactOperation.Download) { + if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download) { String role = user.getRole(); if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); @@ -2874,12 +3206,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(true); } - private Either validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType) { - - return validateUserExists(userId, auditingAction, componentId, artifactId, componentType, false); - - } - private Either validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) { Either validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction); @@ -2892,9 +3218,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(validateUserExists.left().value()); } - private AuditingActionEnum detectAuditingType(ArtifactOperation operation, String origMd5) { + protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) { AuditingActionEnum auditingAction = null; - switch (operation) { + switch (operation.getArtifactOperationEnum()) { case Create: auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD; break; @@ -2945,7 +3271,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData); if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) { - log.debug("Artifact {} was saved in component {}.", artifactData.getId(), resourceId); + log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId); } else { log.info("Failed to save artifact {}.", artifactData.getId()); return false; @@ -2961,19 +3287,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return (ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType())); } - public IResourceOperation getResourceOperation() { - return this.resourceOperation; - } - - public Either createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map artifactInfoMap, String userId, ArtifactGroupTypeEnum groupType, boolean inTransaction) { - Either user = userAdminManager.getUser(userId, inTransaction); + public Either createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) { + Either user = userAdminManager.getUser(userUserId, inTransaction); if (user.isRight()) { ResponseFormat responseFormat; if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) { - log.debug("create artifact placeholder - not authorized user, userId {}", userId); + log.debug("create artifact placeholder - not authorized user, userId {}", userUserId); responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); } else { - log.debug("create artifact placeholder - failed to authorize user, userId {}", userId); + log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId); responseFormat = componentsUtils.getResponseFormat(user.right().value()); } return Either.right(responseFormat); @@ -2995,21 +3317,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { artifactInfo.setArtifactType(artifactType); artifactInfo.setDescription(artifactDescription); artifactInfo.setArtifactGroupType(groupType); - setDefaultArtifactTimeout(groupType, artifactInfo); + nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo); setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo); return artifactInfo; } - private void setDefaultArtifactTimeout(ArtifactGroupTypeEnum groupType, ArtifactDefinition artifactInfo) { - if (groupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) { - artifactInfo.setTimeout(defaultHeatTimeout); - } else { - artifactInfo.setTimeout(NON_HEAT_TIMEOUT); - } - } - private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) { String uniqueId = null; @@ -3032,29 +3346,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { artifactInfo.setMandatory(true); } - public Either, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType) { - return artifactOperation.getArtifacts(parentId, parentType, inTransaction, groupType.getType()); + public Either, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType, String instanceId) { + return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId); } - public Either addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String parentId, NodeTypeEnum parentType, boolean inTransaction) { - return artifactOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, parentId, parentType, inTransaction); - + public Either addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) { + return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId); } - private Either createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String parameters) { - StringBuilder sb = new StringBuilder(); - - sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader()); - sb.append(parameters); - sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter()); - byte[] payload = sb.toString().getBytes(); - - YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); + private Either createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) { - /* - * if (!yamlToObjectConverter.isValidYaml(payload)) { log.debug("Invalid YAML format"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, ArtifactTypeEnum.HEAT_ENV.getType()); return - * Either.right(responseFormat); } - */ + byte[] payload = payloadStr.getBytes(); ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload); return Either.left(artifactData); @@ -3065,60 +3367,81 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param artifactDefinition * @return */ - public Either generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, boolean shouldLock) { - List heatParameters = artifactDefinition.getHeatParameters(); + public Either generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, + boolean shouldLock, String instanceId) { + String payload = generateHeatEnvPayload(artifactDefinition); + return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId); + } + + private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) { + List heatParameters = artifactDefinition.getListHeatParameters(); heatParameters.sort(Comparator.comparing(e -> e.getName())); - StringBuilder sb = new StringBuilder("parameters:\n"); + StringBuilder sb = new StringBuilder(); + sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader()); + sb.append("parameters:\n"); if (heatParameters != null) { + List empltyHeatValues = new ArrayList<>(); for (HeatParameterDefinition heatParameterDefinition : heatParameters) { - if (heatParameterDefinition.getCurrentValue() != null) { - HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType()); - if (type != null) { - switch (type) { - case BOOLEAN: - sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatParameterDefinition.getCurrentValue())).append("\n"); - break; - case NUMBER: - // if - // (ValidationUtils.isFloatNumber(heatParameterDefinition.getCurrentValue())) - // { - // sb.append(" - // ").append(heatParameterDefinition.getName()).append(":").append(" - // ").append(Float.parseFloat(heatParameterDefinition.getCurrentValue())).append("\n"); - // } else { - // sb.append(" - // ").append(heatParameterDefinition.getName()).append(":").append(" - // ").append(Integer.parseInt(heatParameterDefinition.getCurrentValue())).append("\n"); - // } - sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatParameterDefinition.getCurrentValue()).toPlainString()).append("\n"); - break; - case COMMA_DELIMITED_LIST: - case JSON: - sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatParameterDefinition.getCurrentValue()).append("\n"); - break; - default: - String value = heatParameterDefinition.getCurrentValue(); - boolean starts = value.startsWith("\""); - boolean ends = value.endsWith("\""); + + String heatValue = heatParameterDefinition.getCurrentValue(); + if (!ValidationUtils.validateStringNotEmpty(heatValue)) { + heatValue = heatParameterDefinition.getDefaultValue(); + if (!ValidationUtils.validateStringNotEmpty(heatValue)) { + empltyHeatValues.add(heatParameterDefinition); + continue; + } + } + HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType()); + if (type != null) { + switch (type) { + case BOOLEAN: + sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatValue)).append("\n"); + break; + case NUMBER: + sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatValue).toPlainString()).append("\n"); + break; + case COMMA_DELIMITED_LIST: + case JSON: + sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n"); + break; + default: + String value = heatValue; + boolean starts = value.startsWith("\""); + boolean ends = value.endsWith("\""); + if (!(starts && ends)) { + starts = value.startsWith("'"); + ends = value.endsWith("'"); if (!(starts && ends)) { - starts = value.startsWith("'"); - ends = value.endsWith("'"); - if (!(starts && ends)) { - value = "\"" + value + "\""; - } + value = "\"" + value + "\""; } - sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value); - sb.append("\n"); - break; - } + sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value); + sb.append("\n"); + break; + } } } + if (!empltyHeatValues.isEmpty()) { + empltyHeatValues.sort(Comparator.comparing(e -> e.getName())); + empltyHeatValues.forEach(hv -> { + sb.append(" ").append(hv.getName()).append(":"); + HeatParameterType type = HeatParameterType.isValidType(hv.getType()); + if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) { + sb.append(" \"\"").append("\n"); + } else { + sb.append(" ").append("\n"); + } + }); + } } - return generateAndSaveHeatEnvArtifact(artifactDefinition, sb.toString(), component, resourceInstanceName, modifier, shouldLock); + sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter()); + // DE265919 fix Tal G + String result = sb.toString().replaceAll("\\\\n", "\n"); + + return result; } /** @@ -3127,14 +3450,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param payload * @return */ - public Either generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, - boolean shouldLock) { - return generateArtifactPayload(artifactDefinition, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(), () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload)); + public Either generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, + User modifier, boolean shouldLock, String instanceId) { + return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(), + () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId); } - protected Either generateArtifactPayload(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, boolean shouldLock, - Supplier payloadUpdateDateGen, Supplier> esDataCreator) { + protected Either generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, + boolean shouldLock, Supplier payloadUpdateDateGen, Supplier> esDataCreator, String instanceId) { if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() < payloadUpdateDateGen.get()) { @@ -3156,7 +3480,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String esArtifactId = artifactDefinition.getEsId(); Either artifactfromES; ESArtifactData esArtifactData; - if (esArtifactId != null && !esArtifactId.isEmpty()) { + if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) { artifactfromES = artifactCassandraDao.getArtifact(esArtifactId); if (artifactfromES.isRight()) { CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value(); @@ -3169,8 +3493,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { oldCheckSum = GeneralUtility.calculateMD5ByByteArray(esArtifactData.getDataAsArray()); } else { oldCheckSum = artifactDefinition.getArtifactChecksum(); + } - Either updateArifactDefinitionStatus; + Either updateArifactDefinitionStatus = null; if (shouldLock) { Either lockComponent = lockComponent(component, "Update Artifact - lock resource: "); @@ -3183,11 +3508,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) { artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get()); - updateArifactDefinitionStatus = artifactOperation.updateArifactDefinition(artifactDefinition, false); + updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId); log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId()); if (updateArifactDefinitionStatus.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName()); - log.trace("Failed to update payloadUpdateDate ", artifactDefinition.getEsId()); + log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId()); handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); @@ -3197,42 +3522,41 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { oldCheckSum = artifactDefinition.getArtifactChecksum(); artifactDefinition.setArtifactChecksum(newCheckSum); - artifactOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion()); + artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion()); artifactDefinition.setEsId(artifactDefinition.getUniqueId()); - updateArifactDefinitionStatus = artifactOperation.updateArifactDefinition(artifactDefinition, true); + updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId); log.trace("Update Payload ", artifactDefinition.getEsId()); + } + if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) { - if (updateArifactDefinitionStatus.isLeft()) { - - artifactData.setId(artifactDefinition.getUniqueId()); - CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData); - - if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) { - titanGenericDao.commit(); - log.debug("Artifact Saved In ES {}", artifactData.getId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, - ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); + artifactData.setId(artifactDefinition.getUniqueId()); + CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData); - } else { - titanGenericDao.rollback(); - log.info("Failed to save artifact {}.", artifactData.getId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, - ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); + if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) { + titanDao.commit(); + log.debug("Artifact Saved In ES {}", artifactData.getId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, + ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); - return Either.right(responseFormat); - } } else { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName()); - log.debug("Failed To update artifact {}", artifactData.getId()); + titanDao.rollback(); + log.info("Failed to save artifact {}.", artifactData.getId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); return Either.right(responseFormat); - } + } else { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName()); + log.debug("Failed To update artifact {}", artifactData.getId()); + handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, + ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); + + return Either.right(responseFormat); + } } finally { if (shouldLock) { @@ -3245,11 +3569,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } private Either, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, - org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperation operation, boolean shouldLock, boolean inTransaction) { - NodeTypeEnum parentType = convertParentType(componentType); + org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { + convertParentType(componentType); String parentId = parent.getUniqueId(); - Either artifactRes = artifactOperation.getArtifactById(artifactId, false); - ArtifactDefinition currArtifact = artifactRes.left().value(); + // Either artifactRes = this.artifactToscaOperation.getArtifactById(componentId, artifactId); + ArtifactDefinition currArtifact = artifactInfo; if (origMd5 != null) { Either validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); @@ -3298,11 +3622,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (resultOp == null || resultOp.isRight()) { log.debug("all changes rollback"); if (false == inTransaction) - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("all changes committed"); if (false == inTransaction) - titanGenericDao.commit(); + titanDao.commit(); } if (shouldLock) componentType = parent.getComponentType(); @@ -3336,9 +3660,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); return Either.right(responseFormat); } - List currentHeatEnvParams = currArtifact.getHeatParameters(); - List updatedHeatEnvParams = artifactInfo.getHeatParameters(); - List reducedHeatEnvParams = new ArrayList(); + List currentHeatEnvParams = currArtifact.getListHeatParameters(); + List updatedHeatEnvParams = artifactInfo.getListHeatParameters(); + new ArrayList(); // upload if (origMd5 != null) { @@ -3349,7 +3673,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); return Either.right(responseFormat); } - artifactInfo.setHeatParameters(updatedHeatEnvParams); + artifactInfo.setListHeatParameters(updatedHeatEnvParams); } Either validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType()); @@ -3368,61 +3692,133 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (paramName.equalsIgnoreCase(currHeatParam.getName())) { String updatedParamValue = heatEnvParam.getCurrentValue(); if (updatedParamValue != null && updatedParamValue.equals("")) { // reset - heatEnvParam.setCurrentValue(heatEnvParam.getDefaultValue()); - reducedHeatEnvParams.add(heatEnvParam); + currHeatParam.setCurrentValue(heatEnvParam.getDefaultValue()); } else if (updatedParamValue != null) { - reducedHeatEnvParams.add(heatEnvParam); + currHeatParam.setCurrentValue(updatedParamValue); } } } } - if (reducedHeatEnvParams.size() > 0) { - ArtifactDefinition reducedArtifactInfo = new ArtifactDefinition(artifactInfo); - reducedArtifactInfo.setHeatParameters(reducedHeatEnvParams); - Either updateArtifactResult = artifactOperation.updateArifactOnResource(reducedArtifactInfo, componentId, artifactInfo.getUniqueId(), componentType.getNodeType(), inTransaction); + currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis()); + currArtifact.setListHeatParameters(currentHeatEnvParams); - if (updateArtifactResult.isRight()) { - log.debug("Failed to update artifact on graph - {}", artifactId); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArtifactResult.right().value())); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); - return Either.right(responseFormat); - } - ArtifactDefinition updatedArtifact = updateArtifactResult.left().value(); - String updatedArtifactId = updatedArtifact.getUniqueId(); - if (!currArtifact.getUniqueId().equals(updatedArtifactId)) { - currArtifact.setUniqueId(updatedArtifactId); - currArtifact.setPayloadUpdateDate(updatedArtifact.getPayloadUpdateDate()); - currArtifact.setCreationDate(updatedArtifact.getCreationDate()); - currArtifact.setLastUpdateDate(updatedArtifact.getLastUpdateDate()); - currArtifact.setEsId(updatedArtifact.getEsId()); - } - currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis()); + Either updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId); + if (updateArifactRes.isRight()) { + log.debug("Failed to update artifact on graph - {}", artifactId); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value())); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); + return Either.right(responseFormat); + } + StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType); + if (error != StorageOperationStatus.OK) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error)); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); + return Either.right(responseFormat); + } - Either, StorageOperationStatus> heatParamsForEnv = ((org.openecomp.sdc.be.model.operations.impl.ArtifactOperation) artifactOperation).getHeatParamsForEnv(currArtifact); - if (heatParamsForEnv.isRight()) { - log.debug("failed to get heat parameters values for heat artifact {}", updatedArtifact.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatParamsForEnv.right().value())); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); - return Either.right(responseFormat); + error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left().value().getUniqueId(), parent.getUniqueId()); + if (error != StorageOperationStatus.OK) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error)); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); + return Either.right(responseFormat); + } + + } + // } + + insideEither = Either.left(currArtifact); + resultOp = Either.left(insideEither); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName()); + return resultOp; + } + + private Either, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent, + ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, String origMd5) { + + Either, ResponseFormat> resultOp = null; + Either insideEither = null; + /* + * currently getArtifactById does not retrieve heatParameters Either artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value(); + */ + String currentHeatId = currHeatArtifact.getUniqueId(); + ArtifactDefinition updatedHeatArt = currHeatArtifact; + + List updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters(); + List currentHeatEnvParams = currHeatArtifact.getListHeatParameters(); + List newHeatEnvParams = new ArrayList(); + + if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) { + + String paramName; + for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { + + paramName = heatEnvParam.getName(); + for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { + if (paramName.equalsIgnoreCase(currHeatParam.getName())) { + + String updatedParamValue = heatEnvParam.getCurrentValue(); + if (updatedParamValue == null) + updatedParamValue = heatEnvParam.getDefaultValue(); + HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType()); + if (!paramType.getValidator().isValid(updatedParamValue, null)) { + ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE; + ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, ""); + return Either.right(responseFormat); + + } + currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null)); + newHeatEnvParams.add(currHeatParam); + break; + } } - List updatedHeatParaetersList = heatParamsForEnv.left().value(); - currArtifact.setHeatParameters(updatedHeatParaetersList); - - Either updateArifactRes = artifactOperation.updateArifactDefinition(currArtifact, true); - if (updateArifactRes.isRight()) { - log.debug("Failed to update artifact on graph - {}", artifactId); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value())); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); + } + if (!newHeatEnvParams.isEmpty()) { + currHeatArtifact.setListHeatParameters(currentHeatEnvParams); + Either operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent.getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId); + + if (operationStatus.isRight()) { + log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId()); + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus.right().value())); return Either.right(responseFormat); + } + updatedHeatArt = operationStatus.left().value(); + insideEither = Either.left(updatedHeatArt); } } - insideEither = Either.left(currArtifact); + if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) { + artifactEnvInfo.setArtifactChecksum(null); + artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), componentId); + } else { + artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType()); + + } resultOp = Either.left(insideEither); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName()); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, ""); return resultOp; + + } + + private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) { + StorageOperationStatus error = StorageOperationStatus.OK; + log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId()); + List groupsInstances = ri.getGroupInstances(); + // List associatedGroups = null; + List groupInstancesId = null; + if (groupsInstances != null && !groupsInstances.isEmpty()) { + groupInstancesId = groupsInstances.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(artifactId)).map(p -> p.getUniqueId()).collect(Collectors.toList()); + } + if (groupInstancesId != null && !groupInstancesId.isEmpty()) { + // associatedGroups.stream().forEach(c -> this.groupInstanceOperation.updateCustomizationUUID(c.getUniqueId())); + toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId); + } + return error; + } public Either, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType, @@ -3484,25 +3880,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.right(responseFormat); } - public ComponentOperation getComponentOperation(NodeTypeEnum componentType) { - - switch (componentType) { - case Service: - case ResourceInstance: - return serviceOperation; - case Resource: - return resourceOperation; - default: - return null; - } - } - public ArtifactDefinition extractArtifactDefinition(Either eitherArtifact) { ArtifactDefinition ret; if (eitherArtifact.isLeft()) { ret = eitherArtifact.left().value(); } else { - ret = eitherArtifact.right().value().getImplementation(); + ret = eitherArtifact.right().value().getImplementationArtifact(); } return ret; } @@ -3549,7 +3932,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { byte[] downloadedArtifact = null; ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); if (errorWrapper.isEmpty()) { - auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstance.getName()); downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName()); } if (errorWrapper.isEmpty()) { @@ -3568,39 +3950,41 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param componentType * @param componentUuid * @param additionalParams + * @param operation * @return */ - public Either uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map additionalParams) { + public Either uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map additionalParams, + ArtifactOperationInfo operation) { Wrapper errorWrapper = new Wrapper<>(); Either, ResponseFormat> actionResult = null; Either uploadArtifactResult; - ArtifactDefinition uploadArtifact; + ArtifactDefinition uploadArtifact = null; Component component = null; String componentId = null; - ArtifactOperation operation = ArtifactOperation.Create; - operation.setExternalApi(true); ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); - Either getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); - } - if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid)); } if (errorWrapper.isEmpty()) { - if (component != null) { - componentId = component.getUniqueId(); - } else { - componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); + componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); + String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); + + if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); + if (component != null) { + componentId = component.getUniqueId(); + componentName = component.getName(); + } } + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName); } if (errorWrapper.isEmpty()) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, getComponentRes.left().value().getMetadataDataDefinition().getName()); actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null); if (actionResult.isRight()) { log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value()); @@ -3609,11 +3993,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } if (errorWrapper.isEmpty()) { uploadArtifact = actionResult.left().value().left().value(); - updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact); uploadArtifactResult = Either.left(uploadArtifact); } else { uploadArtifactResult = Either.right(errorWrapper.getInnerElement()); } + updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact); return uploadArtifactResult; } @@ -3626,14 +4010,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param componentUuid * @param resourceInstanceName * @param additionalParams + * @param operation * @return */ public Either uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, - Map additionalParams) { + Map additionalParams, ArtifactOperationInfo operation) { Wrapper errorWrapper = new Wrapper<>(); Either uploadArtifactResult; Either, ResponseFormat> actionResult = null; - ArtifactDefinition uploadArtifact; + ArtifactDefinition uploadArtifact = null; Component component = null; String componentInstanceId; String componentId; @@ -3641,11 +4026,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String userId = request.getHeader(Constants.USER_ID_HEADER); ImmutablePair componentRiPair = null; - Either getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName)); } if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper); @@ -3660,9 +4045,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (errorWrapper.isEmpty()) { componentInstanceId = componentRiPair.getRight().getUniqueId(); componentId = componentRiPair.getLeft().getUniqueId(); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); - ArtifactOperation operation = ArtifactOperation.Create; - operation.setExternalApi(true); ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType)); @@ -3673,11 +4055,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } if (errorWrapper.isEmpty()) { uploadArtifact = actionResult.left().value().left().value(); - updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact); uploadArtifactResult = Either.left(uploadArtifact); } else { uploadArtifactResult = Either.right(errorWrapper.getInnerElement()); } + updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact); return uploadArtifactResult; } @@ -3690,45 +4072,46 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param componentUuid * @param artifactUUID * @param additionalParams + * @param operation + * TODO * @return */ public Either updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, - Map additionalParams) { + Map additionalParams, ArtifactOperationInfo operation) { Wrapper errorWrapper = new Wrapper<>(); Either updateArtifactResult; Either, ResponseFormat> actionResult = null; - ArtifactDefinition updateArtifact; + ArtifactDefinition updateArtifact = null; Component component = null; String componentId = null; String artifactId = null; - ArtifactOperation operation = ArtifactOperation.Update; - operation.setExternalApi(true); ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); - Either getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); } - if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper); - } if (errorWrapper.isEmpty()) { - if (component != null) { - componentId = component.getUniqueId(); - } else { - componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); + componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); + String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); + + if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); + if (component != null) { + componentId = component.getUniqueId(); + componentName = component.getName(); + } } + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName); } if (errorWrapper.isEmpty()) { artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType); } if (errorWrapper.isEmpty()) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, getComponentRes.left().value().getMetadataDataDefinition().getName()); - actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null); if (actionResult.isRight()) { log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value()); @@ -3737,12 +4120,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } if (errorWrapper.isEmpty()) { updateArtifact = actionResult.left().value().left().value(); - updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact); updateArtifactResult = Either.left(updateArtifact); } else { updateArtifactResult = Either.right(errorWrapper.getInnerElement()); } + updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact); return updateArtifactResult; } @@ -3756,15 +4139,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param resourceInstanceName * @param artifactUUID * @param additionalParams + * @param operation + * TODO * @return */ public Either updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, - Map additionalParams) { + Map additionalParams, ArtifactOperationInfo operation) { Wrapper errorWrapper = new Wrapper<>(); Either updateArtifactResult; Either, ResponseFormat> actionResult = null; - ArtifactDefinition updateArtifact; + ArtifactDefinition updateArtifact = null; Component component = null; String componentInstanceId = null; String componentId = null; @@ -3773,7 +4158,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String userId = request.getHeader(Constants.USER_ID_HEADER); ImmutablePair componentRiPair = null; - Either getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); @@ -3792,12 +4177,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (errorWrapper.isEmpty()) { componentInstanceId = componentRiPair.getRight().getUniqueId(); componentId = componentRiPair.getLeft().getUniqueId(); - artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentInstanceId, ComponentTypeEnum.RESOURCE_INSTANCE); + artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper); } if (errorWrapper.isEmpty()) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); - ArtifactOperation operation = ArtifactOperation.Update; - operation.setExternalApi(true); ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType)); @@ -3808,13 +4190,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } if (errorWrapper.isEmpty()) { updateArtifact = actionResult.left().value().left().value(); - updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact); updateArtifactResult = Either.left(updateArtifact); } else { updateArtifactResult = Either.right(errorWrapper.getInnerElement()); } + updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact); return updateArtifactResult; - } /** @@ -3825,44 +4206,45 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param componentUuid * @param artifactUUID * @param additionalParams + * @param operation + * TODO * @return */ - public Either deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map additionalParams) { + public Either deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map additionalParams, + ArtifactOperationInfo operation) { Wrapper errorWrapper = new Wrapper<>(); Either deleteArtifactResult; Either, ResponseFormat> actionResult = null; - ArtifactDefinition deleteArtifact; + ArtifactDefinition deleteArtifact = null; Component component = null; String componentId = null; String artifactId = null; - ArtifactOperation operation = ArtifactOperation.Delete; - operation.setExternalApi(true); String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); - Either getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); - } - if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid)); } if (errorWrapper.isEmpty()) { - if (component != null) { - componentId = component.getUniqueId(); - } else { - componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); + componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); + String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); + if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); + if (component != null) { + componentId = component.getUniqueId(); + componentName = component.getName(); + } } + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName); } if (errorWrapper.isEmpty()) { artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType); } if (errorWrapper.isEmpty()) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, getComponentRes.left().value().getMetadataDataDefinition().getName()); - actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null); if (actionResult.isRight()) { log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value()); @@ -3871,16 +4253,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } if (errorWrapper.isEmpty()) { deleteArtifact = actionResult.left().value().left().value(); - updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact); deleteArtifactResult = Either.left(deleteArtifact); } else { deleteArtifactResult = Either.right(errorWrapper.getInnerElement()); } + updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact); return deleteArtifactResult; } /** - * deletes an artifact an a resource instance by UUID + * deletes an artifact from a resource instance by UUID * * @param request * @param componentType @@ -3888,15 +4270,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param resourceInstanceName * @param artifactUUID * @param additionalParams + * @param operation + * TODO * @return */ public Either deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, - Map additionalParams) { + Map additionalParams, ArtifactOperationInfo operation) { Wrapper errorWrapper = new Wrapper<>(); Either deleteArtifactResult; Either, ResponseFormat> actionResult = null; - ArtifactDefinition deleteArtifact; + ArtifactDefinition deleteArtifact = null; Component component = null; String componentInstanceId = null; String componentId = null; @@ -3904,7 +4288,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); ImmutablePair componentRiPair = null; - Either getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); @@ -3923,14 +4307,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (errorWrapper.isEmpty()) { componentInstanceId = componentRiPair.getRight().getUniqueId(); componentId = componentRiPair.getLeft().getUniqueId(); - artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentInstanceId, ComponentTypeEnum.RESOURCE_INSTANCE); + artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper); } if (errorWrapper.isEmpty()) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); - ArtifactOperation operation = ArtifactOperation.Delete; - operation.setExternalApi(true); - actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType)); if (actionResult.isRight()) { @@ -3940,50 +4320,204 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } if (errorWrapper.isEmpty()) { deleteArtifact = actionResult.left().value().left().value(); - updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact); deleteArtifactResult = Either.left(deleteArtifact); } else { deleteArtifactResult = Either.right(errorWrapper.getInnerElement()); } + updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact); return deleteArtifactResult; } + private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper errorWrapper) { + String artifactId = null; + ArtifactDefinition foundArtifact = null; + if (instance.getDeploymentArtifacts() != null) { + foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null); + } + if (foundArtifact == null && instance.getArtifacts() != null) { + foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null); + } + if (foundArtifact == null) { + log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId()); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID)); + } else { + artifactId = foundArtifact.getUniqueId(); + } + return artifactId; + } + + public Either createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component, + Map existingEnvVersions) { + return createHeatEnvPlaceHolder(artifact, envType, parentId, parentType, parentName, user, component, existingEnvVersions, true); + + } + + @SuppressWarnings("unchecked") + public Either createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component, + Map existingEnvVersions, boolean overrideId) { + Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); + if (deploymentResourceArtifacts == null) { + log.debug("no deployment artifacts are configured for generated artifacts"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + Map placeHolderData = (Map) deploymentResourceArtifacts.get(envType); + if (placeHolderData == null) { + log.debug("no env type {} are configured for generated artifacts", envType); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + String envLabel = (artifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase(); + String parentIdParam = parentId; + if (!overrideId) { + parentIdParam = null; + } + Either createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentIdParam, envLabel, placeHolderData, user.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true); + if (createArtifactPlaceHolder.isRight()) { + return Either.right(createArtifactPlaceHolder.right().value()); + } + ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value(); + if (!overrideId) { + // fix for migration only!!!! create heat env placeholder according to heat id. + artifactHeatEnv.setUniqueId(artifact.getUniqueId() + HEAT_ENV_SUFFIX); + } + + artifactHeatEnv.setGeneratedFromId(artifact.getUniqueId()); + artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis()); + artifactHeatEnv.setTimeout(0); + buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData); + // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow + handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions); + // clone heat parameters in case of heat env only not VF heat env + if (envType.equals(HEAT_ENV_NAME)) { + artifactHeatEnv.setHeatParameters(artifact.getHeatParameters()); + } + ArtifactDefinition artifactDefinition; + // Evg : for resource instance artifact will be added later as block with other env artifacts from BL + if (parentType != NodeTypeEnum.ResourceInstance) { + Either addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, artifact, component.getUniqueId(), parentType, parentId); + if (addHeatEnvArtifact.isRight()) { + log.debug("failed to create heat env artifact on resource instance"); + return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null)); + } + artifactDefinition = createArtifactPlaceHolder.left().value(); + } else { + artifactDefinition = artifactHeatEnv; + artifactToscaOperation.generateUUID(artifactDefinition, artifactDefinition.getArtifactVersion()); + } + + if (artifact.getHeatParameters() != null) { + List heatEnvParameters = new ArrayList(); + for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) { + HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter); + heatEnvParameter.setDefaultValue(parameter.getCurrentValue()); + heatEnvParameters.add(heatEnvParameter); + } + artifactDefinition.setListHeatParameters(heatEnvParameters); + } + + // audit + EnumMap artifactAuditingFields = createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.getUniqueId()); + artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parentName); + ComponentTypeEnum componentType = component.getComponentType(); + if (parentType == NodeTypeEnum.ResourceInstance) { + componentType = ComponentTypeEnum.RESOURCE_INSTANCE; + } + componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, componentType, artifactAuditingFields); + return Either.left(artifactDefinition); + } + + private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map placeHolderData) { + String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName()); + String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION); + String name = heatArtifact.getArtifactName(); + String fileName; + if (name == null) { + name = heatArtifact.getArtifactLabel(); + fileName = name + "." + envExtension; + } else { + fileName = name.replaceAll("." + heatExtension, "." + envExtension); + } + heatEnvArtifact.setArtifactName(fileName); + } + + private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map existingEnvVersions) { + if (null != existingEnvVersions) { + String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName()); + if (null != prevVersion) { + heatEnvArtifact.setArtifactVersion(prevVersion); + } + } + } + + /** + * Handles Artifacts Request For Inner Component + * + * @param artifactsToHandle + * @param component + * @param user + * @param vfcsNewCreatedArtifacts + * @param operation + * @param shouldLock + * @param inTransaction + * @return + */ + public Either, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List artifactsToHandle, Resource component, User user, List vfcsNewCreatedArtifacts, + ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { + + Either, ResponseFormat> handleArtifactsResult = null; + ComponentTypeEnum componentType = component.getComponentType(); + List uploadedArtifacts = new ArrayList<>(); + Wrapper errorWrapper = new Wrapper<>(); + Either, ResponseFormat> actionResult; + String originData; + String origMd5; + try { + for (ArtifactDefinition artifact : artifactsToHandle) { + originData = buildJsonStringForCsarVfcArtifact(artifact); + origMd5 = GeneralUtility.calculateMD5ByString(originData); + actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction); + if (actionResult.isRight()) { + log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component.getName(), actionResult.right().value()); + errorWrapper.setInnerElement(actionResult.right().value()); + if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) { + vfcsNewCreatedArtifacts.addAll(uploadedArtifacts); + } + break; + } + uploadedArtifacts.add(actionResult.left().value().left().value()); + } + if (errorWrapper.isEmpty()) { + handleArtifactsResult = Either.left(uploadedArtifacts); + } else { + handleArtifactsResult = Either.right(errorWrapper.getInnerElement()); + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleArtifactsResult = Either.right(responseFormat); + log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e); + } + return handleArtifactsResult; + } + private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper errorWrapper) { ComponentInstance componentInstance = null; - StorageOperationStatus status; - Either getResourceInstanceRes = null; + String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName); Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper); if (errorWrapper.isEmpty()) { - componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findAny().get(); + componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null); if (componentInstance == null) { errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName())); log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName()); } } - if (errorWrapper.isEmpty()) { - getResourceInstanceRes = resourceInstanceOperation.getResourceInstanceById(componentInstance.getUniqueId()); - if (getResourceInstanceRes.isRight()) { - status = getResourceInstanceRes.right().value(); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); - } - } - if (errorWrapper.isEmpty()) { - componentInstance = getResourceInstanceRes.left().value(); - getResourceInstanceRes = resourceInstanceOperation.getFullComponentInstance(componentInstance, componentType.getNodeType()); - if (getResourceInstanceRes.isRight()) { - status = getResourceInstanceRes.right().value(); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); - } else { - componentInstance = getResourceInstanceRes.left().value(); - } - } return componentInstance; } private ImmutablePair getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper errorWrapper) { ImmutablePair relatedComponentComponentInstancePair = null; - ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findAny().get(); + String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName); + ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null); if (componentInstance == null) { errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName())); log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName()); @@ -3998,7 +4532,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { ImmutablePair relatedComponentComponentInstancePair = null; Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper); if (errorWrapper.isEmpty()) { - componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findAny().get(); + componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findFirst().orElse(null); if (componentInstance == null) { errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName())); log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName()); @@ -4039,7 +4573,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper errorWrapper) { Component component = null; - Either getComponentRes = getComponentOperation(componentType).getLatestComponentByUuid(componentType.getNodeType(), componentUuid); + Either getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); @@ -4056,13 +4590,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { StorageOperationStatus storageStatus; ArtifactDefinition latestArtifact = null; List artifacts = null; - NodeTypeEnum parentType; - if (componentType.equals(ComponentTypeEnum.RESOURCE)) { - parentType = NodeTypeEnum.Resource; - } else { - parentType = NodeTypeEnum.Service; - } - Either, StorageOperationStatus> getArtifactsRes = artifactOperation.getArtifacts(parentId, parentType, false); + Either, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId); if (getArtifactsRes.isRight()) { storageStatus = getArtifactsRes.right().value(); log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType.name(), parentId, storageStatus); @@ -4120,8 +4648,29 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } private void updateAuditParametersWithArtifactDefinition(Map additionalParams, ArtifactDefinition artifact) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact)); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName()); + if (artifact == null) { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, ""); + if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, ""); + } + } else { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact)); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName()); + } + } + + private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) { + Map json = new HashMap<>(); + String artifactName = artifact.getArtifactName(); + json.put(Constants.ARTIFACT_NAME, artifactName); + json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel()); + json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType()); + json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType()); + json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription()); + json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData()); + json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName()); + return gson.toJson(json); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java index 15fe86da33..84cf20dcfa 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java @@ -34,7 +34,7 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; -import org.openecomp.sdc.be.resources.data.AttributeData; + import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -78,10 +78,10 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } - try { + try { // Get the resource from DB - Either status = getResource(resourceId); + Either status = toscaOperationFacade.getToscaElement(resourceId); if (status.isRight()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); } @@ -111,17 +111,16 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { // add the new attribute to resource on graph // need to get StorageOpaerationStatus and convert to ActionStatus from // componentsUtils - Either either = attributeOperation.addAttribute(newAttributeDef, resourceId); + Either either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef); if (either.isRight()) { result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); return result; } - - result = Either.left(attributeOperation.convertAttributeDataToAttributeDefinition(either.left().value(), newAttributeDef.getName(), resourceId)); + result = Either.left(either.left().value()); + return result; } finally { commitOrRollback(result); - // unlock component graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); } @@ -150,7 +149,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } // Get the resource from DB - Either status = getResource(resourceId); + Either status = toscaOperationFacade.getToscaElement(resourceId); if (status.isRight()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); } @@ -185,16 +184,16 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { */ public Either updateAttribute(String resourceId, String attributeId, AttributeDefinition newAttDef, String userId) { Either result = null; - + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); if (lockResult != StorageOperationStatus.OK) { BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } - try { // Get the resource from DB - Either eitherResource = getResource(resourceId); + Either eitherResource = toscaOperationFacade.getToscaElement(resourceId); if (eitherResource.isRight()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); } @@ -204,7 +203,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } - + // verify attribute exist in resource Either eitherAttribute = getAttribute(resourceId, attributeId, userId); if (eitherAttribute.isRight()) { @@ -221,7 +220,15 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { return Either.right(defaultValuesValidation.right().value()); } // add the new property to resource on graph - Either eitherAttUpdate = attributeOperation.updateAttribute(attributeId, newAttDef, eitherAllDataTypes.left().value()); + + StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(newAttDef, eitherAllDataTypes.left().value()); + if (validateAndUpdateAttribute != StorageOperationStatus.OK) { + log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, validateAndUpdateAttribute); + result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(validateAndUpdateAttribute), resource.getName())); + } + + + Either eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef); if (eitherAttUpdate.isRight()) { log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, eitherAttUpdate.right().value()); @@ -229,12 +236,13 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { return result; } - result = Either.left(attributeOperation.convertAttributeDataToAttributeDefinition(eitherAttUpdate.left().value(), newAttDef.getName(), resourceId)); + result = Either.left(eitherAttUpdate.left().value()); return result; } finally { commitOrRollback(result); graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); } + } /** @@ -246,7 +254,9 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @return */ public Either deleteAttribute(String resourceId, String attributeId, String userId) { + Either result = null; + Either resp = validateUserExists(userId, "delete Attribute", false); if (resp.isRight()) { return Either.right(resp.right().value()); @@ -255,13 +265,13 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); if (lockResult != StorageOperationStatus.OK) { BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return result; + log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } try { // Get the resource from DB - Either eitherResource = getResource(resourceId); + Either eitherResource = toscaOperationFacade.getToscaElement(resourceId); if (eitherResource.isRight()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); } @@ -280,12 +290,13 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { String attributeName = eitherAttributeExist.left().value().getName(); // delete attribute of resource from graph - Either eitherAttributeDelete = attributeOperation.deleteAttribute(attributeId); - if (eitherAttributeDelete.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete.right().value()), resource.getName())); + StorageOperationStatus eitherAttributeDelete = toscaOperationFacade.deleteAttributeOfResource(resource, attributeName); + if (eitherAttributeDelete != StorageOperationStatus.OK) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete), resource.getName())); return result; } - result = Either.left(attributeOperation.convertAttributeDataToAttributeDefinition(eitherAttributeDelete.left().value(), attributeName, resourceId)); + + result = Either.left(eitherAttributeExist.left().value()); return result; } finally { commitOrRollback(result); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java index 93ddff38d5..df8460ca96 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java @@ -20,57 +20,67 @@ package org.openecomp.sdc.be.components.impl; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; +import java.util.function.Function; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyRule; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.GroupProperty; import org.openecomp.sdc.be.model.IComplexDefaultValue; import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; -import org.openecomp.sdc.be.model.operations.api.IArtifactOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IAttributeOperation; -import org.openecomp.sdc.be.model.operations.api.IComponentOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; +import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; import org.openecomp.sdc.be.model.operations.api.IGroupOperation; import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation; import org.openecomp.sdc.be.model.operations.api.IPropertyOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.ComponentOperation; -import org.openecomp.sdc.be.model.operations.impl.ProductOperation; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; -import org.openecomp.sdc.be.model.operations.impl.ServiceOperation; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter; +import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator; +import org.openecomp.sdc.be.resources.data.PropertyValueData; import org.openecomp.sdc.be.user.IUserBusinessLogic; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import com.google.gson.JsonElement; + import fj.data.Either; public abstract class BaseBusinessLogic { @@ -81,18 +91,12 @@ public abstract class BaseBusinessLogic { @Autowired protected IUserBusinessLogic userAdmin; - @Autowired - protected ResourceOperation resourceOperation; - @Autowired protected IGraphLockOperation graphLockOperation; @Autowired - protected ServiceOperation serviceOperation; - - @Autowired - protected ProductOperation productOperation; - + protected TitanDao titanDao; + @Autowired protected TitanGenericDao titanGenericDao; @@ -101,22 +105,32 @@ public abstract class BaseBusinessLogic { @Autowired protected IGroupOperation groupOperation; + + @Autowired + protected IGroupInstanceOperation groupInstanceOperation; @Autowired protected IGroupTypeOperation groupTypeOperation; - @Autowired - protected IArtifactOperation artifactOperation; + /*@Autowired + protected IArtifactOperation artifactOperation;*/ + @javax.annotation.Resource + protected ArtifactsOperations artifactToscaOperation; - @Autowired - protected IAttributeOperation attributeOperation; +// @Autowired +// protected IAttributeOperation attributeOperation; @Autowired - protected IPropertyOperation propertyOperation; + protected PropertyOperation propertyOperation; @Autowired protected ApplicationDataTypeCache applicationDataTypeCache; + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + protected DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); + public void setUserAdmin(UserBusinessLogic userAdmin) { this.userAdmin = userAdmin; } @@ -129,15 +143,20 @@ public abstract class BaseBusinessLogic { this.graphLockOperation = graphLockOperation; } + public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { + this.toscaOperationFacade = toscaOperationFacade; + } + + private static Logger log = LoggerFactory.getLogger(BaseBusinessLogic.class.getName()); + + public static final String EMPTY_VALUE = null; protected Either validateUserNotEmpty(User user, String ecompErrorContext) { String userId = user.getUserId(); if (StringUtils.isEmpty(userId)) { - // user.setUserId("UNKNOWN"); log.debug("User header is missing "); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUserMissingError, ecompErrorContext, user.getUserId()); BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, user.getUserId()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); return Either.right(responseFormat); @@ -166,7 +185,7 @@ public abstract class BaseBusinessLogic { log.debug("validateUserExists - failed to authorize user, userId {}", userId); } log.debug("User is not listed. userId {}", userId); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUserMissingError, ecompErrorContext, userId); + BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId); return Either.right(eitherCreator.right().value()); } return Either.left(eitherCreator.left().value()); @@ -187,7 +206,6 @@ public abstract class BaseBusinessLogic { } if (log.isDebugEnabled()) log.debug("User is not listed. userId {}", userId); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUserMissingError, ecompErrorContext, userId); BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId); return Either.right(responseFormat); } @@ -223,7 +241,7 @@ public abstract class BaseBusinessLogic { BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), componentId); ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType); ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName()); - log.debug("Failed to lock component {} error - {}", componentId, actionStatus); + log.debug("Failed to lock component {} error - {}" ,componentId, actionStatus); return Either.right(responseFormat); } } @@ -233,9 +251,9 @@ public abstract class BaseBusinessLogic { NodeTypeEnum nodeType = componentType.getNodeType(); if (false == inTransaction) { if (either == null || either.isRight()) { - titanGenericDao.rollback(); + titanDao.rollback(); } else { - titanGenericDao.commit(); + titanDao.commit(); } } // unlock resource @@ -265,17 +283,12 @@ public abstract class BaseBusinessLogic { } } - protected Either validateComponentExists(String componentId, ComponentTypeEnum componentType, boolean inTransaction, boolean createNewTransaction) { - ComponentOperation componentOperation = getComponentOperation(componentType); - Either componentFound = null; - // if(createNewTransaction){ - // componentFound = componentOperation.getComponent_tx(componentId, - // inTransaction); - // } - // else{ - componentFound = componentOperation.getComponent(componentId, inTransaction); - // } - + protected Either validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView filter) { + + if(filter == null){ + filter = new ComponentParametersView(); + } + Either componentFound = toscaOperationFacade.getToscaElement(componentId, filter); if (componentFound.isRight()) { StorageOperationStatus storageOperationStatus = componentFound.right().value(); ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, componentType); @@ -286,35 +299,33 @@ public abstract class BaseBusinessLogic { return Either.left(componentFound.left().value()); } - protected Either validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView, String userId, - AuditingActionEnum auditingAction, User user) { - - ComponentOperation componentOperation = getComponentOperation(componentType); - - if (componentOperation == null) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - log.debug("addGroup - not supported component type {}", componentType); - // handleAuditing(auditingAction, null, componentId, user, null, - // null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - Either componentResult = componentOperation.getComponent(componentId, componentParametersView, true); - - if (componentResult.isRight()) { - ActionStatus status = (componentType.equals(ComponentTypeEnum.RESOURCE)) ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND; - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId); - - log.debug("Service not found, serviceId {}", componentId); - // ComponentTypeEnum componentForAudit = - // (componentType.equals(ComponentTypeEnum.RESOURCE)) ? - // ComponentTypeEnum.RESOURCE : ComponentTypeEnum.SERVICE; - // handleAuditing(auditingAction, null, componentId, user, null, - // null, artifactId, responseFormat, componentForAudit, null); - return Either.right(responseFormat); - } - return Either.left(componentResult.left().value()); - } +// protected Either validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView, String userId, +// AuditingActionEnum auditingAction, User user) { +// +// ComponentOperation componentOperation = getComponentOperation(componentType); +// +// if (componentOperation == null) { +// ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); +// log.debug("addGroup - not supported component type {}", componentType); +// return Either.right(responseFormat); +// } +// Either componentResult = componentOperation.getComponent(componentId, componentParametersView, true); +// +// if (componentResult.isRight()) { +// ActionStatus status = (componentType.equals(ComponentTypeEnum.RESOURCE)) ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND; +// +// ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId); +// +// log.debug("Service not found, serviceId {}", componentId); +// // ComponentTypeEnum componentForAudit = +// // (componentType.equals(ComponentTypeEnum.RESOURCE)) ? +// // ComponentTypeEnum.RESOURCE : ComponentTypeEnum.SERVICE; +// // handleAuditing(auditingAction, null, componentId, user, null, +// // null, artifactId, responseFormat, componentForAudit, null); +// return Either.right(responseFormat); +// } +// return Either.left(componentResult.left().value()); +// } public Either validateCanWorkOnComponent(Component component, String userId) { Either canWork = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); @@ -323,7 +334,7 @@ public abstract class BaseBusinessLogic { return canWork; } - // verify user id is not null + // verify userId is not null if (userId == null) { log.debug("Current user userId is null"); return canWork; @@ -345,47 +356,6 @@ public abstract class BaseBusinessLogic { return Either.left(true); } - public ComponentOperation getComponentOperation(ComponentTypeEnum componentTypeEnum) { - if (ComponentTypeEnum.SERVICE == componentTypeEnum) { - return serviceOperation; - } else if (ComponentTypeEnum.RESOURCE == componentTypeEnum) { - return resourceOperation; - } else if (ComponentTypeEnum.PRODUCT == componentTypeEnum) { - return productOperation; - } - return null; - } - - public IComponentOperation getIComponentOperation(ComponentTypeEnum componentTypeEnum) { - - switch (componentTypeEnum) { - case SERVICE: - return serviceOperation; - case RESOURCE: - return resourceOperation; - case PRODUCT: - return productOperation; - default: - break; - } - - return null; - } - - public ComponentOperation getComponentOperationByParentComponentType(ComponentTypeEnum parentComponentType) { - switch (parentComponentType) { - case SERVICE: - return resourceOperation; - case RESOURCE: - return resourceOperation; - case PRODUCT: - return serviceOperation; - default: - break; - } - return null; - } - public ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) { switch (parentComponentType) { case SERVICE: @@ -401,8 +371,8 @@ public abstract class BaseBusinessLogic { } // For UT - public void setTitanGenericDao(TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; + public void setTitanGenericDao(TitanDao titanDao) { + this.titanDao = titanDao; } protected Either, ResponseFormat> getAllDataTypes(ApplicationDataTypeCache applicationDataTypeCache) { @@ -453,23 +423,23 @@ public abstract class BaseBusinessLogic { return Either.left(true); } - protected Either getResource(final String resourceId) { - - log.debug("Get resource with id {}", resourceId); - Either status = resourceOperation.getResource(resourceId); - if (status.isRight()) { - log.debug("Resource with id {} was not found", resourceId); - return Either.right(status.right().value()); - } - - Resource resource = status.left().value(); - if (resource == null) { - BeEcompErrorManager.getInstance().logBeComponentMissingError("Property Business Logic", ComponentTypeEnum.RESOURCE.getValue(), resourceId); - log.debug("General Error while get resource with id {}", resourceId); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - return Either.left(resource); - } +// protected Either getResource(final String resourceId) { +// +// log.debug("Get resource with id {}", resourceId); +// Either status = resourceOperation.getResource(resourceId); +// if (status.isRight()) { +// log.debug("Resource with id {} was not found", resourceId); +// return Either.right(status.right().value()); +// } +// +// Resource resource = status.left().value(); +// if (resource == null) { +// BeEcompErrorManager.getInstance().logBeComponentMissingError("Property Business Logic", ComponentTypeEnum.RESOURCE.getValue(), resourceId); +// log.debug("General Error while get resource with id {}", resourceId); +// return Either.right(StorageOperationStatus.GENERAL_ERROR); +// } +// return Either.left(resource); +// } protected void handleDefaultValue(IComplexDefaultValue newAttributeDef, Map dataTypes) { // convert property @@ -503,8 +473,7 @@ public abstract class BaseBusinessLogic { } protected void validateCanWorkOnComponent(String componentId, ComponentTypeEnum componentTypeEnum, String userId, Wrapper errorWrapper) { - IComponentOperation componentOperation = getIComponentOperation(componentTypeEnum); - if (!ComponentValidationUtils.canWorkOnComponent(componentId, componentOperation, userId)) { + if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) { log.info("Restricted operation for user {} on {} {}", userId, componentTypeEnum.getValue(), componentId); errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } @@ -531,10 +500,10 @@ public abstract class BaseBusinessLogic { protected void commitOrRollback(Either result) { if (result == null || result.isRight()) { log.warn("operation failed. do rollback"); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("operation success. do commit"); - titanGenericDao.commit(); + titanDao.commit(); } } @@ -555,9 +524,9 @@ public abstract class BaseBusinessLogic { } protected Either validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView, boolean inTransaction) { - ComponentOperation componentOperation = getComponentOperation(componentType); + Either componentFound = null; - componentFound = componentOperation.getComponent(componentId, componentParametersView, inTransaction); + componentFound = toscaOperationFacade.getToscaElement(componentId, componentParametersView); if (componentFound.isRight()) { StorageOperationStatus storageOperationStatus = componentFound.right().value(); @@ -568,4 +537,267 @@ public abstract class BaseBusinessLogic { } return Either.left(componentFound.left().value()); } + + protected Either validateFreeText(GroupProperty groupPropertyToUpdate) { + + Either ret; + final String groupTypeValue = groupPropertyToUpdate.getValue(); + if (!StringUtils.isEmpty(groupTypeValue)) { + if (!ValidationUtils.validateDescriptionLength(groupTypeValue)) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, + NodeTypeEnum.Property.getName(), + String.valueOf(ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH))); + } + + else if (!ValidationUtils.validateIsEnglish(groupTypeValue)) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_DESCRIPTION, + NodeTypeEnum.Property.getName())); + } else { + ret = Either.left(groupPropertyToUpdate); + } + + } else { + ret = Either.left(groupPropertyToUpdate); + } + return ret; + } + + @SuppressWarnings("unchecked") + protected > boolean enumHasValueFilter(String name, Function enumGetter, T... enumValues) { + T enumFound = enumGetter.apply(name); + return Arrays.asList(enumValues).contains(enumFound); + } + + protected Either validatePropValueBeforeCreate(ComponentInstanceProperty property, String value, boolean isValidate, String innerType, Map allDataTypes) { + String propertyType = property.getType(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = property.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + innerType = propDef.getType(); + } + + Either isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes); + + String newValue = value; + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (res == false) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + + ImmutablePair pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate); + log.debug("After validateAndUpdateRules. pair = {}", pair); + if (pair.getRight() != null && pair.getRight() == false) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + + return Either.left(newValue); + } + + protected Either validateInputValueBeforeCreate(ComponentInstanceInput property, String value, boolean isValidate, String innerType, Map allDataTypes) { + String propertyType = property.getType(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = property.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + innerType = propDef.getType(); + } + + Either isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes); + + String newValue = value; + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (res == false) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + + ImmutablePair pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate); + log.debug("After validateAndUpdateRules. pair = {}", pair); + if (pair.getRight() != null && pair.getRight() == false) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + + return Either.left(newValue); + } + + public Either validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType, Map dataTypes) { + log.trace("Going to validate property value and its type. type = {}, value = {}", propertyType, value); + ToscaPropertyType type = getType(propertyType); + + if (isValidate) { + + if (type == null) { + DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); + ImmutablePair validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes); + if (validateResult.right.booleanValue() == false) { + log.debug("The value {} of property from type {} is invalid", value, propertyType); + return Either.right(false); + } + JsonElement jsonElement = validateResult.left; + String valueFromJsonElement = getValueFromJsonElement(jsonElement); + return Either.left(valueFromJsonElement); + } + log.trace("before validating property type {}", propertyType); + boolean isValidProperty = isValidValue(type, value, innerType, dataTypes); + if (false == isValidProperty) { + log.debug("The value {} of property from type {} is invalid", value, type); + return Either.right(false); + } + } + Object convertedValue = value; + if (false == isEmptyValue(value) && isValidate) { + PropertyValueConverter converter = type.getConverter(); + convertedValue = converter.convert(value, innerType, dataTypes); + } + return Either.left(convertedValue); + } + + public ImmutablePair validateAndUpdateRules(String propertyType, List rules, String innerType, Map dataTypes, boolean isValidate) { + + if (rules == null || rules.isEmpty() == true) { + return new ImmutablePair(null, true); + } + + for (PropertyRule rule : rules) { + String value = rule.getValue(); + Either updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes); + if (updateResult.isRight()) { + Boolean status = updateResult.right().value(); + if (status == false) { + return new ImmutablePair(value, status); + } + } else { + String newValue = null; + Object object = updateResult.left().value(); + if (object != null) { + newValue = object.toString(); + } + rule.setValue(newValue); + } + } + + return new ImmutablePair(null, true); + } + + protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map dataTypes) { + if (isEmptyValue(value)) { + return true; + } + + PropertyTypeValidator validator = type.getValidator(); + + boolean isValid = validator.isValid(value, innerType, dataTypes); + if (true == isValid) { + return true; + } else { + return false; + } + + } + + public boolean isEmptyValue(String value) { + if (value == null) { + return true; + } + return false; + } + + public boolean isNullParam(String value) { + if (value == null) { + return true; + } + return false; + } + + public void addRulesToNewPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) { + + List rules = resourceInstanceProperty.getRules(); + if (rules == null) { + PropertyRule propertyRule = buildRuleFromPath(propertyValueData, resourceInstanceProperty, resourceInstanceId); + rules = new ArrayList<>(); + rules.add(propertyRule); + } else { + rules = sortRules(rules); + } + + propertyValueData.setRules(rules); + } + + private PropertyRule buildRuleFromPath(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) { + List path = resourceInstanceProperty.getPath(); + // FOR BC. Since old Property values on VFC/VF does not have rules on + // graph. + // Update could be done on one level only, thus we can use this + // operation to avoid migration. + if (path == null || path.isEmpty() == true) { + path = new ArrayList<>(); + path.add(resourceInstanceId); + } + PropertyRule propertyRule = new PropertyRule(); + propertyRule.setRule(path); + propertyRule.setValue(propertyValueData.getValue()); + return propertyRule; + } + + private List sortRules(List rules) { + + // TODO: sort the rules by size and binary representation. + // (x, y, .+) --> 110 6 priority 1 + // (x, .+, z) --> 101 5 priority 2 + + return rules; + } + + protected String getValueFromJsonElement(JsonElement jsonElement) { + String value = null; + + if (jsonElement == null || jsonElement.isJsonNull()) { + value = EMPTY_VALUE; + } else { + if (jsonElement.toString().isEmpty()) { + value = ""; + } else { + value = jsonElement.toString(); + } + } + + return value; + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java index 26ea80ac4b..57ab46346a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java @@ -72,9 +72,7 @@ public class CategoriesImportManager { NodeTypeEnum nodeTypeCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.CATEGORY); NodeTypeEnum nodeTypeSubCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.SUBCATEGORY); NodeTypeEnum nodeTypeGroup = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.GROUPING); - if (log.isDebugEnabled()) { - log.debug("createCategoriesByDao: creating componentType:{} nodeTypeCategory:{} nodeTypeSubCategory:{} nodeTypeGroup:{}", componentType, nodeTypeCategory, nodeTypeSubCategory, nodeTypeGroup); - } + log.debug("createCategoriesByDao: creating componentType:{} nodeTypeCategory:{} nodeTypeSubCategory:{} nodeTypeGroup:{}", componentType, nodeTypeCategory, nodeTypeSubCategory, nodeTypeGroup); List newCategoriesvalue = new ArrayList<>(); for (CategoryDefinition category : entry.getValue()) { @@ -124,16 +122,18 @@ public class CategoriesImportManager { Either createdGrouping = elementOperation.createGrouping(subcategory.getUniqueId(), grouping, nodeTypeGroup); if (createdGrouping.isRight()) { if (ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY.equals(createdGrouping.right().value())) { - log.debug(" create grouping for {}. group {} already exists", entry.getKey(), grouping.getName()); + log.debug(" create grouping for {} group {} already exists ", entry.getKey(), grouping.getName()); String groupingId = UniqueIdBuilder.buildGroupingUid(grouping.getUniqueId(), grouping.getNormalizedName()); createdGrouping = elementOperation.getGroupingUniqueForType(nodeTypeGroup, groupingId); if (createdGrouping.isRight()) { - log.debug("failed to get grouping that exists groupingId: {}, type: {}", groupingId, nodeTypeGroup); + log.debug("failed to get grouping that exists groupingId: {} type: {}", groupingId, nodeTypeGroup); return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value())); } } - log.debug("Failed to create groupingcategory for {}, category {}, subcategory {}, grouping {}, error {}", entry.getKey(), category.getName(), subcategory.getName(), (grouping != null ? grouping.getName() : null), - (createdGrouping != null && createdGrouping.right() != null ? createdGrouping.right().value() : null)); + log.debug("Failed to create groupingcategory for {} category {} subcategory {} grouping {} error {}", entry.getKey(), + category.getName(), subcategory.getName(), grouping != null ? grouping.getName() : null, + createdGrouping != null && createdGrouping.right() != null ? createdGrouping.right().value() : null); + return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value())); } else { log.debug("createGroupingDeo: create Grouping was successful {}", createdGrouping.left().value()); @@ -147,15 +147,15 @@ public class CategoriesImportManager { Either createdSubCategory = elementOperation.createSubCategory(newcategory.getUniqueId(), subcategory, nodeTypeSubCategory); if (createdSubCategory.isRight()) { if (ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY.equals(createdSubCategory.right().value())) { - log.debug(" create subcategory for {} category {}, alreay exists retrieving", entry.getKey(), newcategory.getName(), subcategory.getName()); + log.debug(" create subcategory for {} category {} subcategory {} already exists retrieving", entry.getKey(), newcategory.getName(), subcategory.getName()); String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(newcategory.getUniqueId(), subcategory.getNormalizedName()); createdSubCategory = elementOperation.getSubCategory(nodeTypeSubCategory, subCategoryId); if (createdSubCategory.isRight()) { - log.debug("failed to get sub category that exists subCategoryId: {}, type: {}", subCategoryId, nodeTypeSubCategory); + log.debug("failed to get sub category that exists subCategoryId: {} type: {}", subCategoryId, nodeTypeSubCategory); return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value())); } } else { - log.debug("Failed to create subcategory for {} category {}, error {}", entry.getKey(), newcategory.getName(), subcategory.getName(), createdSubCategory.right().value()); + log.debug("Failed to create subcategory for {} category: {} subcategory: {} error {}", entry.getKey(), newcategory.getName(), subcategory.getName(), createdSubCategory.right().value()); return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value())); } } else { @@ -168,7 +168,7 @@ public class CategoriesImportManager { log.debug("createCategorieDeo: creating category {}", category); Either createdCategory = elementOperation.createCategory(category, nodeTypeCategory); if (createdCategory.isRight()) { - log.debug("Failed to create category for {}, error {}", entry.getKey(), category.getName(), createdCategory.right().value()); + log.debug("Failed to create category for {} {} error {}", entry.getKey(), category.getName(), createdCategory.right().value()); if (!ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS.equals(createdCategory.right().value())) { return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value())); } else { @@ -176,7 +176,7 @@ public class CategoriesImportManager { String categoryId = UniqueIdBuilder.buildCategoryUid(category.getNormalizedName(), nodeTypeCategory); createdCategory = elementOperation.getCategory(nodeTypeCategory, categoryId); if (createdCategory.isRight()) { - log.debug("failed to get category that exists categoryId: {}, type: {}", categoryId, nodeTypeCategory); + log.debug("failed to get category that exists categoryId: {} type: {}", categoryId, nodeTypeCategory); return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value())); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java index 9b99b665f7..f97b4cf3f1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java @@ -119,7 +119,7 @@ public class CommonImportManager { } } catch (Exception e) { - log.debug("Failed to yaml file {} {}", elementTypesYml, e); + log.debug("Failed to yaml file {}", elementTypesYml, e); return Either.right(ActionStatus.INVALID_YAML_FILE); } return Either.left(elementTypes); @@ -133,7 +133,7 @@ public class CommonImportManager { } - enum ElementTypeEnum { + public enum ElementTypeEnum { PolicyType, GroupType, DataType, CapabilityType, InterfaceLifecycleType }; @@ -204,7 +204,7 @@ public class CommonImportManager { Either validateElementType = validator.apply(elementType); if (validateElementType.isRight()) { ResponseFormat responseFormat = validateElementType.right().value(); - log.debug("Failed in validation of element type {}. Response is {}", elementType, responseFormat.getFormattedMessage()); + log.debug("Failed in validation of element type: {}. Response is {}", elementType, responseFormat.getFormattedMessage()); eitherResult = Either.right(responseFormat); break; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java index 6c7b8b9bc7..f880883438 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java @@ -24,37 +24,59 @@ import java.util.ArrayList; import java.util.Collection; import java.util.EnumMap; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; import java.util.stream.Collectors; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.ImmutableTriple; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum; +import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; +import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.CapReqDef; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Operation; +import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.cache.ComponentCache; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.ComponentOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.be.utils.CommonBeUtils; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.config.EcompErrorName; @@ -65,6 +87,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import com.datastax.driver.core.UserType.Field; +import com.wordnik.swagger.models.auth.In; + import fj.data.Either; public abstract class ComponentBusinessLogic extends BaseBusinessLogic { @@ -75,6 +100,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { @Autowired protected ComponentCache componentCache; + private static Logger log = LoggerFactory.getLogger(ComponentBusinessLogic.class.getName()); private static final String TAG_FIELD_LABEL = "tag"; @@ -85,6 +111,14 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { public abstract Either, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText); + /** + * + * @param componentId + * @param dataParamsToReturn + * @return + */ + public abstract Either getUiComponentDataTransferByComponentId(String componentId, List dataParamsToReturn); + protected Either validateUser(User user, String ecompErrorContext, Component component, AuditingActionEnum auditAction, boolean inTransaction) { Either userValidationResult = validateUserNotEmpty(user, ecompErrorContext); ResponseFormat responseFormat; @@ -193,12 +227,14 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { protected Either validateComponentNameUnique(User user, Component component, AuditingActionEnum actionEnum) { ComponentTypeEnum type = component.getComponentType(); - ComponentOperation componentOperation = getComponentOperation(type); - Either dataModelResponse; - dataModelResponse = componentOperation.validateComponentNameExists(component.getName()); + ResourceTypeEnum resourceType = null; + if(component instanceof Resource){ + resourceType = ((Resource)component).getResourceType(); + } + Either dataModelResponse = toscaOperationFacade.validateComponentNameExists(component.getName(), resourceType, type); if (dataModelResponse.isLeft()) { - if (dataModelResponse.left().value()) { + if ( !dataModelResponse.left().value()) { return Either.left(true); } else { log.info("Component with name {} already exists", component.getName()); @@ -207,7 +243,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return Either.right(errorResponse); } } - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "validateComponentNameUnique"); BeEcompErrorManager.getInstance().logBeSystemError("validateComponentNameUnique"); log.debug("Error while validateComponentNameUnique for component: {}", component.getName()); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); @@ -216,12 +251,12 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { } protected Either validateContactId(User user, Component component, AuditingActionEnum actionEnum) { - log.debug("validate component contact info"); + log.debug("validate component contactId"); ComponentTypeEnum type = component.getComponentType(); String contactId = component.getContactId(); if (!ValidationUtils.validateStringNotEmpty(contactId)) { - log.info("contact info is missing."); + log.info("contact is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT, type.getValue()); componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type); return Either.right(errorResponse); @@ -238,7 +273,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { private Either validateContactId(String contactId, ComponentTypeEnum type) { if (contactId != null) { if (!ValidationUtils.validateContactId(contactId)) { - log.info("contact info is invalid."); + log.info("contact is invalid."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, type.getValue()); return Either.right(errorResponse); } @@ -247,6 +282,48 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return Either.left(false); } + + public Either validateConformanceLevel(String componentId, ComponentTypeEnum componentTypeEnum, String userId) { + log.trace("validate conformance level"); + + if (componentTypeEnum != ComponentTypeEnum.SERVICE) { + log.error("conformance level validation for non service component, id {}", componentId); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + return Either.right(errorResponse); + } + + Either resp = validateUserExists(userId, "validateConformanceLevel", false); + if (resp.isRight()) { + log.error("can't validate conformance level, user is not validated, id {}, userId {}", componentId, userId); + return Either.right(resp.right().value()); + } + + ComponentParametersView filter = new ComponentParametersView(true); + Either eitherComponent = validateComponentExists(componentId, componentTypeEnum, filter); + if (eitherComponent.isRight()) { + log.error("can't validate conformance level, component not found, id {}", componentId); + BeEcompErrorManager.getInstance().logBeComponentMissingError("validateConformanceLevel", componentTypeEnum.getValue(), componentId); + return Either.right(eitherComponent.right().value()); + } + + Component component = eitherComponent.left().value(); + if (component.getConformanceLevel() == null || "".equals(component.getConformanceLevel())) { + log.error("component conformance level property is null or empty, id {}", componentId); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(errorResponse); + } + + String configConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getMinToscaConformanceLevel(); + Boolean result = true; + if (CommonBeUtils.conformanceLevelCompare(component.getConformanceLevel(), configConformanceLevel) < 0) { + log.error("invalid asset conformance level, id {}, asset conformanceLevel {}, config conformanceLevel {}", componentId, component.getConformanceLevel(), configConformanceLevel); + result = false; + } + log.trace("conformance level validation finished"); + + return Either.left(result); + } + protected Either validateIcon(User user, Component component, AuditingActionEnum actionEnum) { log.debug("validate Icon"); ComponentTypeEnum type = component.getComponentType(); @@ -341,7 +418,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { if (ComponentTypeEnum.RESOURCE.equals(component.getComponentType())) { return Either.left(true); } - log.debug("validate PROJECT_CODE name "); + log.debug("validate ProjectCode name "); String projectCode = component.getProjectCode(); if (!ValidationUtils.validateStringNotEmpty(projectCode)) { @@ -452,9 +529,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { * @return */ public Either getComponent(String componentId, ComponentTypeEnum componentTypeEnum) { - ComponentOperation componentOperation = getComponentOperation(componentTypeEnum); - Either eitherComponent = componentOperation.getComponent(componentId, false); - return eitherComponent; + return toscaOperationFacade.getToscaElement(componentId); } public Either getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) { @@ -463,103 +538,52 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { if (resp.isRight()) { return Either.right(resp.right().value()); } - - Map> capabilities = new HashMap<>(); - Map> requirements = new HashMap<>(); - Either eitherRet; - ComponentOperation componentOperation = getComponentOperation(componentTypeEnum); - Either eitherComponent = validateComponentExists(componentId, componentTypeEnum, false, true); + Either eitherRet = null; + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreCapabilities(false); + filter.setIgnoreRequirements(false); + filter.setIgnoreComponentInstances(false); + Either eitherComponent = validateComponentExists(componentId, componentTypeEnum, filter); if (eitherComponent.isLeft()) { - Either>, TitanOperationStatus> eitherCapabilities = componentOperation.getCapabilities(eitherComponent.left().value(), componentTypeEnum.getNodeType(), false); - if (eitherCapabilities.isRight()) { - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - eitherRet = Either.right(errorResponse); - } else { - Either>, TitanOperationStatus> eitherRequirements = componentOperation.getRequirements(eitherComponent.left().value(), componentTypeEnum.getNodeType(), false); - if (eitherRequirements.isRight()) { - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - eitherRet = Either.right(errorResponse); - } else { - requirements = eitherRequirements.left().value(); - capabilities = eitherCapabilities.left().value(); - eitherRet = Either.left(new CapReqDef(requirements, capabilities)); - } - } + eitherRet = Either.left(new CapReqDef(eitherComponent.left().value().getRequirements(), eitherComponent.left().value().getCapabilities())); } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "getRequirementsAndCapabilities", componentId); BeEcompErrorManager.getInstance().logBeComponentMissingError("getRequirementsAndCapabilities", componentTypeEnum.getValue(), componentId); eitherRet = Either.right(eitherComponent.right().value()); } - return eitherRet; } public Either, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, List componentUids, String userId) { - - long startUser = System.currentTimeMillis(); - Either resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false); - long endUser = System.currentTimeMillis(); - log.debug("Activation time of get user {} ms", (endUser - startUser)); - ResponseFormat responseFormat; - if (resp.isLeft()) { - - List result = new ArrayList(); - Set nonProcessesComponents = new HashSet<>(); - nonProcessesComponents.addAll(componentUids); - - long startGetComp = System.currentTimeMillis(); - // Read components from cache - Set filteredComponents = new HashSet<>(); - filteredComponents.addAll(componentUids); - - Either, List, Set>, ActionStatus> allPartialComponents = componentCache.getComponentsForLeftPanel(componentTypeEnum, internalComponentType, filteredComponents); - - if (allPartialComponents.isRight()) { - log.debug("Components was not fetched from cache. Status is {}", allPartialComponents.right().value()); - } else { - ImmutableTriple, List, Set> immutableTriple = allPartialComponents.left().value(); - List processedComponents = immutableTriple.left; - if (processedComponents != null) { - result.addAll(processedComponents); - } - List dirtyComponents = immutableTriple.middle; - if (dirtyComponents != null) { - result.addAll(dirtyComponents); - } - - Set nonProcessesComponentsFromCache = immutableTriple.right; - nonProcessesComponents = nonProcessesComponentsFromCache; - } - long endGetComp = System.currentTimeMillis(); - log.debug("Activation time of get Comp from cache {} ms", (endGetComp - startGetComp)); - - // Fecth non cached components - List componentsUidToFetch = new ArrayList(); - componentsUidToFetch.addAll(nonProcessesComponents); - - long startGetCompFromGraph = System.currentTimeMillis(); - if (componentsUidToFetch.size() > 0) { - log.debug("Number of Components to fetch from graph is {}", componentsUidToFetch.size()); - ComponentOperation componentOperation = getComponentOperation(componentTypeEnum); - Boolean isHighest = isHighest(highestFilter); - Either, StorageOperationStatus> nonCheckoutCompResponse = componentOperation.getLatestVersionNotAbstractComponents(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType, componentsUidToFetch); - - if (nonCheckoutCompResponse.isLeft()) { - log.debug("Retrived Resource successfully."); - result.addAll(nonCheckoutCompResponse.left().value()); - } else { - responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())); + ResponseFormat responseFormat = null; + try{ + Either resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false); + + if (resp.isLeft()) { + List result = new ArrayList<>(); + List componentsUidToFetch = new ArrayList<>(); + componentsUidToFetch.addAll(componentUids); + + if (componentsUidToFetch.size() > 0) { + log.debug("Number of Components to fetch from graph is {}", componentsUidToFetch.size()); + Boolean isHighest = isHighest(highestFilter); + Either, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractComponents(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType, componentsUidToFetch); + + if (nonCheckoutCompResponse.isLeft()) { + log.debug("Retrived Resource successfully."); + result.addAll(nonCheckoutCompResponse.left().value()); + } else { + responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())); + } } + return Either.left(result); + } else { + responseFormat = resp.right().value(); } - long endGetCompFromGraph = System.currentTimeMillis(); - log.debug("Activation time of get Comp from graph {} ms", (endGetCompFromGraph - startGetCompFromGraph)); - - return Either.left(result); - } else { - responseFormat = resp.right().value(); } - + finally{ + titanDao.commit(); + } return Either.right(responseFormat); } @@ -580,42 +604,27 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return isHighest; } - public Either>, ResponseFormat> getLatestVersionNotAbstractComponentsUidOnly(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, String userId) { - Either resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false); - ResponseFormat responseFormat; - if (resp.isLeft()) { - - ComponentOperation componentOperation = getComponentOperation(componentTypeEnum); - Boolean isHighest = isHighest(highestFilter); - Either, StorageOperationStatus> nonCheckoutCompResponse = componentOperation.getLatestVersionNotAbstractComponentsMetadataOnly(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType); - - if (nonCheckoutCompResponse.isLeft()) { - log.debug("Retrived Resource successfully."); - List> res = new ArrayList<>(); - - // MapresMap = - // nonCheckoutCompResponse.left().value().stream().collect() - // .collect(Collectors.toMap( - // p -> p.getMetadataDataDefinition().getUniqueId(), - // p-> p.getMetadataDataDefinition().getVersion())); - - res = nonCheckoutCompResponse.left().value().stream().map(p -> { - HashMap map = new HashMap<>(); - map.put("uid", p.getMetadataDataDefinition().getUniqueId()); - map.put("version", p.getMetadataDataDefinition().getVersion()); - Long lastUpdateDate = p.getMetadataDataDefinition().getLastUpdateDate(); - String lastUpdateDateStr = lastUpdateDate != null ? String.valueOf(lastUpdateDate.longValue()) : "0"; - map.put("timestamp", lastUpdateDateStr); - return map; - }).collect(Collectors.toList()); - - return Either.left(res); - } - responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())); - } else { - responseFormat = resp.right().value(); - } + public Either, ResponseFormat> getLatestVersionNotAbstractComponentsMetadata(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, String userId) { + ResponseFormat responseFormat = null; + try{ + Either resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false); + if (resp.isLeft()) { + + Boolean isHighest = isHighest(highestFilter); + Either, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType); + + if (nonCheckoutCompResponse.isLeft()) { + log.debug("Retrived Resource successfully."); + return Either.left(nonCheckoutCompResponse.left().value()); + } + responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())); + } else { + responseFormat = resp.right().value(); + } + } finally { + titanDao.commit(); + } return Either.right(responseFormat); } @@ -623,6 +632,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { } + @SuppressWarnings("unchecked") public void setToscaArtifactsPlaceHolders(Component component, User user) { Map artifactMap = component.getToscaArtifacts(); if (artifactMap == null) { @@ -645,17 +655,37 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { } public Either, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock) { + return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true); + } + + public Either, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock, boolean fetchTemplatesFromDB) { + Either toscaElement = toscaOperationFacade.getToscaFullElement(component.getUniqueId()); + if ( toscaElement.isRight() ){ + ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(toscaElement.right().value(), component.getComponentType())); + return Either.right(response); + } + component = toscaElement.left().value(); Either, ResponseFormat> generateToscaRes = null; if (component.getToscaArtifacts() != null && !component.getToscaArtifacts().isEmpty()) { - ArtifactDefinition toscaArtifact = component.getToscaArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny().get(); - generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, true); + ArtifactDefinition toscaArtifact = component.getToscaArtifacts().values().stream() + .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())) + .findAny().get(); + generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB); if (generateToscaRes.isRight()) { return generateToscaRes; } - toscaArtifact = component.getToscaArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny().get(); + toscaArtifact = generateToscaRes.left().value().left().value(); + component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact); + toscaArtifact = component.getToscaArtifacts().values().stream() + .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) + .findAny().get(); generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, true); } - // TODO if csar artifact fails delete template artifact + if (generateToscaRes.isRight()) { + return generateToscaRes; + } + ArtifactDefinition toscaArtifact = generateToscaRes.left().value().left().value(); + component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact); return generateToscaRes; } @@ -665,23 +695,35 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { } public Either, ResponseFormat> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid, EnumMap additionalParam) { - // get info - ComponentOperation componentOperation = getComponentOperation(componentType); - Either latestVersion = componentOperation.getLatestComponentByUuid(componentType.getNodeType(), uuid); - if (latestVersion.isRight()) { - ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(latestVersion.right().value(), componentType)); + + Either, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getComponentListByUuid(uuid, null); + + if (latestVersionEither.isRight()) { + ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentType)); + return Either.right(response); + } + + List components = latestVersionEither.left().value(); + + Component component = components.stream().filter(c -> c.isHighestVersion()).findFirst().orElse(null); + if(component == null){ + component = components.stream().filter(c -> c.getLifecycleState() == LifecycleStateEnum.CERTIFIED).findFirst().orElse(null); + } + + if(component == null){ + ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType)); return Either.right(response); - } - Component component = latestVersion.left().value(); additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName()); // TODO remove after migration - handle artifact not found(no // placeholder) if (null == component.getToscaArtifacts() || component.getToscaArtifacts().isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ArtifactTypeEnum.TOSCA_CSAR.name())); } - ArtifactDefinition csarArtifact = component.getToscaArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny().get(); - return artifactsBusinessLogic.handleDownloadToscaModelRequest(component, csarArtifact, true, false); + ArtifactDefinition csarArtifact = component.getToscaArtifacts().values().stream() + .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) + .findAny().get(); + return artifactsBusinessLogic.handleDownloadToscaModelRequest(component, csarArtifact); } protected StorageOperationStatus markComponentToDelete(Component component) { @@ -693,13 +735,10 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return StorageOperationStatus.NOT_FOUND; } - ComponentOperation componentOperation = getComponentOperation(componentType); - - Either markResourceToDelete = componentOperation.markComponentToDelete(component, true); - if (markResourceToDelete.isRight()) { - StorageOperationStatus result = markResourceToDelete.right().value(); - log.debug("failed to mark component {} of type {} for delete. error = {}", uniqueId, componentType, result); - return result; + StorageOperationStatus markResourceToDelete = toscaOperationFacade.markComponentToDelete(component); + if (StorageOperationStatus.OK != markResourceToDelete) { + log.debug("failed to mark component {} of type {} for delete. error = {}", uniqueId, componentType, markResourceToDelete); + return markResourceToDelete; } else { log.debug("Component {} of type {} was marked as deleted", uniqueId, componentType); return StorageOperationStatus.OK; @@ -756,43 +795,52 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { protected Either, ResponseFormat> deleteMarkedComponents(ComponentTypeEnum componentType) { - List deletedComponents = new ArrayList(); +// List deletedComponents = new ArrayList(); log.trace("start deleteMarkedComponents"); - ComponentOperation componentOperation = getComponentOperation(componentType); - Either, StorageOperationStatus> resourcesToDelete = componentOperation.getAllComponentsMarkedForDeletion(); - if (resourcesToDelete.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourcesToDelete.right().value(), componentType)); + Either, StorageOperationStatus> deleteMarkedElements = toscaOperationFacade.deleteMarkedElements(componentType); + + titanDao.commit(); + if ( deleteMarkedElements.isRight()){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType)); return Either.right(responseFormat); } - - for (String resourceToDelete : resourcesToDelete.left().value()) { - - Either deleteMarkedResource = deleteMarkedComponent(resourceToDelete, componentType); - if (deleteMarkedResource.isLeft()) { - deletedComponents.add(deleteMarkedResource.left().value()); - } - } - +// ComponentOperation componentOperation = getComponentOperation(componentType); +// Either, StorageOperationStatus> resourcesToDelete = componentOperation.getAllComponentsMarkedForDeletion(); +// if (resourcesToDelete.isRight()) { +// ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourcesToDelete.right().value(), componentType)); +// return Either.right(responseFormat); +// } +// +// for (String resourceToDelete : resourcesToDelete.left().value()) { +// +// Either deleteMarkedResource = deleteMarkedComponent(resourceToDelete, componentType); +// if (deleteMarkedResource.isLeft()) { +// deletedComponents.add(deleteMarkedResource.left().value()); +// } +// } +// if(deletedComponents.size() == 0) { +// log.debug("Component list to delete is empty. do commit"); +// titanGenericDao.commit(); +// } log.trace("end deleteMarkedComponents"); - return Either.left(deletedComponents); + return Either.left(deleteMarkedElements.left().value()); } private Either deleteMarkedComponent(String componentToDelete, ComponentTypeEnum componentType) { Either result = null; - ComponentOperation componentOperation = getComponentOperation(componentType); NodeTypeEnum compNodeType = componentType.getNodeType(); StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentToDelete, compNodeType); if (!lockResult.equals(StorageOperationStatus.OK)) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, "Delete marked component"); - log.debug("Failed to lock component {}. error - {}", componentToDelete, lockResult); + log.debug("Failed to lock component {} error - {}", componentToDelete, lockResult); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return result; } try { // check if resource has relations - Either isResourceInUse = componentOperation.isComponentInUse(componentToDelete); + Either isResourceInUse = toscaOperationFacade.isComponentInUse(componentToDelete); if (isResourceInUse.isRight()) { log.info("deleteMarkedResource - failed to find relations to resource. id = {}, type = {}, error = {}", componentToDelete, componentType, isResourceInUse.right().value().name()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); @@ -803,7 +851,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { if (isResourceInUse.isLeft() && isResourceInUse.left().value() == false) { // delete resource and its artifacts in one transaction - Either, StorageOperationStatus> artifactsRes = componentOperation.getComponentArtifactsForDelete(componentToDelete, compNodeType, true); + Either, StorageOperationStatus> artifactsRes = getComponentArtifactsForDelete(componentToDelete, compNodeType, true); if (artifactsRes.isRight() && !artifactsRes.right().value().equals(StorageOperationStatus.NOT_FOUND)) { log.info("failed to check artifacts for component node. id = {}, type = {}, error = {}", componentToDelete, componentType, artifactsRes.right().value().name()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); @@ -814,8 +862,8 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { if (artifactsRes.isLeft()) { artifactsToDelete = artifactsRes.left().value(); } - - Either deleteComponentRes = componentOperation.deleteComponent(componentToDelete, true); + + Either deleteComponentRes = toscaOperationFacade.deleteToscaComponent(componentToDelete); if (deleteComponentRes.isRight()) { log.info("failed to delete component. id = {}, type = {}, error = {}", componentToDelete, componentType, deleteComponentRes.right().value().name()); ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteComponentRes.right().value()); @@ -846,15 +894,337 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { if (result == null || result.isRight()) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "delete marked component"); log.debug("operation failed. do rollback"); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("operation success. do commit"); - titanGenericDao.commit(); + titanDao.commit(); } graphLockOperation.unlockComponent(componentToDelete, compNodeType); } return result; } + + public Either, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType, boolean inTransacton) { + List artifacts = new ArrayList(); + Either, StorageOperationStatus> artifactsResponse = artifactToscaOperation.getArtifacts(parentId); + if (artifactsResponse.isRight()) { + if (!artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + log.debug("failed to retrieve artifacts for {} {}", parentType, parentId); + return Either.right(artifactsResponse.right().value()); + } + } else { + artifacts.addAll(artifactsResponse.left().value().values()); + } + +// if (NodeTypeEnum.Resource.equals(parentType)) { +// Either, StorageOperationStatus> interfacesArtifactsForResource = getAdditionalArtifacts(parentId, false, true); +// if (artifactsResponse.isRight() && !interfacesArtifactsForResource.right().value().equals(StorageOperationStatus.NOT_FOUND)) { +// log.debug("failed to retrieve interface artifacts for {} {}", parentType, parentId); +// return Either.right(interfacesArtifactsForResource.right().value()); +// } else if (artifactsResponse.isLeft()) { +// artifacts.addAll(interfacesArtifactsForResource.left().value()); +// } +// } + return Either.left(artifacts); + } + + /** + * + * @param componentId + * @param user + * @param dataParamsToReturn - ui list of params to return + * @return + */ + + public Either getComponentDataFilteredByParams(String componentId, User user, List dataParamsToReturn) { + + if (user != null) { + Either eitherCreator = validateUserExists(user, "Get Component by filtered by ui params", false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + } + + UiComponentDataTransfer result = new UiComponentDataTransfer(); + + if(dataParamsToReturn == null || dataParamsToReturn.isEmpty()) { + Either.left(result); + + } else { + Either uiDataTransferEither = getUiComponentDataTransferByComponentId(componentId, dataParamsToReturn); + if(uiDataTransferEither.isRight()){ + return Either.right(uiDataTransferEither.right().value()); + } + result = uiDataTransferEither.left().value(); + } + + return Either.left(result); + } + + protected void generateInputsFromGenericTypeProperties(T component, Resource genericType) { + + List genericTypeProps = genericType.getProperties(); + if(null != genericTypeProps) { + String genericUniqueId = genericType.getUniqueId(); + List inputs = convertGenericTypePropertiesToInputsDefintion(genericTypeProps, genericUniqueId); + if(null != component.getInputs()) + inputs.addAll(component.getInputs()); + component.setInputs(inputs); + } + } + + private List convertGenericTypePropertiesToInputsDefintion(List genericTypeProps, String genericUniqueId) { + return genericTypeProps.stream() + .map(p -> setInputDefinitionFromProp(p, genericUniqueId)) + .collect(Collectors.toList()); + } + + private InputDefinition setInputDefinitionFromProp(PropertyDefinition prop, String genericUniqueId){ + InputDefinition input = new InputDefinition(prop); + input.setOwnerId(genericUniqueId); + return input; + } + + protected Either fetchAndSetDerivedFromGenericType(T component){ + + String genericTypeToscaName = component.fetchGenericTypeToscaNameFromConfig(); + if(null == genericTypeToscaName) + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + Either findLatestGeneric = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(genericTypeToscaName); + if(findLatestGeneric.isRight()) + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType(), genericTypeToscaName)); + Resource genericTypeResource = findLatestGeneric.left().value(); + component.setDerivedFromGenericInfo(genericTypeResource); + return Either.left(genericTypeResource); + } + + public Either>, ResponseFormat> getFilteredComponentInstanceProperties(String componentId, Map> filters, String userId) { + Either>, ResponseFormat> response = null; + Either getResourceRes = null; + try{ + if(!filters.containsKey(FilterKeyEnum.NAME_FRAGMENT) && StringUtils.isEmpty(filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0))){ + response = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + if (userId != null && response == null) { + Either validateUserRes = validateUserExists(userId, "Get filtered component instance properties", false); + if (validateUserRes.isRight()) { + response = Either.right(validateUserRes.right().value()); + } + } + if(response == null){ + getResourceRes = toscaOperationFacade.getToscaElement(componentId); + if(getResourceRes.isRight()){ + response = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()))); + } + } + if(response == null){ + response = getFilteredComponentInstancesProperties(getResourceRes.left().value(), filters); + } + } catch(Exception e){ + log.debug("The exception {} occured during filtered instance properties fetching. the containing component is {}. ", e, componentId); + response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally{ + if (response.isLeft()){ + toscaOperationFacade.commit(); + } else { + toscaOperationFacade.rollback(); + } + } + return response; + } + + private Either>, ResponseFormat> getFilteredComponentInstancesProperties(Component component, Map> filters) { + + Map> filteredProperties = new HashMap<>(); + Either>, ResponseFormat> result = Either.left(filteredProperties); + List filteredInstances = getFilteredInstances(component, filters.get(FilterKeyEnum.RESOURCE_TYPE)); + String propertyNameFragment= filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0); + boolean searchByFragment = propertyNameFragment.length() > 3 ; + if(CollectionUtils.isNotEmpty(filteredInstances)){ + for(ComponentInstance instance : filteredInstances){ + if(component.getComponentInstancesProperties()!=null &&component.getComponentInstancesProperties().containsKey(instance.getUniqueId())){ + List currProperties = getFilteredComponentInstanceProperties(component.getComponentInstancesProperties().get(instance.getUniqueId()), propertyNameFragment, searchByFragment); + if(CollectionUtils.isNotEmpty(currProperties)){ + filteredProperties.put(instance.getUniqueId(), currProperties); + } + } + if(component.getComponentInstancesInputs()!=null && component.getComponentInstancesInputs().containsKey(instance.getUniqueId())){ + List currInputs = getFilteredComponentInstanceInputs(component.getComponentInstancesInputs().get(instance.getUniqueId()), propertyNameFragment, searchByFragment); + if(CollectionUtils.isNotEmpty(currInputs)){ + if(filteredProperties.get(instance.getUniqueId())!=null){ + filteredProperties.get(instance.getUniqueId()).addAll(currInputs); + } else { + filteredProperties.put(instance.getUniqueId(), currInputs); + } + } + } + } + } + return result; + } + + private List getFilteredComponentInstanceInputs(List inputs, String propertyNameFragment, boolean searchByFragment) { + return inputs.stream().filter(i -> isMatchingInput(i, propertyNameFragment, searchByFragment)).collect(Collectors.toList()); + } + + private List getFilteredComponentInstanceProperties(List instanceProperties, String propertyNameFragment, boolean searchByFragment) { + return instanceProperties.stream().filter(p -> isMatchingProperty(p, propertyNameFragment, searchByFragment)).collect(Collectors.toList()); + } + + private boolean isMatchingInput(ComponentInstanceInput input, String propertyNameFragment, boolean searchByFragment) { + boolean isMatching = false; + if(searchByFragment && input.getName().toLowerCase().contains(propertyNameFragment)){ + isMatching = true; + } + if(!searchByFragment && input.getName().equalsIgnoreCase(propertyNameFragment)){ + isMatching = true; + } + return isMatching; + } + + private boolean isMatchingProperty(ComponentInstanceProperty property, String propertyNameFragment, boolean searchByFragment) { + boolean isMatching = false; + if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment)){ + isMatching = true; + } + if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){ + isMatching = true; + } + if (!isMatching && !ToscaPropertyType.isPrimitiveType(property.getType())){ + isMatching = isMatchingComplexPropertyByRecursively(property, propertyNameFragment, searchByFragment); + } + return isMatching; + } + + private boolean isMatchingComplexPropertyByRecursively(PropertyDataDefinition property, String propertyNameFragment, boolean searchByFragment) { + String propertyType; + List dataTypeProperties; + DataTypeDefinition currentProperty; + if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment.toLowerCase())){ + return true; + } + if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){ + return true; + } + + propertyType = isEmptyInnerType(property) ? property.getType() : property.getSchema().getProperty().getType(); + + if(ToscaPropertyType.isScalarType(propertyType)){ + return false; + } + Either getDataTypeByNameRes = propertyOperation.getDataTypeByName(propertyType); + if(getDataTypeByNameRes.isRight()){ + return false; + } + currentProperty = getDataTypeByNameRes.left().value(); + dataTypeProperties = currentProperty.getProperties(); + + if(CollectionUtils.isNotEmpty(dataTypeProperties)){ + for(PropertyDefinition prop : dataTypeProperties){ + if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){ + return true; + } + } + } + dataTypeProperties = currentProperty.getDerivedFrom().getProperties(); + if(CollectionUtils.isNotEmpty(dataTypeProperties)){ + for(PropertyDefinition prop : dataTypeProperties){ + if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){ + return true; + } + } + } + return false; + } + + private boolean isEmptyInnerType(PropertyDataDefinition property) { + return property == null|| property.getSchema() == null || property.getSchema().getProperty() == null || property.getSchema().getProperty().getType() == null; + } + + public Either shouldUpgradeToLatestGeneric(Component clonedComponent) { + + if(!clonedComponent.deriveFromGeneric()) + return Either.left(false); + Boolean shouldUpgrade = false; + String currentGenericType = clonedComponent.getDerivedFromGenericType(); + String currentGenericVersion = clonedComponent.getDerivedFromGenericVersion(); + Either fetchAndSetLatestGeneric = fetchAndSetDerivedFromGenericType(clonedComponent); + if(fetchAndSetLatestGeneric.isRight()) + return Either.right(fetchAndSetLatestGeneric.right().value()); + Resource genericTypeResource = fetchAndSetLatestGeneric.left().value(); + if(null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion.equals(genericTypeResource.getVersion())){ + List genericTypeProps = genericTypeResource.getProperties(); + List genericTypeInputs = null == genericTypeProps? null : convertGenericTypePropertiesToInputsDefintion(genericTypeProps, genericTypeResource.getUniqueId()); + shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeInputs); + if(!shouldUpgrade) { + reverntUpdateOfGenericVersion(clonedComponent, currentGenericType, currentGenericVersion); + } + } + return Either.left(shouldUpgrade); + } + + private void reverntUpdateOfGenericVersion(Component clonedComponent, String currentGenericType, String currentGenericVersion) { + clonedComponent.setDerivedFromGenericType(currentGenericType); + clonedComponent.setDerivedFromGenericVersion(currentGenericVersion); + } + + + private boolean upgradeToLatestGeneric(Component componentToCheckOut, List upgradedList) { + + if (!componentToCheckOut.shouldGenerateInputs()) + return true; + + List currentList = new ArrayList<>(); + // nullify existing ownerId from existing list and merge into updated list + if (null != componentToCheckOut.getInputs()) { + for(InputDefinition input : componentToCheckOut.getInputs()) { + InputDefinition copy = new InputDefinition(input); + copy.setOwnerId(null); + currentList.add(copy); + } + } + if (null == upgradedList) { + componentToCheckOut.setInputs(currentList); + return true; + } + Map currentMap = PropertyDataDefinition.listToMapByName(currentList); + Map upgradedMap = PropertyDataDefinition.listToMapByName(upgradedList); + Either, String> eitherMerged = PropertyDataDefinition.mergeProperties(upgradedMap, currentMap, true); + if (eitherMerged.isRight()) { + log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic", eitherMerged.right().value()); + return false; + } + componentToCheckOut.setInputs(new ArrayList(eitherMerged.left().value().values())); + return true; + } + + private List getFilteredInstances(Component component, List resourceTypes) { + List filteredInstances = null; + if(CollectionUtils.isEmpty(resourceTypes)){ + filteredInstances = component.getComponentInstances(); + } + else if(CollectionUtils.isNotEmpty(component.getComponentInstances())){ + filteredInstances = component.getComponentInstances() + .stream().filter(i -> isMatchingType(i.getOriginType(), resourceTypes)).collect(Collectors.toList()); + } + if(filteredInstances == null){ + filteredInstances = new ArrayList<>(); + } + return filteredInstances; + } + + private boolean isMatchingType(OriginTypeEnum originType, List resourceTypes) { + boolean isMatchingType = false; + for(String resourceType : resourceTypes){ + if(originType == OriginTypeEnum.findByValue(resourceType.toUpperCase())){ + isMatchingType = true; + break; + } + } + return isMatchingType; + } } + + diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java index 89ef6f7e19..1623375926 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java @@ -21,21 +21,32 @@ package org.openecomp.sdc.be.components.impl; import java.util.ArrayList; -import java.util.EnumMap; import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; +import java.util.Optional; +import java.util.UUID; import java.util.stream.Collectors; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; -import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.info.CreateAndAssotiateInfo; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; @@ -44,25 +55,29 @@ import org.openecomp.sdc.be.model.ComponentInstanceAttribute; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.HeatParameterDefinition; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupInstance; import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames; +import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation; -import org.openecomp.sdc.be.model.operations.api.IComponentOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.ComponentOperation; -import org.openecomp.sdc.be.model.operations.impl.GroupOperation; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; +import org.openecomp.sdc.be.resources.data.ComponentInstanceData; +import org.openecomp.sdc.be.resources.data.PropertyValueData; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.datastructure.Wrapper; -import org.openecomp.sdc.common.util.GeneralUtility; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; @@ -73,95 +88,86 @@ import fj.data.Either; public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { - private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension"; - - static final String HEAT_ENV_NAME = "heatEnv"; - private static final String HEAT_ENV_SUFFIX = "env"; - private static Logger log = LoggerFactory.getLogger(ComponentInstanceBusinessLogic.class.getName()); @Autowired private IComponentInstanceOperation componentInstanceOperation; - @Autowired - private PropertyOperation propertyOperation; - @Autowired private ArtifactsBusinessLogic artifactBusinessLogic; - @Autowired - private GroupOperation groupOperation; + private ApplicationDataTypeCache dataTypeCache; + + public static final String VF_MODULE = "org.openecomp.groups.VfModule"; public ComponentInstanceBusinessLogic() { } public Either createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) { - return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true, true, true); + return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true); } - public Either createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock, - boolean createNewTransaction) { - - Either resp = validateUserExists(userId, "create Component Instance", inTransaction); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class); - if (validateValidJson.isRight()) { - return Either.right(validateValidJson.right().value()); - } + public Either createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) { - Either validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - final ComponentOperation containerOperation = getComponentOperation(containerComponentType); - - Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, inTransaction, createNewTransaction); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); - - Either validateAllowedToContainCompInstances = validateAllowedToContainCompInstances(containerComponent); - if (validateAllowedToContainCompInstances.isRight()) { - return Either.right(validateAllowedToContainCompInstances.right().value()); - } - - Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - if (resourceInstance != null && containerComponentType != null) { - Either validateComponentInstanceParentState = validateComponentInstanceParentState(containerComponentType, resourceInstance); - if (validateComponentInstanceParentState.isRight()) { - return Either.right(validateComponentInstanceParentState.right().value()); + Component origComponent = null; + Either resultOp = null; + User user = null; + org.openecomp.sdc.be.model.Component containerComponent = null; + ComponentTypeEnum containerComponentType; + + try{ + Either resp = validateUserExists(userId, "create Component Instance", inTransaction); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } else { + user = resp.left().value(); } - } - if (needLock) { - - Either lockComponent = lockComponent(containerComponent, "createComponentInstance"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); + Either validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class); + if (validateValidJson.isRight()) { + return Either.right(validateValidJson.right().value()); } - } - - Either resultOp = null; - try { - log.debug("Try to create entry on graph"); - Either eitherResourceName = getOriginComponentNameFromComponentInstance(resourceInstance, inTransaction); - - if (eitherResourceName.isRight()) { - resultOp = Either.right(eitherResourceName.right().value()); - return resultOp; + + Either validateComponentType = validateComponentType(containerComponentParam); + if (validateComponentType.isRight()) { + return Either.right(validateComponentType.right().value()); + } else { + containerComponentType = validateComponentType.left().value(); } - Component origComponent = eitherResourceName.left().value(); - - resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, userId, containerOperation, inTransaction); + + Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } else { + containerComponent = validateComponentExists.left().value(); + } + + Either validateAllowedToContainCompInstances = validateAllowedToContainCompInstances(containerComponent); + if (validateAllowedToContainCompInstances.isRight()) { + return Either.right(validateAllowedToContainCompInstances.right().value()); + } + + Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); + if (validateCanWorkOnComponent.isRight()) { + return Either.right(validateCanWorkOnComponent.right().value()); + } + + if (resourceInstance != null && containerComponentType != null) { + Either getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance); + if (getOriginComponentRes.isRight()) { + return Either.right(getOriginComponentRes.right().value()); + } else { + origComponent = getOriginComponentRes.left().value(); + } + } + if (needLock) { + Either lockComponent = lockComponent(containerComponent, "createComponentInstance"); + if (lockComponent.isRight()) { + return Either.right(lockComponent.right().value()); + } + } + log.debug("Try to create entry on graph"); + resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user); return resultOp; } finally { @@ -181,15 +187,15 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return Either.right(resp.right().value()); } + User user = resp.left().value(); Either validateComponentType = validateComponentType(containerComponentParam); if (validateComponentType.isRight()) { return Either.right(validateComponentType.right().value()); } final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - final ComponentOperation containerOperation = getComponentOperation(containerComponentType); - Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, false, true); + Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); if (validateComponentExists.isRight()) { return Either.right(validateComponentExists.right().value()); } @@ -212,7 +218,6 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { try { log.debug("Try to create entry on graph"); - NodeTypeEnum containerNodeType = containerComponentType.getNodeType(); Either eitherResourceName = getOriginComponentNameFromComponentInstance(resourceInstance, true); if (eitherResourceName.isRight()) { @@ -221,7 +226,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } Component origComponent = eitherResourceName.left().value(); - Either result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, userId, containerOperation, true); + Either result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user); if (result.isRight()) { log.debug("Failed to create resource instance {}", containerComponentId); resultOp = Either.right(result.right().value()); @@ -238,8 +243,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;// createRequirementCapabilityrelDef(associationInfo); - - Either resultReqCapDef = componentInstanceOperation.associateResourceInstances(containerComponentId, containerNodeType, requirementCapabilityRelDef, true); + Either resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef); if (resultReqCapDef.isLeft()) { log.debug("Enty on graph is created."); RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value(); @@ -260,7 +264,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { private Either getOriginComponentNameFromComponentInstance(ComponentInstance componentInstance, boolean inTransaction) { Either eitherResponse; - Either eitherComponent = getCompInstOriginComponentOperation().getComponent(componentInstance.getComponentUid(), inTransaction); + Either eitherComponent = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid()); if (eitherComponent.isRight()) { log.debug("Failed to get origin component with id {} for component instance {} ", componentInstance.getComponentUid(), componentInstance.getName()); eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null)); @@ -270,167 +274,10 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return eitherResponse; } - private Either handleNameLogic(Component origComponent, ComponentInstance componentInstance, ComponentTypeEnum containerComponentType, String containerComponentId, boolean isCreate, boolean inTransaction) { - Either eitherResult; - final ComponentOperation containerOperation = getComponentOperation(containerComponentType); - - Either componentInNumberStatus = containerOperation.increaseAndGetComponentInstanceCounter(containerComponentId, true); - - if (componentInNumberStatus.isRight()) { - log.debug("Failed to get component instance number for container component {} ", containerComponentId); - eitherResult = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(componentInNumberStatus.right().value(), true), "", null)); - } else { - String resourceInNumber = componentInNumberStatus.left().value().toString(); - eitherResult = Either.left(resourceInNumber); - } - - if (eitherResult.isLeft()) { - Either eitherSpecificLogic; - if (isCreate) { - eitherSpecificLogic = handleNameLogicForNewComponentInstance(origComponent, componentInstance, eitherResult.left().value(), containerComponentType, inTransaction); - } else { - eitherSpecificLogic = handleNameLogicForUpdatingComponentInstance(origComponent, componentInstance, componentInNumberStatus, containerComponentType, inTransaction); - } - if (eitherSpecificLogic.isRight()) { - eitherResult = Either.right(eitherSpecificLogic.right().value()); - } - } - return eitherResult; - } - - private Either handleNameLogicForUpdatingComponentInstance(Component origComponent, ComponentInstance componentInstance, Either componentInNumberStatus, - ComponentTypeEnum containerComponentType, boolean inTransaction) { - Either eitherResult = Either.left(true); - if (componentInstance.getName() == null || componentInstance.getName().isEmpty()) { - if (origComponent == null) { - Either eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, inTransaction); - - if (eitherResourceName.isRight()) { - eitherResult = Either.right(eitherResourceName.right().value()); - return eitherResult; - } - origComponent = eitherResourceName.left().value(); - - String resourceName = origComponent.getName(); - String logicalName = componentInstanceOperation.createComponentInstLogicalName(componentInNumberStatus.left().value().toString(), resourceName); - componentInstance.setName(logicalName); - if (containerComponentType == ComponentTypeEnum.RESOURCE) { - Resource resource = (Resource) origComponent; - componentInstance.setToscaComponentName(resource.getToscaResourceName()); - } - - } - } - - Either eitherValidation = validateComponentInstanceName(componentInstance.getName(), componentInstance, false); - if (eitherValidation.isRight()) { - eitherResult = Either.right(eitherValidation.right().value()); - } - return eitherResult; - } - - private Either handleNameLogicForNewComponentInstance(Component origComponent, ComponentInstance componentInstance, String resourceInNumber, ComponentTypeEnum containerComponentType, boolean inTransaction) { - Either eitherResult = Either.left(true); - - if (origComponent == null) { - Either eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, inTransaction); - - if (eitherResourceName.isRight()) { - eitherResult = Either.right(eitherResourceName.right().value()); - return eitherResult; - } - - origComponent = eitherResourceName.left().value(); - } - - String resourceName = origComponent.getName(); - componentInstance.setComponentName(resourceName); - if (componentInstance.getName() == null || componentInstance.getName().isEmpty()) - componentInstance.setName(resourceName); - String logicalName = componentInstanceOperation.createComponentInstLogicalName(resourceInNumber, componentInstance.getName()); - - Either eitherValidation = validateComponentInstanceName(logicalName, componentInstance, true); - if (eitherValidation.isRight()) { - eitherResult = Either.right(eitherValidation.right().value()); - } - if (containerComponentType == ComponentTypeEnum.RESOURCE) { - Resource resource = (Resource) origComponent; - componentInstance.setToscaComponentName(resource.getToscaResourceName()); - } - - return eitherResult; - } - - public Either createComponentInstanceOnGraph(String containerComponentParam, org.openecomp.sdc.be.model.Component containerComponent, Component origComponent, ComponentInstance componentInstance, String userId, - boolean needLock, boolean inTransaction) { - - Either validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - final ComponentOperation containerOperation = getComponentOperation(containerComponentType); - Either resultOp = null; - if (needLock) { - - Either lockComponent = lockComponent(containerComponent, "createComponentInstance"); - - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - try { - resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, componentInstance, userId, containerOperation, inTransaction); - return resultOp; - - } finally { - if (needLock) - unlockComponent(resultOp, containerComponent); - } - - } - - private Map getExistingEnvVersions(ComponentInstance componentInstance) { - if (null == componentInstance.getDeploymentArtifacts()) - return null; - return componentInstance.getDeploymentArtifacts().values() - //filter env artifacts - .stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) - //map name to version - .collect(Collectors.toMap(a -> a.getArtifactName(), a -> a.getArtifactVersion())); - } - - private Either createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component origComponent, ComponentInstance componentInstance, String userId, - ComponentOperation containerOperation, boolean inTransaction) { + private Either createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) { Either resultOp; - boolean nameAlreadyExist = true; - String resourceInNumber = ""; - String containerComponentId = containerComponent.getUniqueId(); - ComponentTypeEnum containerComponentType = containerComponent.getComponentType(); - NodeTypeEnum containerNodeType = containerComponentType.getNodeType(); - NodeTypeEnum compInstNodeType = getNodeTypeOfComponentInstanceOrigin(); - while (nameAlreadyExist) { - - Either eitherNameLogic = handleNameLogic(origComponent, componentInstance, containerComponent.getComponentType(), containerComponent.getUniqueId(), true, inTransaction); - if (eitherNameLogic.isRight()) { - return Either.right(eitherNameLogic.right().value()); - } else { - resourceInNumber = eitherNameLogic.left().value(); - } - - Either isNameExistStatus = componentInstanceOperation.isComponentInstanceNameExist(containerComponentId, containerNodeType, null, componentInstance.getNormalizedName()); - if (isNameExistStatus.isRight()) { - log.debug("Failed to check if component instance name exists for container component {}", containerComponentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND, componentInstance.getName(), containerComponentId)); - return resultOp; - } - nameAlreadyExist = isNameExistStatus.left().value(); - - } - - Either result = componentInstanceOperation.createComponentInstance(containerComponentId, containerNodeType, resourceInNumber, componentInstance, compInstNodeType, inTransaction); + Either, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user); if (result.isRight()) { log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName()); @@ -439,17 +286,23 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } log.debug("Entity on graph is created."); - ComponentInstance compInst = result.left().value(); - - Map existingEnvVersions = getExistingEnvVersions(componentInstance); - Either addComponentInstanceArtifacts = addComponentInstanceArtifacts(containerComponent, compInst, userId, inTransaction, existingEnvVersions); + Component updatedComponent = result.left().value().getLeft(); + Map existingEnvVersions = new HashMap<>(); + //TODO existingEnvVersions ?? + Either addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions); if (addComponentInstanceArtifacts.isRight()) { log.debug("Failed to create component instance {}", componentInstance.getName()); resultOp = Either.right(addComponentInstanceArtifacts.right().value()); return resultOp; } - resultOp = Either.left(compInst); + Optional updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst(); + if (!updatedInstanceOptional.isPresent()) { + log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName()); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); + return resultOp; + } + resultOp = Either.left(updatedInstanceOptional.get()); return resultOp; } @@ -459,14 +312,15 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { * @param componentInstance * @param userId * @param existingEnvVersions + * TODO * @param containerComponentId * * @return */ - protected Either addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, String userId, boolean inTransaction, + protected Either addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user, Map existingEnvVersions) { log.debug("add artifacts to resource instance"); - + List filteredGroups = null; ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance); if (!ActionStatus.OK.equals(status)) { ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null); @@ -478,10 +332,11 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (componentDeploymentArtifacts == null) { return Either.left(ActionStatus.OK); } - Map finalDeploymentArtifacts = new HashMap(componentDeploymentArtifacts); + Map finalDeploymentArtifacts = new HashMap(); + + Map> groupInstancesArtifacts = new HashMap<>(); + for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) { - // if (artifact.getArtifactType().equalsIgnoreCase( - // ArtifactTypeEnum.HEAT.getType())) { String type = artifact.getArtifactType(); if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) { @@ -489,92 +344,65 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } if (artifact.checkEsIdExist()) { - Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); - if (deploymentResourceArtifacts == null) { - log.debug("no deployment artifacts are configured for resource instance"); - break; - } - Map placeHolderData = (Map) deploymentResourceArtifacts.get(HEAT_ENV_NAME); - - String envLabel = (artifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase(); - Either createArtifactPlaceHolder = artifactBusinessLogic.createArtifactPlaceHolderInfo(componentInstance.getUniqueId(), envLabel, placeHolderData, userId, ArtifactGroupTypeEnum.DEPLOYMENT, - inTransaction); - if (createArtifactPlaceHolder.isRight()) { - return Either.right(createArtifactPlaceHolder.right().value()); + Either createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, + componentInstance.getName(), user, containerComponent, existingEnvVersions); + if (createHeatEnvPlaceHolder.isRight()) { + return Either.right(createHeatEnvPlaceHolder.right().value()); } - ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value(); - - artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis()); - artifactHeatEnv.setTimeout(0); - buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData); - - // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow - handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions); - Either addHeatEnvArtifact = artifactBusinessLogic.addHeatEnvArtifact(artifactHeatEnv, artifact, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true); - if (addHeatEnvArtifact.isRight()) { - log.debug("failed to create heat env artifact on resource instance"); - return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null)); + ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value(); + + //put heat + finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact); + + //put env + finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition); + + if(CollectionUtils.isNotEmpty(originComponent.getGroups())){ + filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList()); } - - ArtifactDefinition artifactDefinition = addHeatEnvArtifact.left().value(); - if (artifact.getHeatParameters() != null) { - List heatEnvParameters = new ArrayList(); - for (HeatParameterDefinition parameter : artifact.getHeatParameters()) { - HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter); - heatEnvParameter.setDefaultValue(parameter.getCurrentValue()); - heatEnvParameters.add(heatEnvParameter); + if (CollectionUtils.isNotEmpty(filteredGroups)) { + for (GroupDefinition groupInstance : filteredGroups) { + Optional op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny(); + if (op.isPresent()) { + List artifactsUid; + if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) { + artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId()); + } else { + artifactsUid = new ArrayList<>(); + } + artifactsUid.add(artifactDefinition); + groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid); + break; + } } - artifactDefinition.setHeatParameters(heatEnvParameters); - } - finalDeploymentArtifacts.put(envLabel, artifactDefinition); - // audit - EnumMap artifactAuditingFields = artifactBusinessLogic.createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.getUniqueId()); - artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentInstance.getName()); - handleAuditing(AuditingActionEnum.ARTIFACT_UPLOAD, containerComponent, userId, artifactAuditingFields, inTransaction); + } } - // } } - componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts); - return Either.left(ActionStatus.OK); - } - - private void handleAuditing(AuditingActionEnum artifactUpload, org.openecomp.sdc.be.model.Component containerComponent, String userId, EnumMap artifactAuditingFields, boolean inTransaction) { - - Either user = userAdmin.getUser(userId, inTransaction); - if (user.isRight()) { - log.debug("failed to get user properties from graph for audit"); - return; + StorageOperationStatus artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts); + if ( artStatus != StorageOperationStatus.OK){ + log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus); + return Either.left(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)); + } - - componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user.left().value(), containerComponent, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, ComponentTypeEnum.RESOURCE_INSTANCE, artifactAuditingFields); - - } - - private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map existingEnvVersions) { - if (null != existingEnvVersions) { - String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName()); - if (null != prevVersion) { - heatEnvArtifact.setArtifactVersion(prevVersion); - } + StorageOperationStatus result = toscaOperationFacade + .addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts); + if (result != StorageOperationStatus.OK) { + log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId()); + return Either.left(componentsUtils.convertFromStorageResponse(result)); } - } - - private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map placeHolderData) { - String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName()); - String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION); - String fileName = heatArtifact.getArtifactName().replaceAll("." + heatExtension, "." + envExtension); - heatEnvArtifact.setArtifactName(fileName); + componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts); + return Either.left(ActionStatus.OK); } private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) { - Either, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT); + Either, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null); Map deploymentArtifacts = new HashMap(); if (getResourceDeploymentArtifacts.isRight()) { StorageOperationStatus status = getResourceDeploymentArtifacts.right().value(); if (!status.equals(StorageOperationStatus.NOT_FOUND)) { - log.debug("Failed to fetch resource artifacts. status is {}", status); + log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status); return componentsUtils.convertFromStorageResponseForResourceInstance(status, true); } } else { @@ -595,11 +423,11 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return ActionStatus.OK; } - public Either updateComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) { - return updateComponentInstance(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true); + public Either updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) { + return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true); } - public Either updateComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction, + public Either updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction, boolean needLock, boolean createNewTransaction) { Either resp = validateUserExists(userId, "update Component Instance", inTransaction); @@ -616,7 +444,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, inTransaction, createNewTransaction); + Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); if (validateComponentExists.isRight()) { return Either.right(validateComponentExists.right().value()); } @@ -627,28 +455,24 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return Either.right(validateCanWorkOnComponent.right().value()); } ComponentTypeEnum instanceType = getComponentType(containerComponentType); - Either validateParentStatus = componentInstanceOperation.validateParent(containerComponentId, componentInstanceId, inTransaction); + Either validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid()); if (validateParentStatus.isRight()) { log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId); resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase())); return resultOp; } - Boolean isPrentValid = validateParentStatus.left().value(); - if (!isPrentValid) { + if (!validateParentStatus.left().value()) { resultOp = Either.right( componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId)); return resultOp; - } if (needLock) { - Either lockComponent = lockComponent(containerComponent, "updateComponentInstance"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } } - try { Either eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, inTransaction); @@ -659,7 +483,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } Component origComponent = eitherResourceName.left().value(); - resultOp = updateComponentInstance(containerComponentId, containerComponentType, origComponent, componentInstanceId, componentInstance, inTransaction); + resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance, inTransaction); return resultOp; } finally { @@ -690,6 +514,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { ComponentParametersView componentFilter = new ComponentParametersView(); componentFilter.disableAll(); componentFilter.setIgnoreUsers(false); + componentFilter.setIgnoreComponentInstances(false); Either validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter, true); if (validateComponentExists.isRight()) { return Either.right(validateComponentExists.right().value()); @@ -705,14 +530,8 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { ComponentTypeEnum instanceType = getComponentType(containerComponentType); for (ComponentInstance componentInstance : componentInstanceList) { - Either validateParentStatus = componentInstanceOperation.validateParent(containerComponentId, componentInstance.getUniqueId(), true); - if (validateParentStatus.isRight()) { - log.debug("Failed to get component instance {} on service {}", componentInstance.getUniqueId(), containerComponentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase())); - return resultOp; - } - Boolean isPrentValid = validateParentStatus.left().value(); - if (!isPrentValid) { + boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId()); + if (!validateParent) { resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId)); return resultOp; @@ -728,23 +547,46 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } List updatedList = new ArrayList<>(); - for (ComponentInstance componentInstance : componentInstanceList) { - - Either eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, true); - - if (eitherResourceName.isRight()) { - resultOp = Either.right(eitherResourceName.right().value()); - return resultOp; + List instancesFromContainerComponent = containerComponent.getComponentInstances(); + List listForUpdate = new ArrayList<>(); + if(instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty()) + containerComponent.setComponentInstances(componentInstanceList); + else{ + Iterator iterator = instancesFromContainerComponent.iterator(); + while(iterator.hasNext()){ + ComponentInstance origInst = iterator.next(); + Optional op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny(); + if(op.isPresent()){ + ComponentInstance updatedCi = op.get(); + Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName()); + if(!isUniqueName){ + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", + origInst.getName(), updatedCi.getName()); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName())); + return resultOp; + } + + listForUpdate.add(updatedCi); + } + else + listForUpdate.add(origInst); } - Component origComponent = eitherResourceName.left().value(); - - Either resultSingleUpdate = updateComponentInstance(containerComponentId, containerComponentType, origComponent, componentInstance.getUniqueId(), componentInstance, true); - - if (resultSingleUpdate.isRight()) { - resultOp = Either.right(resultSingleUpdate.right().value()); - return resultOp; + containerComponent.setComponentInstances(listForUpdate); + + if(resultOp == null){ + Either updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); + if(updateStatus.isRight()){ + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null)); + return resultOp; + } + for(ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()){ + Optional op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny(); + if(op.isPresent()){ + updatedList.add(updatedInstance); + } + } } - updatedList.add(resultSingleUpdate.left().value()); } resultOp = Either.left(updatedList); @@ -757,6 +599,10 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } + private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) { + return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId)); + } + private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) { if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) { return ComponentTypeEnum.SERVICE_INSTANCE; @@ -765,78 +611,56 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - public Either updateComponentInstance(String containerComponentParam, org.openecomp.sdc.be.model.Component containerComponent, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId, - ComponentInstance componentInstance, boolean needLock, boolean inTransaction) { - Either resultOp = null; - Either validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - if (needLock) { + private Either updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId, + ComponentInstance componentInstance, boolean inTransaction) { - Either lockComponent = lockComponent(containerComponent, "updateComponentInstance"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); + Either resultOp = null; + Optional componentInstanceOptional = null; + Either, StorageOperationStatus> updateRes = null; + + if (resultOp == null) { + componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst(); + if (!componentInstanceOptional.isPresent()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName()); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); } } - - try { - - resultOp = updateComponentInstance(containerComponent.getUniqueId(), containerComponentType, origComponent, componentInstanceId, componentInstance, inTransaction); - return resultOp; - - } finally { - if (needLock) - unlockComponent(resultOp, containerComponent); - } - - } - - private Either updateComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId, - ComponentInstance componentInstance, boolean inTransaction) { - Either resultOp; - - Either eitherNameLogic = handleNameLogic(origComponent, componentInstance, containerComponentType, containerComponentId, false, inTransaction); - if (eitherNameLogic.isRight()) { - return Either.right(eitherNameLogic.right().value()); + if (resultOp == null) { + ComponentInstance oldComponentInstance = componentInstanceOptional.get(); + String newInstanceName = componentInstance.getName(); + Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName); + if (!isUniqueName) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", oldComponentInstance.getName(), newInstanceName); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName())); + } } - NodeTypeEnum containerNodeType = containerComponentType.getNodeType(); - - Either isNameExistStatus = componentInstanceOperation.isComponentInstanceNameExist(containerComponentId, containerNodeType, componentInstanceId, componentInstance.getNormalizedName()); - if (isNameExistStatus.isRight()) { - log.debug("Failed to get resource instance names for service {}", containerComponentId); - - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND, componentInstance.getName(), containerComponentId)); - return resultOp; + if (resultOp == null) { + updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, componentInstance); + if (updateRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(), + updateRes.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null)); + } } - Boolean isNameExist = isNameExistStatus.left().value(); - if (isNameExist) { - containerComponentType = getComponentTypeOfComponentInstance(); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName())); - return resultOp; + if (resultOp == null) { + String newInstanceId = updateRes.left().value().getRight(); + Optional updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst(); + if (!updatedInstanceOptional.isPresent()) { + log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName()); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); + }else{ + resultOp = Either.left(updatedInstanceOptional.get()); + } + } - - log.debug("Try to update entry on graph"); - Either result = componentInstanceOperation.updateResourceInstance(containerComponentId, containerNodeType, componentInstanceId, componentInstance, inTransaction); - - if (result.isLeft()) { - log.debug("Enty on graph is updated."); - ComponentInstance resResourceInfo = result.left().value(); - resultOp = Either.left(resResourceInfo); - return resultOp; - - } else { - log.debug("Failed to update entry on graph for resource instance {}", componentInstance.getName()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), false), "", componentInstance.getName())); - return resultOp; + if (resultOp == null) { + resultOp = Either.left(componentInstanceOptional.get()); } - + return resultOp; } - public Either deleteComponentInstance(String containerComponentParam, String containerComponentId, String resourceInstanceId, String userId) { + public Either deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) { Either resp = validateUserExists(userId, "delete Component Instance", false); if (resp.isRight()) { @@ -849,7 +673,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, false, true); + Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); if (validateComponentExists.isRight()) { return Either.right(validateComponentExists.right().value()); } @@ -865,13 +689,13 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } // validate resource /* - * if (!ComponentValidationUtils.canWorkOnComponent(containerComponentId, serviceOperation, userId)) { log.info( "Restricted operation for user {} on service {}", userId, containerComponentId); return Either.right(componentsUtils + * if (!ComponentValidationUtils.canWorkOnComponent(containerComponentId, serviceOperation, userId)) { log.info( "Restricted operation for user " + userId + " on service " + containerComponentId); return Either.right(componentsUtils * .getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } // lock resource StorageOperationStatus lockStatus = graphLockOperation.lockComponent( containerComponentId, NodeTypeEnum.Service); if (lockStatus != StorageOperationStatus.OK) { - * log.debug("Failed to lock service {}", containerComponentId); resultOp = Either.right(componentsUtils .getResponseFormat(componentsUtils .convertFromStorageResponse(lockStatus))); return resultOp; } + * log.debug("Failed to lock service {}", containerComponentId); resultOp = Either.right(componentsUtils .getResponseFormat(componentsUtils .convertFromStorageResponse(lockStatus))); return resultOp; } */ Either resultOp = null; try { - resultOp = deleteComponentInstance(containerComponentId, resourceInstanceId, containerComponentType); + resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); return resultOp; } finally { @@ -882,37 +706,51 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - private Either deleteComponentInstance(String containerComponentId, String resourceInstanceId, ComponentTypeEnum containerComponentType) { - Either resultOp; - NodeTypeEnum containerNodeType = containerComponentType.getNodeType(); - Either result = componentInstanceOperation.deleteComponentInstance(containerNodeType, containerComponentId, resourceInstanceId, true); + private Either deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) { - if (result.isRight()) { - log.debug("Failed to delete entry on graph for resourceInstance {}", resourceInstanceId); - ActionStatus status = componentsUtils.convertFromStorageResponse(result.right().value(), containerComponentType); - // TODO check - /* - * if (ActionStatus.SERVICE_NOT_FOUND.equals(status)) { resultOp = Either .right(componentsUtils .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND)); } else { - */ - resultOp = Either.right(componentsUtils.getResponseFormat(status, resourceInstanceId)); - // } - return resultOp; + Either resultOp = null; + ComponentInstance deletedInstance = null; + Either, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId); + + if (deleteRes.isRight()) { + log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId); + ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType); + resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId)); + } + if (resultOp == null) { + log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent); + deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent); + resultOp = Either.left(deletedInstance); + } + if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) { + List groupsToUpdate = new ArrayList<>(); + for(GroupDataDefinition currGroup : containerComponent.getGroups()){ + if(currGroup.getMembers().containsKey(deletedInstance.getName())){ + currGroup.getMembers().remove(deletedInstance.getName()); + groupsToUpdate.add(currGroup); + } + } + Either, StorageOperationStatus> updateGroupsRes = + toscaOperationFacade.updateGroupsOnComponent(containerComponent, containerComponent.getComponentType(), groupsToUpdate); + if (updateGroupsRes.isRight()) { + log.debug("Failed to delete component instance {} from group members. ", componentInstanceId); + ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType); + resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId)); + } } - ComponentInstance resResourceInfo = result.left().value(); - resultOp = Either.left(resResourceInfo); - - log.debug("Entry on graph is deleted. Exist more connections on this artifact."); + return resultOp; + } - Map deploymentArtifacts = resResourceInfo.getDeploymentArtifacts(); - if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) { - StorageOperationStatus deleteArtifactsIfNotOnGraph = artifactBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(new ArrayList(deploymentArtifacts.values())); - if (!deleteArtifactsIfNotOnGraph.equals(StorageOperationStatus.OK)) { - log.debug("failed to delete artifact payload. status={}", deleteArtifactsIfNotOnGraph.name()); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value()), resourceInstanceId)); + private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) { + ComponentInstance foundInstance = null; + for(ComponentInstance instance : containerComponent.getComponentInstances()){ + if(instance.getUniqueId().equals(componentInstanceId)){ + foundInstance = instance; + containerComponent.getComponentInstances().remove(instance); + break; } - } - return resultOp; + return foundInstance; } public Either associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) { @@ -929,7 +767,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Either resultOp = null; - Either validateComponentExists = validateComponentExists(componentId, componentTypeEnum, inTransaction, createNewTransaction); + Either validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); if (validateComponentExists.isRight()) { return Either.right(validateComponentExists.right().value()); } @@ -949,7 +787,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { try { - resultOp = associateRIToRIOnGraph(componentId, requirementDef, componentTypeEnum, inTransaction); + resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction); return resultOp; @@ -959,12 +797,12 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - public Either associateRIToRIOnGraph(String componentId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) { + public Either associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) { log.debug("Try to create entry on graph"); Either resultOp = null; - Either result = componentInstanceOperation.associateResourceInstances(componentId, componentTypeEnum.getNodeType(), requirementDef, inTransaction); + Either result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef); if (result.isLeft()) { log.debug("Enty on graph is created."); @@ -973,11 +811,11 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return resultOp; } else { - log.debug("Failed to associate node {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode()); + log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode()); String fromNameOrId = ""; String toNameOrId = ""; - Either fromResult = componentInstanceOperation.getResourceInstanceById(requirementDef.getFromNode()); - Either toResult = componentInstanceOperation.getResourceInstanceById(requirementDef.getToNode()); + Either fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode()); + Either toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode()); toNameOrId = requirementDef.getFromNode(); fromNameOrId = requirementDef.getFromNode(); @@ -1002,7 +840,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } Either resultOp = null; - Either validateComponentExists = validateComponentExists(componentId, componentTypeEnum, false, true); + Either validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); if (validateComponentExists.isRight()) { return Either.right(validateComponentExists.right().value()); } @@ -1019,7 +857,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } try { log.debug("Try to create entry on graph"); - Either result = componentInstanceOperation.dissociateResourceInstances(componentId, componentTypeEnum.getNodeType(), requirementDef, true); + Either result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef); if (result.isLeft()) { log.debug("Enty on graph is created."); RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value(); @@ -1028,11 +866,11 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } else { - log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode()); + log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode()); String fromNameOrId = ""; String toNameOrId = ""; - Either fromResult = componentInstanceOperation.getResourceInstanceById(requirementDef.getFromNode()); - Either toResult = componentInstanceOperation.getResourceInstanceById(requirementDef.getToNode()); + Either fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode()); + Either toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode()); toNameOrId = requirementDef.getFromNode(); fromNameOrId = requirementDef.getFromNode(); @@ -1072,26 +910,6 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return result; } - private Either updateInputValue(ComponentInstanceInput input, String resourceInstanceId) { - Either eitherInput = componentInstanceOperation.updateInputValueInResourceInstance(input, resourceInstanceId, true); - Either result; - if (eitherInput.isLeft()) { - log.debug("Input value {} was updated on graph.", input.getValueUniqueUid()); - ComponentInstanceInput instanceInput = eitherInput.left().value(); - - result = Either.left(instanceInput); - - } else { - log.debug("Failed to update input value {} in resource instance {}", input, resourceInstanceId); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherInput.right().value()); - - result = Either.right(componentsUtils.getResponseFormat(actionStatus, "")); - - } - return result; - } - private Either createAttributeValue(ComponentInstanceAttribute attribute, String resourceInstanceId) { Either result; @@ -1161,15 +979,39 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { finally { if (result == null || result.isRight()) { - titanGenericDao.rollback(); + titanDao.rollback(); } else { - titanGenericDao.commit(); + titanDao.commit(); } // unlock resource graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); } } + // US833308 VLI in service - specific network_role property value logic + private StorageOperationStatus concatServiceNameToVLINetworkRolePropertyValue(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property) { + if (StringUtils.isNotEmpty(property.getValue()) && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName()) && ComponentTypeEnum.SERVICE == componentTypeEnum) { + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreComponentInstances(false); + Either getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView); + if (getServiceResult.isRight()) { + return getServiceResult.right().value(); + } + Component service = getServiceResult.left().value(); + Optional getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny(); + if (!getInstance.isPresent()) { + return StorageOperationStatus.NOT_FOUND; + } + String prefix = service.getSystemName() + "."; + String value = property.getValue(); + if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) { + property.setValue(prefix + value); + } + } + return StorageOperationStatus.OK; + } + public Either createOrUpdatePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property, String userId) { Either resultOp = null; @@ -1184,11 +1026,264 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); return resultOp; } + Either getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll); + + if (getResourceResult.isRight()) { + log.debug("Failed to retrieve component, component id {}", componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + Component containerComponent = getResourceResult.left().value(); + + if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { + log.info("Restricted operation for user: {} on service {}", userId, componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + Either resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId); + if (resourceInstanceStatus.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId)); + return resultOp; + } + ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); + // specific property value logic US833308 + StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertyValue(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, property); + if (StorageOperationStatus.OK != fetchByIdsStatus) { + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus))); + return resultOp; + } + // lock resource + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock service {}", componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + return resultOp; + } + String innerType = null; + String propertyType = property.getType(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = property.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + innerType = propDef.getType(); + } + // Specific Update Logic + Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + } + Either isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value()); + + String newValue = property.getValue(); + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (res == false) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + + ImmutablePair pair = propertyOperation.validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes.left().value(), true); + if (pair.getRight() != null && pair.getRight() == false) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + } + + + + try { + List instanceProperties = containerComponent.getComponentInstancesProperties().get(resourceInstanceId); + Optional instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); + StorageOperationStatus status; + instanceProperty.get().setValue(newValue); + if(instanceProperty.isPresent()){ + status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property); + } else { + status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property); + } + if(status != StorageOperationStatus.OK){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + return resultOp; + } + foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); + Either updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); + + if (updateContainerRes.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + return resultOp; + } + resultOp = Either.left(property); + return resultOp; + + } finally { + if (resultOp == null || resultOp.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + + } + + public Either createOrUpdateInstanceInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput property, String userId) { + + Either resultOp = null; + + Either resp = validateUserExists(userId, "create Or Update Property Value", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + return resultOp; + } + Either getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll); + + if (getResourceResult.isRight()) { + log.debug("Failed to retrieve component, component id {}", componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + Component containerComponent = getResourceResult.left().value(); + + if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { + log.info("Restricted operation for user: {} on service {}", userId, componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + Either resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId); + if (resourceInstanceStatus.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId)); + return resultOp; + } + + ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); + + // lock resource + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock service {}", componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + return resultOp; + } + String innerType = null; + String propertyType = property.getType(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = property.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + innerType = propDef.getType(); + } + // Specific Update Logic + Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + } + Either isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value()); + + String newValue = property.getValue(); + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (res == false) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + + try { + List instanceProperties = containerComponent.getComponentInstancesInputs().get(resourceInstanceId); + Optional instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); + StorageOperationStatus status; + if(instanceProperty.isPresent()){ + instanceProperty.get().setValue(property.getValue()); + status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property); + } else { + status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property); + } + if(status != StorageOperationStatus.OK){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + return resultOp; + } + foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); + Either updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); + + if (updateContainerRes.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + return resultOp; + } + resultOp = Either.left(property); + return resultOp; + + } finally { + if (resultOp == null || resultOp.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + + } + + public Either createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property, + String userId) { + + Either resultOp = null; - IComponentOperation componentOperation = getIComponentOperation(componentTypeEnum); + Either resp = validateUserExists(userId, "create Or Update Property Value", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } - if (!ComponentValidationUtils.canWorkOnComponent(componentId, componentOperation, userId)) { - log.info("Restricted operation for user {} on service {}", userId, componentId); + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + return resultOp; + } + + if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) { + log.info("Restricted operation for user: {} on service: {}", userId, componentId); resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); return resultOp; } @@ -1201,63 +1296,67 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } try { String propertyValueUid = property.getValueUniqueUid(); + if (propertyValueUid == null) { - Either counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.PROPERTY_COUNTER, true); + Either counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId); if (counterRes.isRight()) { - log.debug("increaseAndGetResourcePropertyCounter failed resource instance {} property {}", resourceInstanceId, property); + log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property); StorageOperationStatus status = counterRes.right().value(); ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus)); } Integer index = counterRes.left().value(); - Either result = componentInstanceOperation.addPropertyValueToResourceInstance(property, resourceInstanceId, index, true); + Either result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true); if (result.isLeft()) { - log.debug("Property value was added to resource instance {}", resourceInstanceId); + log.trace("Property value was added to resource instance {}", resourceInstanceId); ComponentInstanceProperty instanceProperty = result.left().value(); resultOp = Either.left(instanceProperty); - return resultOp; } else { - log.debug("Failed to add property value {} to resource instance {}", property, resourceInstanceId); - // TODO: esofer add error + log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId); ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - - return resultOp; } } else { - Either result = componentInstanceOperation.updatePropertyValueInResourceInstance(property, resourceInstanceId, true); + Either result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true); if (result.isLeft()) { log.debug("Property value {} was updated on graph.", property.getValueUniqueUid()); ComponentInstanceProperty instanceProperty = result.left().value(); resultOp = Either.left(instanceProperty); - return resultOp; } else { - log.debug("Failed to update property value {} in resource instance {}", property, resourceInstanceId); + log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId); ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + } + } + if (resultOp.isLeft()) { + StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId); + if (updateCustomizationUUID != StorageOperationStatus.OK) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - return resultOp; } } + return resultOp; } finally { if (resultOp == null || resultOp.isRight()) { - titanGenericDao.rollback(); + titanDao.rollback(); } else { - titanGenericDao.commit(); + titanDao.commit(); } // unlock resource graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); @@ -1280,10 +1379,8 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return resultOp; } - IComponentOperation componentOperation = getIComponentOperation(componentTypeEnum); - - if (!ComponentValidationUtils.canWorkOnComponent(componentId, componentOperation, userId)) { - log.info("Restricted operation for user {} on service {}", userId, componentId); + if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) { + log.info("Restricted operation for user: {} on service: {}", userId, componentId); resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); return resultOp; } @@ -1318,7 +1415,6 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } else { log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId); - // TODO: esofer add error ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); @@ -1338,7 +1434,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return resultOp; } else { - log.debug("Failed to update property value {} in reosurce instance {}", inputProperty, resourceInstanceId); + log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId); ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); @@ -1350,9 +1446,9 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } finally { if (resultOp == null || resultOp.isRight()) { - titanGenericDao.rollback(); + titanDao.rollback(); } else { - titanGenericDao.commit(); + titanDao.commit(); } // unlock resource graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); @@ -1375,9 +1471,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return resultOp; } - IComponentOperation componentOperation = getIComponentOperation(componentTypeEnum); - - if (!ComponentValidationUtils.canWorkOnComponent(serviceId, componentOperation, userId)) { + if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) { log.info("Restricted operation for user {} on service {}", userId, serviceId); resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); return resultOp; @@ -1411,9 +1505,9 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } finally { if (resultOp == null || resultOp.isRight()) { - titanGenericDao.rollback(); + titanDao.rollback(); } else { - titanGenericDao.commit(); + titanDao.commit(); } // unlock resource graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType()); @@ -1421,60 +1515,32 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } - private Either validateComponentInstanceName(String resourceInstanceName, ComponentInstance resourceInstance, boolean isCreate) { - ComponentTypeEnum containerComponentType = getComponentTypeOfComponentInstance(); - if (!isCreate) { - if (resourceInstanceName == null) - return Either.left(true); - } - - if (!ValidationUtils.validateStringNotEmpty(resourceInstanceName)) { - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, containerComponentType.getValue()); - - return Either.right(errorResponse); - } - resourceInstance.setNormalizedName(ValidationUtils.normaliseComponentInstanceName(resourceInstanceName)); - if (!isCreate) { - if (!ValidationUtils.validateResourceInstanceNameLength(resourceInstanceName)) { - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, containerComponentType.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - - return Either.right(errorResponse); - } - if (!ValidationUtils.validateResourceInstanceName(resourceInstanceName)) { - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME, containerComponentType.getValue()); - - return Either.right(errorResponse); - } - } - - return Either.left(true); - - } - - private Either validateComponentInstanceParentState(ComponentTypeEnum containerComponentType, ComponentInstance resourceInstance) { - String componentId = resourceInstance.getComponentUid(); - Either eitherResourceResponse = Either.right(StorageOperationStatus.GENERAL_ERROR); - + private Either getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) { + + Either eitherResponse = null; ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType); - ComponentOperation componentOperation = getComponentOperation(componentType); - if (componentOperation != null) - eitherResourceResponse = componentOperation.getComponent(componentId, true); - - Component component = null; - ResponseFormat errorResponse = null; - if (eitherResourceResponse.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(eitherResourceResponse.right().value(), componentType); + Component component; + ResponseFormat errorResponse; + Either getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid()); + if (getComponentRes.isRight()) { + log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName()); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType); errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); - return Either.right(errorResponse); + eitherResponse = Either.right(errorResponse); + } + if(eitherResponse == null) { + component = getComponentRes.left().value(); + LifecycleStateEnum resourceCurrState = component.getLifecycleState(); + if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { + ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE; + errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString()); + eitherResponse = Either.right(errorResponse); + } } - component = eitherResourceResponse.left().value(); - LifecycleStateEnum resourceCurrState = component.getLifecycleState(); - if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { - ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE; - errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString()); - return Either.right(errorResponse); + if(eitherResponse == null) { + eitherResponse = Either.left(getComponentRes.left().value()); } - return Either.left(true); + return eitherResponse; } public Either changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) { @@ -1484,6 +1550,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return Either.right(resp.right().value()); } + User user = resp.left().value(); Either resultOp = null; Either validateComponentType = validateComponentType(containerComponentParam); @@ -1492,9 +1559,8 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - final ComponentOperation containerOperation = getComponentOperation(containerComponentType); - Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, false, true); + Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); if (validateComponentExists.isRight()) { return Either.right(validateComponentExists.right().value()); } @@ -1505,25 +1571,12 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return Either.right(validateCanWorkOnComponent.right().value()); } - Either validateParentStatus = componentInstanceOperation.validateParent(containerComponentId, componentInstanceId, false); - if (validateParentStatus.isRight()) { - log.debug("Failed to get resource instance {} on service {}", componentInstanceId, containerComponentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, componentInstanceId)); - return resultOp; - } - Boolean isPrentValid = validateParentStatus.left().value(); - if (!isPrentValid) { + Either resourceInstanceStatus = getResourceInstanceById(containerComponent,componentInstanceId); + if (resourceInstanceStatus.isRight()) { resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId)); return resultOp; - } - Either resourceInstanceStatus = componentInstanceOperation.getResourceInstanceById(componentInstanceId); - if (resourceInstanceStatus.isRight()) { - log.debug("Failed to get resource instance {} on service {}", componentInstanceId, containerComponentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, componentInstanceId)); - return resultOp; - } ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value(); Either lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion"); @@ -1538,43 +1591,24 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } String resourceId = newComponentInstance.getComponentUid(); - if (!getCompInstOriginComponentOperation().isComponentExist(resourceId)) { - log.debug("resource {} not found.", resourceId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + Either componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId); + if(componentExistsRes.isRight()){ + log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId)); return resultOp; } - - // esofer - before deleting component instance, we should keep the - // groups which holds this instance - List groupsToRevert = new ArrayList<>(); - Either, StorageOperationStatus> associatedGroups = groupOperation.getAssociatedGroupsToComponentInstance(componentInstanceId, true); - if (associatedGroups.isRight()) { - StorageOperationStatus status = associatedGroups.right().value(); - if (status != StorageOperationStatus.OK) { - BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to getch groups of current component instance", ErrorSeverity.ERROR); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return resultOp; - } - } else { - List groups = associatedGroups.left().value(); - groupsToRevert.addAll(groups); - } - // rbetzer - before deleting component instance, retrieve env artifacts to keep track of artifactVersion - - Either, StorageOperationStatus> retrieveEnvArtifacts = componentInstanceOperation.fetchCIEnvArtifacts(componentInstanceId); - if (retrieveEnvArtifacts.isLeft()) - newComponentInstance.setDeploymentArtifacts(retrieveEnvArtifacts.left().value()); - else if (retrieveEnvArtifacts.right().value() != StorageOperationStatus.OK) { - log.debug("falied to fetch instance deployment artifacts {}", componentInstanceId ); + else if (!componentExistsRes.left().value()) { + log.debug("The resource {} not found ", resourceId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); + return resultOp; } - resultOp = deleteComponentInstance(containerComponentId, componentInstanceId, containerComponentType); + List groupInstances = currentResourceInstance.getGroupInstances(); + Map deploymentArtifacts = currentResourceInstance.getDeploymentArtifacts(); + resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); if (resultOp.isRight()) { - log.debug("failed to delete resource instance {}", resourceId); - return resultOp; - } Either eitherResourceName = getOriginComponentNameFromComponentInstance(newComponentInstance, true); @@ -1592,41 +1626,53 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { newComponentInstance.setPosY(resResourceInfo.getPosY()); newComponentInstance.setDescription(resResourceInfo.getDescription()); - resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, userId, containerOperation, true); + resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user); if (resultOp.isRight()) { - log.debug("failed to create resource instance {}", resourceId); - return resultOp; - } - newComponentInstance = resultOp.left().value(); - newComponentInstance.setName(resResourceInfo.getName()); - resultOp = updateComponentInstance(containerComponentId, containerComponentType, origComponent, newComponentInstance.getUniqueId(), newComponentInstance, true); - ComponentInstance updatedComponentInstance = resultOp.left().value(); if (resultOp.isRight()) { log.debug("failed to create resource instance {}", resourceId); return resultOp; } - if (false == groupsToRevert.isEmpty()) { - StorageOperationStatus associatedGroupsToComponentInstance = groupOperation.associateGroupsToComponentInstance(groupsToRevert, updatedComponentInstance.getUniqueId(), updatedComponentInstance.getName(), true); - if (associatedGroupsToComponentInstance != StorageOperationStatus.OK) { + if (CollectionUtils.isNotEmpty(groupInstances)) { + StorageOperationStatus addGroupsToComponentInstance = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, updatedComponentInstance, groupInstances); + if (addGroupsToComponentInstance != StorageOperationStatus.OK) { + BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to associate groups to new component instance", ErrorSeverity.ERROR); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + return resultOp; + } + } + if (MapUtils.isNotEmpty(deploymentArtifacts)) { + StorageOperationStatus addDeploymentArtifactsToComponentInstance = toscaOperationFacade.addDeploymentArtifactsToComponentInstance(containerComponent, updatedComponentInstance, deploymentArtifacts); + if (addDeploymentArtifactsToComponentInstance != StorageOperationStatus.OK) { BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to associate groups to new component instance", ErrorSeverity.ERROR); resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return resultOp; } } - Either fullResourceInstance = componentInstanceOperation.getFullComponentInstance(resultOp.left().value(), getNodeTypeOfComponentInstanceOrigin()); - if (fullResourceInstance.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fullResourceInstance.right().value()), resourceId)); + + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreComponentInstances(false); + Either updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter); + if (updatedComponentRes.isRight()) { + StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); + log.debug("Component with id {} was not found", containerComponentId); + return Either.right(responseFormat); + } + resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(),updatedComponentInstance.getUniqueId()); + if (resourceInstanceStatus.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId())); return resultOp; } - resultOp = Either.left(fullResourceInstance.left().value()); + resultOp = Either.left(resourceInstanceStatus.left().value()); return resultOp; } finally { @@ -1640,9 +1686,48 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { protected abstract ComponentTypeEnum getComponentTypeOfComponentInstance(); - protected abstract ComponentOperation getContainerComponentOperation(); + // US831698 + public Either, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) { + final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id"; + Component containerComponent = null; + + Either, ResponseFormat> resultOp = null; + try { + Either validateUserExists = validateUserExists(userId, ECOMP_ERROR_CONTEXT, false); + if (validateUserExists.isRight()) { + resultOp = Either.right(validateUserExists.right().value()); + return resultOp; + } - protected abstract ComponentOperation getCompInstOriginComponentOperation(); + Either validateComponentType = validateComponentType(containerComponentTypeParam); + if (validateComponentType.isRight()) { + resultOp = Either.right(validateComponentType.right().value()); + return resultOp; + } + + Either validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId); + if (validateContainerComponentExists.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()))); + return resultOp; + } + containerComponent = validateContainerComponentExists.left().value(); + + Either resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); + if (resourceInstanceStatus.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); + return resultOp; + } + + List instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId); + if(CollectionUtils.isEmpty(instanceProperties)){ + instanceProperties = new ArrayList<>(); + } + resultOp = Either.left(instanceProperties); + return resultOp; + } finally { + unlockComponent(resultOp, containerComponent); + } + } protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper instaceCounterWrapper, Wrapper errorWrapper) { Either counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true); @@ -1658,4 +1743,75 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } + /** + * updates componentInstance modificationTime + * + * @param componentInstance + * @param componentInstanceType + * @param modificationTime + * @param inTransaction + * @return + */ + public Either updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) { + Either result; + Either updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime, + inTransaction); + if (updateComponentInstanceRes.isRight()) { + log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value()))); + } else { + result = Either.left(updateComponentInstanceRes.left().value()); + } + return result; + } + + private Boolean validateInstanceNameUniqueness(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) { + Boolean isUnique = true; + String newInstanceNormalizedName = ValidationUtils.normalizeComponentInstanceName(newInstanceName); + if (!oldComponentInstance.getNormalizedName().equals(newInstanceNormalizedName)) { + Optional foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(newInstanceNormalizedName)).findFirst(); + if (foundComponentInstance.isPresent()) { + isUnique = false; + } + if (isUnique) { + foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().endsWith(newInstanceNormalizedName)).findFirst(); + if (foundComponentInstance.isPresent()) { + isUnique = false; + } + } + } + return isUnique; + } + + private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) { + Boolean isUnique = true; + String newInstanceNormalizedName = ValidationUtils.normalizeComponentInstanceName(newInstanceName); + if (!oldComponentInstance.getNormalizedName().equals(newInstanceNormalizedName)) { + Optional foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(newInstanceNormalizedName)).findFirst(); + if (foundComponentInstance.isPresent()) { + isUnique = false; + } + } + return isUnique; + } + + private Either getResourceInstanceById(Component containerComponent, String instanceId) { + + Either result = null; + List instances = containerComponent.getComponentInstances(); + Optional foundInstance = null; + if(CollectionUtils.isEmpty(instances)){ + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + if(result == null){ + foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); + if(!foundInstance.isPresent()){ + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + if(result == null){ + result = Either.left(foundInstance.get()); + } + return result; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java index 6cebc7dd53..e8c04c22c1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java @@ -110,6 +110,9 @@ public class CompositionBusinessLogic { case VFC: offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; break; + case VFCMT: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; + break; default: offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; break; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java index 226225a07c..9c5cefb24c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java @@ -87,7 +87,7 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic { if (!lockResult.equals(StorageOperationStatus.OK)) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, "createConsumer"); BeEcompErrorManager.getInstance().logBeFailedLockObjectError("createConsumer", NodeTypeEnum.ConsumerCredentials.getName(), consumerName); - log.debug("Failed to lock consumer {} error - {}", consumerName, lockResult); + log.debug("Failed to lock consumer: {} error - {}", consumerName, lockResult); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); @@ -123,7 +123,7 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic { private Either validateUser(User user, ConsumerDefinition consumer, AuditingActionEnum auditAction) { if (user.getUserId() == null || user.getUserId().trim().isEmpty()) { - log.debug("createEcompUser method - user is missing. userId={}", user.getUserId()); + log.debug("createEcompUser method - user is missing. userId= {}", user.getUserId()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); log.debug("audit before sending response"); componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user); @@ -132,7 +132,7 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic { log.debug("get user from DB"); Either eitherCreator = userAdmin.getUser(user.getUserId(), false); if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - log.debug("createEcompUser method - user is not listed. userId={}", user.getUserId()); + log.debug("createEcompUser method - user is not listed. userId= {}", user.getUserId()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS); log.debug("audit before sending response"); componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java index badb257a80..ae6237897a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java @@ -22,16 +22,20 @@ package org.openecomp.sdc.be.components.impl; import java.io.ByteArrayInputStream; import java.io.IOException; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Collectors; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.tosca.CsarUtils; import org.openecomp.sdc.common.util.GeneralUtility; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; @@ -55,22 +59,74 @@ public class CsarValidationUtils { public static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions"; - public final static String[] TOSCA_METADATA_FIELDS = { TOSCA_META_FILE_VERSION, CSAR_VERSION, CREATED_BY, TOSCA_META_ENTRY_DEFINITIONS }; + private static final String[] TOSCA_METADATA_FIELDS = { TOSCA_META_FILE_VERSION, CSAR_VERSION, CREATED_BY, TOSCA_META_ENTRY_DEFINITIONS }; public final static String ARTIFACTS_METADATA_FILE = "HEAT.meta"; - public final static String ARTIFACTS = "Artifacts/"; - public static final String TOSCA_CSAR_EXTENSION = ".csar"; - +/** + * Validates Csar + * @param csar + * @param csarUUID + * @param componentsUtils + * @return + */ public static Either validateCsar(Map csar, String csarUUID, ComponentsUtils componentsUtils) { Either validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils); if (validateStatus.isRight()) { return Either.right(validateStatus.right().value()); } + + removeNonUniqueArtifactsFromCsar(csar); + log.trace("TOSCA-Metadata/TOSCA.meta file found, CSAR id {}", csarUUID); - return validateTOSCAMetadataFile(csar, csarUUID, componentsUtils); + validateStatus = validateTOSCAMetadataFile(csar, csarUUID, componentsUtils); + if (validateStatus.isRight()) { + return Either.right(validateStatus.right().value()); + } + return Either.left(true); + } + + private static void removeNonUniqueArtifactsFromCsar(Map csar) { + + List nonUniqueArtifactsToRemove = new ArrayList<>(); + String[] paths = csar.keySet().toArray(new String[csar.keySet().size()]); + int numberOfArtifacts = paths.length; + for(int i = 0; i < numberOfArtifacts; ++i ){ + collectNonUniqueArtifact(paths, i, numberOfArtifacts, nonUniqueArtifactsToRemove); + } + nonUniqueArtifactsToRemove.stream().forEach(path->csar.remove(path)); + } + + private static void collectNonUniqueArtifact( String[] paths, int currInd, int numberOfArtifacts, List nonUniqueArtifactsToRemove) { + + String[] parsedPath = paths[currInd].split("/"); + String[] otherParsedPath; + int artifactNameInd = parsedPath.length - 1; + for(int j = currInd + 1; j < numberOfArtifacts; ++j ){ + otherParsedPath = paths[j].split("/"); + if(parsedPath.length == otherParsedPath.length && parsedPath.length > 3 && isEqualArtifactNames(parsedPath, otherParsedPath)){ + log.error("Can't upload two artifact with the same name {}. The artifact with path {} will be handled, and the artifact with path {} will be ignored. ", + parsedPath[artifactNameInd], paths[currInd], paths[j]); + nonUniqueArtifactsToRemove.add(paths[j]); + } + } + } + private static boolean isEqualArtifactNames(String[] parsedPath, String[] otherParsedPath) { + boolean isEqualArtifactNames = false; + int artifactNameInd = parsedPath.length - 1; + int artifactGroupTypeInd = parsedPath.length - 3; + String groupType = parsedPath[artifactGroupTypeInd]; + String artifactName = parsedPath[artifactNameInd]; + String otherGroupType = otherParsedPath[artifactGroupTypeInd]; + String otherArtifactName = otherParsedPath[artifactNameInd]; + String vfcToscaName = parsedPath.length == 5 ? parsedPath[1] : null; + + if(artifactName.equalsIgnoreCase(otherArtifactName) && groupType.equalsIgnoreCase(otherGroupType)){ + isEqualArtifactNames = vfcToscaName == null ? true : vfcToscaName.equalsIgnoreCase(otherParsedPath[1]); + } + return isEqualArtifactNames; } public static Either, ResponseFormat> getToscaYaml(Map csar, String csarUUID, ComponentsUtils componentsUtils) { @@ -83,7 +139,7 @@ public class CsarValidationUtils { try { props.load(new ByteArrayInputStream(toscaMetaBytes)); } catch (IOException e) { - log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); + log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e); BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); } @@ -110,39 +166,39 @@ public class CsarValidationUtils { } public static Either, ResponseFormat> getArtifactsMeta(Map csar, String csarUUID, ComponentsUtils componentsUtils) { - - if (!csar.containsKey(ARTIFACTS + ARTIFACTS_METADATA_FILE)) { + + if( !csar.containsKey(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE) ) { log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID); BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, ARTIFACTS_METADATA_FILE)); } log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", ARTIFACTS_METADATA_FILE, csarUUID); - byte[] artifactsMetaBytes = csar.get(ARTIFACTS + ARTIFACTS_METADATA_FILE); + byte[] artifactsMetaBytes = csar.get(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE); if (artifactsMetaBytes == null) { - log.debug("Entry-Definitions {} file not found in csar, csar ID {}", ARTIFACTS + ARTIFACTS_METADATA_FILE, csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + ARTIFACTS + ARTIFACTS_METADATA_FILE + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, ARTIFACTS + ARTIFACTS_METADATA_FILE)); + log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, ARTIFACTS_METADATA_FILE, csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE)); } String artifactsFileContents = new String(artifactsMetaBytes); - return Either.left(new ImmutablePair(ARTIFACTS + ARTIFACTS_METADATA_FILE, artifactsFileContents)); + return Either.left(new ImmutablePair(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE, artifactsFileContents)); } - public static Either, ResponseFormat> getArtifactsContent(String csarUUID, Map csar, String artifactName, ComponentsUtils componentsUtils) { - if (!csar.containsKey(ARTIFACTS + artifactName)) { + public static Either, ResponseFormat> getArtifactsContent(String csarUUID, Map csar, String artifactPath, String artifactName, ComponentsUtils componentsUtils) { + if (!csar.containsKey(artifactPath)) { log.debug("Entry-Definitions entry not found in Artifacts/HEAT.meta file, csar ID {}", csarUUID); BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, ARTIFACTS + artifactName, csarUUID)); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, CsarUtils.ARTIFACTS_PATH + artifactName, csarUUID)); } - log.trace("Found Entry-Definitions property in Artifacts/HEAT.meta, Entry-Definitions: {}, CSAR id: {}", ARTIFACTS + artifactName, csarUUID); - byte[] artifactFileBytes = csar.get(ARTIFACTS + artifactName); + log.trace("Found Entry-Definitions property in Artifacts/HEAT.meta, Entry-Definitions: {}, CSAR id: {}", artifactPath, csarUUID); + byte[] artifactFileBytes = csar.get(artifactPath); if (artifactFileBytes == null) { - log.debug("Entry-Definitions {} file not found in csar, csar ID {}", ARTIFACTS + artifactName, csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + ARTIFACTS + artifactName + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, ARTIFACTS + artifactName, csarUUID)); + log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, artifactName, csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + artifactPath + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, artifactPath, csarUUID)); } return Either.left(new ImmutablePair(artifactName, artifactFileBytes)); @@ -182,7 +238,7 @@ public class CsarValidationUtils { try { props.load(new ByteArrayInputStream(splited[index].getBytes())); } catch (IOException e) { - log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); + log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e); BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java index 5ebb86f1ba..958adc0eef 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java @@ -29,17 +29,27 @@ import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; +import java.util.stream.Collectors; +import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum; import org.openecomp.sdc.be.datamodel.utils.NodeTypeConvertUtils; +import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ArtifactType; import org.openecomp.sdc.be.model.Component; @@ -48,6 +58,7 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Product; import org.openecomp.sdc.be.model.PropertyScope; import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.ResourceMetadataDefinition; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.Tag; import org.openecomp.sdc.be.model.User; @@ -56,15 +67,25 @@ import org.openecomp.sdc.be.model.category.GroupingDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.ComponentOperation; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.resources.data.ComponentMetadataData; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.be.resources.data.ServiceMetadataData; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.category.CategoryData; +import org.openecomp.sdc.be.resources.data.category.SubCategoryData; +import org.openecomp.sdc.be.ui.model.UiCategories; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.thinkaurelius.titan.core.TitanGraph; + import fj.data.Either; @org.springframework.stereotype.Component("elementsBusinessLogic") @@ -198,10 +219,8 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } private Either>, ResponseFormat> handleFollowedCertifiedServices(Set distStatus) { - Map propertiesToMatch = new HashMap<>(); - propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); - Either, StorageOperationStatus> services = serviceOperation.getCertifiedServicesWithDistStatus(propertiesToMatch, distStatus, false); + Either, StorageOperationStatus> services = toscaOperationFacade.getCertifiedServicesWithDistStatus(distStatus); if (services.isLeft()) { Map> result = new HashMap>(); List list = new ArrayList<>(); @@ -216,43 +235,37 @@ public class ElementBusinessLogic extends BaseBusinessLogic { private Either>, ResponseFormat> handleTester(String userId) { Set lifecycleStates = new HashSet(); lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either, StorageOperationStatus> resources = resourceOperation.getTesterFollowed(userId, lifecycleStates, false); - - if (resources.isLeft()) { - Either, StorageOperationStatus> services = serviceOperation.getTesterFollowed(userId, lifecycleStates, false); - if (services.isLeft()) { - Map> result = new HashMap>(); - result.put("services", services.left().value()); - result.put("resources", resources.left().value()); - return Either.left(result); - } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value()))); - } - } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resources.right().value()))); - } + lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); + Either>, ResponseFormat> result = getFollowedResourcesAndServices(null, lifecycleStates, null); + + return result; } private Either>, ResponseFormat> getFollowedResourcesAndServices(String userId, Set lifecycleStates, Set lastStateStates) { - Either, StorageOperationStatus> resources = resourceOperation.getFollowed(userId, lifecycleStates, lastStateStates, false); - - if (resources.isLeft()) { - Either, StorageOperationStatus> services = serviceOperation.getFollowed(userId, lifecycleStates, lastStateStates, false); - if (services.isLeft()) { - Map> result = new HashMap>(); - result.put("services", services.left().value()); - result.put("resources", resources.left().value()); - return Either.left(result); + + try { + Either, StorageOperationStatus> resources = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.RESOURCE); + + if (resources.isLeft()) { + Either, StorageOperationStatus> services = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.SERVICE); + if (services.isLeft()) { + Map> result = new HashMap>(); + result.put("services", services.left().value()); + result.put("resources", resources.left().value()); + return Either.left(result); + } else { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value()))); + } } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value()))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resources.right().value()))); } - } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resources.right().value()))); + } finally { + titanDao.commit(); } } private Either>, ResponseFormat> getFollowedProducts(String userId, Set lifecycleStates, Set lastStateStates) { - Either, StorageOperationStatus> products = productOperation.getFollowed(userId, lifecycleStates, lastStateStates, false); + Either, StorageOperationStatus> products = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.PRODUCT); if (products.isLeft()) { Map> result = new HashMap>(); result.put("products", products.left().value()); @@ -393,10 +406,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic { String origSubCategoryName = subCategoryName; User user = new User(); - /* - * if (userId == null) { user.setUserId("UNKNOWN"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, - * auditingAction, componentType); return Either.right(responseFormat); } - */ Either validateUser = validateUserExists(userId, "createSubCategory", false); if (validateUser.isRight()) { log.debug("Validation of user failed, userId {}", userId); @@ -720,6 +729,49 @@ public class ElementBusinessLogic extends BaseBusinessLogic { componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); return Either.left(categories); } + + public Either getAllCategories(String userId) { + AuditingActionEnum auditingAction = AuditingActionEnum.GET_CATEGORY_HIERARCHY; + ResponseFormat responseFormat; + UiCategories categories = new UiCategories(); + + Either userResponse = validateUserExists(userId, "get all categories", false); + + if (userResponse.isRight()) { + return Either.right(userResponse.right().value()); + } + User user = userResponse.left().value(); + + //GET resource categories + Either, ActionStatus> getResourceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, false); + if (getResourceCategoriesByType.isRight()) { + responseFormat = componentsUtils.getResponseFormat(getResourceCategoriesByType.right().value()); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.RESOURCE.getValue(), responseFormat); + return Either.right(responseFormat); + } + categories.setResourceCategories(getResourceCategoriesByType.left().value()); + + //GET service categories + Either, ActionStatus> getServiceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ServiceNewCategory, false); + if (getServiceCategoriesByType.isRight()) { + responseFormat = componentsUtils.getResponseFormat(getServiceCategoriesByType.right().value()); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.SERVICE.getValue(), responseFormat); + return Either.right(responseFormat); + } + categories.setServiceCategories(getServiceCategoriesByType.left().value()); + + //GET product categories + Either, ActionStatus> getProductCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ProductCategory, false); + if (getProductCategoriesByType.isRight()) { + responseFormat = componentsUtils.getResponseFormat(getProductCategoriesByType.right().value()); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.PRODUCT.getValue(), responseFormat); + return Either.right(responseFormat); + } + + categories.setProductCategories(getProductCategoriesByType.left().value()); + return Either.left(categories); + + } public Either deleteCategory(String categoryId, String componentTypeParamName, String userId) { @@ -800,7 +852,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { // validate user exists if (userId == null) { - log.debug("User id is null"); + log.debug("UserId is null"); return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION)); } @@ -938,19 +990,17 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } Map> resMap = new HashMap<>(); - Either, StorageOperationStatus> resResources = resourceOperation.getResourceCatalogData(false); + Either, StorageOperationStatus> resResources = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.RESOURCE); if (resResources.isLeft()) { - Either, StorageOperationStatus> resServices = serviceOperation.getServiceCatalogData(false); + Either, StorageOperationStatus> resServices = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.SERVICE); if (resServices.isLeft()) { - Either, StorageOperationStatus> resProducts = productOperation.getProductCatalogData(false); - if (resProducts.isLeft()) { - resMap.put("resources", resResources.left().value()); - resMap.put("services", resServices.left().value()); - resMap.put("products", resProducts.left().value()); - return Either.left(resMap); - } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resProducts.right().value()))); - } + // Either, StorageOperationStatus> resProducts = productOperation.getProductCatalogData(false); + // if (resProducts.isLeft()) { + resMap.put("resources", resResources.left().value()); + resMap.put("services", resServices.left().value()); + resMap.put("products", new ArrayList<>()); + + return Either.left(resMap); } else { return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resServices.right().value()))); } @@ -971,11 +1021,14 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } if (filters == null || filters.isEmpty()) { - return getCatalogComponentsByAssetType(assetTypeEnum); + Either, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum); + if(componentsList.isRight()) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentsList.right().value()))); + } + return Either.left(componentsList.left().value()); } - ComponentOperation componentOperation = getComponentOperation(assetTypeEnum); - Either, StorageOperationStatus> result = componentOperation.getFilteredComponents(filters, false); + Either, StorageOperationStatus> result = getFilteredComponents(filters, assetTypeEnum, false); if (result.isRight()) {// category hierarchy mismatch or // category/subCategory/distributionStatus not @@ -990,46 +1043,51 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return Either.left(result.left().value()); } - public Either, ResponseFormat> getCatalogComponentsByAssetType(ComponentTypeEnum assetTypeEnum) { + private Either, StorageOperationStatus> getFilteredComponents(Map filters, ComponentTypeEnum assetType, boolean inTransaction) { + Either, StorageOperationStatus> assetResult = null; + if(assetType == ComponentTypeEnum.RESOURCE){ + + assetResult = getFilteredResouces(filters, inTransaction); + + } else if (assetType == ComponentTypeEnum.SERVICE){ + + assetResult = getFilteredServices(filters, inTransaction); + } + return assetResult; + } - if (assetTypeEnum == null) { - log.debug("getCatalogComponentsByAssetType: Corresponding ComponentTypeEnum not found"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } + private Either, StorageOperationStatus> getFilteredServices(Map filters, boolean inTransaction) { + + Either, StorageOperationStatus> components = null; - switch (assetTypeEnum) { - case RESOURCE: + String categoryName = filters.get(FilterKeyEnum.CATEGORY); + String distributionStatus = filters.get(FilterKeyEnum.DISTRIBUTION_STATUS); + DistributionStatusEnum distEnum = DistributionStatusEnum.findState(distributionStatus); + if (distributionStatus != null && distEnum == null) { + filters.remove(FilterKeyEnum.CATEGORY); + return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); + } - Either, StorageOperationStatus> resourceCatalogData = resourceOperation.getResourceCatalogDataVFLatestCertifiedAndNonCertified(false); - if (resourceCatalogData.isLeft()) { - log.debug("getCatalogComponentsByAssetType: Resource fetching successful"); - return Either.left(resourceCatalogData.left().value()); - } else { - log.debug("getCatalogComponentsByAssetType: Resource fetching failed"); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceCatalogData.right().value()))); + if (categoryName != null) { // primary filter + components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(), NodeTypeEnum.Service, inTransaction, ServiceMetadataData.class, null); + if (components.isLeft() && distEnum != null) {// secondary filter + Predicate statusFilter = p -> ((Service) p).getDistributionStatus().equals(distEnum); + return Either.left(components.left().value().stream().filter(statusFilter).collect(Collectors.toList())); } + filters.remove(FilterKeyEnum.DISTRIBUTION_STATUS); + return components; + } - case SERVICE: - Either, StorageOperationStatus> serviceCatalogData = serviceOperation.getServiceCatalogDataLatestCertifiedAndNotCertified(false); - if (serviceCatalogData.isLeft()) { - log.debug("getCatalogComponentsByAssetType: Service fetching successful"); - return Either.left(serviceCatalogData.left().value()); - } else { - log.debug("getCatalogComponentsByAssetType: Service fetching failed"); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceCatalogData.right().value()))); - } - /* - * case PRODUCT: Either, StorageOperationStatus> resCatalogData = productOperation.getProductCatalogData(false); if(resCatalogData.isLeft()){ log. debug("getCatalogComponentsByAssetType: Product fetching successful" ); - * return Either.left(resCatalogData.left().value()); }else { log. debug("getCatalogComponentsByAssetType: Product fetching failed" ); return Either.right(componentsUtils .getResponseFormat(componentsUtils.convertFromStorageResponse( - * resCatalogData.right().value()))); } - */ - default: - log.debug("Invalid Asset Type"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + Set distStatusSet = new HashSet<>(); + distStatusSet.add(distEnum); + Either, StorageOperationStatus> servicesWithDistStatus = toscaOperationFacade.getServicesWithDistStatus(distStatusSet, null); + if (servicesWithDistStatus.isRight()) { // not found == empty list + return Either.left(new ArrayList<>()); } + + return Either.left((List)servicesWithDistStatus.left().value()); } - // TODO new story Tal public Either, ResponseFormat> getCatalogComponentsByUuidAndAssetType(String assetType, String uuid) { if (assetType == null || assetType == null) { @@ -1044,40 +1102,15 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); } - switch (assetTypeEnum) { - - case RESOURCE: - Either, StorageOperationStatus> resourceListByUuid = resourceOperation.getLatestResourceByUuid(uuid, false); - - if (resourceListByUuid.isLeft()) { - log.debug("getCatalogComponentsByUuidAndAssetType: Resource fetching successful"); - return Either.left(resourceListByUuid.left().value()); - } - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(resourceListByUuid.right().value()); - log.debug("getCatalogComponentsByUuidAndAssetType: Resource fetching failed"); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - - case SERVICE: - Either, StorageOperationStatus> serviceCatalogData = serviceOperation.getLatestServiceByUuid(uuid, false); - - if (serviceCatalogData.isLeft()) { - log.debug("getCatalogComponentsByUuidAndAssetType: Service fetching successful"); - return Either.left(serviceCatalogData.left().value()); - } - + Either, StorageOperationStatus> componentsListByUuid = toscaOperationFacade.getComponentListByUuid(uuid, null); + if(componentsListByUuid.isRight()) { log.debug("getCatalogComponentsByUuidAndAssetType: Service fetching failed"); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceCatalogData.right().value()))); - // case Product is for future US - /* - * case PRODUCT: Either, StorageOperationStatus> resCatalogData = productOperation.getProductCatalogData(false); if(resCatalogData.isLeft()){ log. debug("getCatalogComponentsByAssetType: Product fetching successful" ); return - * Either.left(resCatalogData.left().value()); }else { log. debug("getCatalogComponentsByAssetType: Product fetching failed" ); return Either.right(componentsUtils .getResponseFormat(componentsUtils.convertFromStorageResponse( - * resCatalogData.right().value()))); } - */ - default: - log.debug("Invalid Asset Type"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(componentsListByUuid.right().value(), ComponentTypeEnum.SERVICE); + return Either.right(componentsUtils.getResponseFormat(actionStatus, uuid)); } + + log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + "Service fetching successful"); + return Either.left(componentsListByUuid.left().value()); } public List getAllComponentTypesParamNames() { @@ -1121,5 +1154,228 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } return params; } + + public Either, StorageOperationStatus> getFilteredResouces(Map filters, boolean inTransaction) { + + String subCategoryName = filters.get(FilterKeyEnum.SUB_CATEGORY); + String categoryName = filters.get(FilterKeyEnum.CATEGORY); + ResourceTypeEnum resourceType = ResourceTypeEnum.getType( filters.get(FilterKeyEnum.RESOURCE_TYPE)); + Either>, StorageOperationStatus> subcategories = null; + Optional> subCategoryData; + + if (categoryName != null) { + subcategories = getAllSubCategories(categoryName); + if (subcategories.isRight()) { + filters.remove(FilterKeyEnum.SUB_CATEGORY); + return Either.right(subcategories.right().value()); + } + } + if (subCategoryName != null) { // primary filter + if (categoryName != null) { + subCategoryData = validateCategoryHierarcy(subcategories.left().value(), subCategoryName); + if (!subCategoryData.isPresent()) { + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + return fetchByCategoryOrSubCategoryUid((String) subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, + ResourceMetadataData.class, resourceType); + } + + return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, ResourceMetadataData.class, resourceType); + } + if(subcategories != null){ + return fetchByMainCategory(subcategories.left().value(), inTransaction, resourceType); + } + return fetchByResourceType(filters.get(FilterKeyEnum.RESOURCE_TYPE), inTransaction); + } + + private Either>, StorageOperationStatus> getAllSubCategories(String categoryName) { + Either categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class); + if (categoryResult.isRight()) { + return Either.right(categoryResult.right().value()); + } + CategoryData categoryData = categoryResult.left().value(); + + Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(), + GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class); + if (childrenNodes.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenNodes.right().value())); + } + return Either.left(childrenNodes.left().value()); + } + + private Optional> validateCategoryHierarcy(List> childNodes, String subCategoryName) { + Predicate> matchName = p -> p.getLeft().getSubCategoryDataDefinition().getName().equals(subCategoryName); + return childNodes.stream().filter(matchName).findAny(); + } + + protected Either, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction, + Class clazz, ResourceTypeEnum resourceType) { + try { + Either graph = titanDao.getGraph(); + if (graph.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); + + } + return collectComponents(graph.left().value(), neededType, categoryUid, categoryType, clazz, resourceType); + + } finally { + if (false == inTransaction) { + titanDao.commit(); + } + } + } + + protected Either, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction, + Class clazz, ResourceTypeEnum resourceType) { + List components = new ArrayList<>(); + try { + Class categoryClazz = categoryType == NodeTypeEnum.ServiceNewCategory ? CategoryData.class : SubCategoryData.class; + Map props = new HashMap(); + props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); + Either, TitanOperationStatus> getCategory = titanGenericDao.getByCriteria(categoryType, props, categoryClazz); + if (getCategory.isRight()) { + return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); + } + Either graph = titanDao.getGraph(); + if (graph.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); + + } + for (GraphNode category : getCategory.left().value()) { + Either, StorageOperationStatus> result = collectComponents(graph.left().value(), neededType, (String) category.getUniqueId(), categoryType, clazz, resourceType); + if (result.isRight()) { + return result; + } + components.addAll(result.left().value()); + } + + return Either.left(components); + } finally { + if (false == inTransaction) { + titanDao.commit(); + } + } + } + + private Either, StorageOperationStatus> collectComponents(TitanGraph graph, NodeTypeEnum neededType, String categoryUid, NodeTypeEnum categoryType, Class clazz, ResourceTypeEnum resourceType) { + List components = new ArrayList<>(); + Either>, TitanOperationStatus> parentNodes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(categoryType), categoryUid, GraphEdgeLabels.CATEGORY, neededType, clazz); + if (parentNodes.isLeft()) { + for (ImmutablePair component : parentNodes.left().value()) { + ComponentMetadataDataDefinition componentData = component.getLeft().getMetadataDataDefinition(); + Boolean isHighest = componentData.isHighestVersion(); + boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, componentData); + + if (isHighest && isMatchingResourceType) { + Either result = (Either) toscaOperationFacade.getToscaElement(componentData.getUniqueId(), JsonParseFlagEnum.ParseMetadata); + if (result.isRight()) { + return Either.right(result.right().value()); + } + components.add(result.left().value()); + } + } + } + return Either.left(components); + } + + private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType, + ComponentMetadataDataDefinition componentData) { + + boolean isMatching; + if (componentType == NodeTypeEnum.Resource) { + if (resourceType == null) { + isMatching = true; + } else { + isMatching = resourceType == ((ResourceMetadataDataDefinition)componentData).getResourceType(); + } + } else { + isMatching = true; + } + return isMatching; + } + + private Either, StorageOperationStatus> fetchByMainCategory(List> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) { + List components = new ArrayList<>(); + + for (ImmutablePair subCategory : subcategories) { + Either, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid((String) subCategory.getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, + inTransaction, ResourceMetadataData.class, resourceType); + if (fetched.isRight()) { + // return fetched; + continue; + } + components.addAll(fetched.left().value()); + } + return Either.left(components); + } + + private Either, StorageOperationStatus> fetchByResourceType(String resourceType, boolean inTransaction) { + List components = null; + StorageOperationStatus status; + Wrapper statusWrapper = new Wrapper<>(); + Either, StorageOperationStatus> result; + try { + + Either, StorageOperationStatus> getResources = toscaOperationFacade.fetchByResourceType(resourceType); //titanGenericDao.getByCriteria(nodeType, props, clazz); + if (getResources.isRight()) { + status = getResources.right().value(); + if(status != StorageOperationStatus.NOT_FOUND){ + statusWrapper.setInnerElement(getResources.right().value()); + }else{ + components = new ArrayList<>(); + } + } else{ + components = getResources.left().value(); + } + if(!statusWrapper.isEmpty()){ + result = Either.right(statusWrapper.getInnerElement()); + }else{ + result = Either.left(components); + } + return result; + } finally { + if (!inTransaction) { + titanDao.commit(); + } + } + } + + Component convertComponentMetadataDataToComponent(ComponentMetadataData componentMetadataData) { + return convertResourceDataToResource((ResourceMetadataData) componentMetadataData); + } + private Resource convertResourceDataToResource(ResourceMetadataData resourceData) { + + ResourceMetadataDefinition resourceMetadataDataDefinition = new ResourceMetadataDefinition((ResourceMetadataDataDefinition) resourceData.getMetadataDataDefinition()); + + Resource resource = new Resource(resourceMetadataDataDefinition); + + return resource; + } + private Either, StorageOperationStatus> fetchByDistributionStatus(String status, boolean inTransaction) { + Map props = new HashMap(); + props.put(GraphPropertiesDictionary.DISTRIBUTION_STATUS.getProperty(), status); + props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); + return (Either, StorageOperationStatus>) (Either) getServiceListByCriteria(props, inTransaction); + } + + private Either, StorageOperationStatus> getServiceListByCriteria(Map props, boolean inTransaction) { + props.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName()); + Either, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class); + + if (byCriteria.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value())); + } + List services = new ArrayList(); + List servicesDataList = byCriteria.left().value(); + for (ServiceMetadataData data : servicesDataList) { + Either service = toscaOperationFacade.getToscaElement(data.getMetadataDataDefinition().getUniqueId()); + if (service.isLeft()) { + services.add((Service)service.left().value()); + } else { + log.debug("Failed to fetch resource for name = {} and id = {}",data.getMetadataDataDefinition().getName(),data.getUniqueId()); + } + } + return Either.left(services); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java index 3b4528d3a3..ba08f11928 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java @@ -20,9 +20,11 @@ package org.openecomp.sdc.be.components.impl; +import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -34,11 +36,21 @@ import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.math.NumberUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.codehaus.jackson.JsonGenerationException; +import org.codehaus.jackson.map.JsonMappingException; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.info.ArtifactDefinitionInfo; @@ -48,29 +60,42 @@ import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupInstance; +import org.openecomp.sdc.be.model.GroupInstanceProperty; import org.openecomp.sdc.be.model.GroupProperty; import org.openecomp.sdc.be.model.GroupTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition.GroupInstancePropertyValueUpdateBehavior; +import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames; +import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; +import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations; +import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.ComponentOperation; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.GroupOperation; import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonSyntaxException; import fj.data.Either; @org.springframework.stereotype.Component("groupBusinessLogic") public class GroupBusinessLogic extends BaseBusinessLogic { + private static String ADDING_GROUP = "AddingGroup"; - public static String INITIAL_VERSION = "1"; + public static final String INITIAL_VERSION = "1"; private static final String CREATE_GROUP = "CreateGroup"; @@ -87,8 +112,15 @@ public class GroupBusinessLogic extends BaseBusinessLogic { @javax.annotation.Resource private GroupTypeOperation groupTypeOperation; - @javax.annotation.Resource - private GroupOperation groupOperation; + + @Autowired + ArtifactsOperations artifactsOperation; + + @Autowired + private GroupsOperation groupsOperation; + @Autowired + private ApplicationDataTypeCache dataTypeCache; + /** * @@ -113,7 +145,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - public Either createGroup(String componentId, String userId, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) { + /*public Either createGroup(String componentId, String userId, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) { Either result = null; @@ -142,7 +174,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false); - Either validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView, userId, null, user); + Either validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); @@ -164,16 +196,16 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); - titanGenericDao.commit(); + titanDao.commit(); } } } - } + }*/ private String getComponentTypeForResponse(org.openecomp.sdc.be.model.Component component) { String componentTypeForResponse = "SERVICE"; @@ -203,7 +235,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } List currentArtifacts = deploymentArtifacts.values().stream().map(p -> p.getUniqueId()).collect(Collectors.toList()); - log.debug("The deployment artifacts of component {} are {}", component.getNormalizedName(), deploymentArtifacts); + log.debug("The deployment artifacts of component {} are {}" , component.getNormalizedName(), deploymentArtifacts); if (false == currentArtifacts.containsAll(artifacts)) { BeEcompErrorManager.getInstance().logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO); return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); @@ -213,43 +245,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } - /** - * Verify that the artifact members belongs to the component - * - * @param component - * @param artifacts - * @return - */ - private Either, ResponseFormat> getArtifactsBelongsToComponent(Component component, List artifacts, String context) { - - /* - * if (artifacts == null || true == artifacts.isEmpty()) { return Either.left(true); } - */ - - Map deploymentArtifacts = component.getDeploymentArtifacts(); - if (deploymentArtifacts == null || true == deploymentArtifacts.isEmpty()) { - BeEcompErrorManager.getInstance().logInvalidInputError(context, "No deployment artifact found under component " + component.getNormalizedName(), ErrorSeverity.INFO); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - List resultList = new ArrayList(); - - for (String artifactId : artifacts) { - Optional groupArtifactOp = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny(); - - if (groupArtifactOp.isPresent()) { - ArtifactDefinition groupArtifact = groupArtifactOp.get(); - resultList.add(groupArtifact); - } else { - BeEcompErrorManager.getInstance().logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - - } - } - - return Either.left(resultList); - - } - /** * verify that the members are component instances of the component * @@ -290,67 +285,54 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } } - ComponentOperation componentOperation = getComponentOperationByParentComponentType(componentType); - if (componentOperation instanceof ResourceOperation) { - ResourceOperation resourceOperation = (ResourceOperation) componentOperation; - - for (Entry groupMember : groupMembers.entrySet()) { - - String componentInstName = groupMember.getKey(); - String componentInstUid = groupMember.getValue(); - - ComponentInstance componentInstance = compInstUidToCompInstMap.get(componentInstUid); - String componentUid = componentInstance.getComponentUid(); - List componentToscaNames = new ArrayList<>(); - TitanOperationStatus status = resourceOperation.fillResourceDerivedListFromGraph(componentUid, componentToscaNames); - if (status != TitanOperationStatus.OK) { - BeEcompErrorManager.getInstance().logInternalFlowError(CREATE_GROUP, "Cannot find tosca list of component id " + componentUid, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - log.debug("The tosca names of component id {} are {}", componentUid, memberToscaTypes); - - boolean found = false; - for (String memberToscaType : memberToscaTypes) { - if (componentToscaNames.contains(memberToscaType)) { - found = true; - break; - } - } - if (found == false) { - BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, - "No tosca types from " + memberToscaTypes + " can be found in the tosca list " + componentToscaNames + " of component " + componentInstance.getNormalizedName(), ErrorSeverity.INFO); - /* - * # %1 - member name # %2 - group name # %3 - group type - */ - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, componentInstName, groupName, groupType)); - } else { - log.debug("Component instance {} fits to one of the required tosca types", componentInstance.getNormalizedName()); - } - } - } else { - BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Cannot find tosca list since it is not supported for product", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } +// ComponentOperation componentOperation = getComponentOperationByParentComponentType(componentType); +// if (componentOperation instanceof ResourceOperation) { +// ResourceOperation resourceOperation = (ResourceOperation) componentOperation; +// +// for (Entry groupMember : groupMembers.entrySet()) { +// +// String componentInstName = groupMember.getKey(); +// String componentInstUid = groupMember.getValue(); +// +// ComponentInstance componentInstance = compInstUidToCompInstMap.get(componentInstUid); +// String componentUid = componentInstance.getComponentUid(); +// List componentToscaNames = new ArrayList<>(); +// TitanOperationStatus status = resourceOperation.fillResourceDerivedListFromGraph(componentUid, componentToscaNames); +// if (status != TitanOperationStatus.OK) { +// BeEcompErrorManager.getInstance().logInternalFlowError(CREATE_GROUP, "Cannot find tosca list of component id " + componentUid, ErrorSeverity.ERROR); +// return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); +// } +// +// log.debug("The tosca names of component id {} are {}", componentUid, memberToscaTypes); +// +// boolean found = false; +// for (String memberToscaType : memberToscaTypes) { +// if (componentToscaNames.contains(memberToscaType)) { +// found = true; +// break; +// } +// } +// if (found == false) { +// BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, +// "No tosca types from " + memberToscaTypes + " can be found in the tosca list " + componentToscaNames + " of component " + componentInstance.getNormalizedName(), ErrorSeverity.INFO); +// /* +// * # %1 - member name # %2 - group name # %3 - group type +// */ +// return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, componentInstName, groupName, groupType)); +// } else { +// log.debug("Component instance {} fits to one of the required tosca types", componentInstance.getNormalizedName()); +// } +// } +// } else { +// BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Cannot find tosca list since it is not supported for product", ErrorSeverity.ERROR); +// return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); +// } } return Either.left(true); } - public ComponentOperation getComponentOperation(NodeTypeEnum componentType) { - - switch (componentType) { - case Service: - case ResourceInstance: - return serviceOperation; - case Resource: - return resourceOperation; - default: - return null; - } - } - /** * Update specific group version * @@ -358,7 +340,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - public Either updateGroupVersion(GroupDefinition groupDefinition, boolean inTransaction) { + /*public Either updateGroupVersion(GroupDefinition groupDefinition, boolean inTransaction) { Either result = null; List groupIdsToUpdateVersion = new ArrayList<>(); groupIdsToUpdateVersion.add(groupDefinition.getUniqueId()); @@ -370,7 +352,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic { result = Either.right(updateGroupVersion.right().value()); } return result; - } + }*/ + + /** * Update list of groups versions @@ -379,7 +363,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - public Either, StorageOperationStatus> updateGroupVersion(List groupsUniqueId, boolean inTransaction) { + /*public Either, StorageOperationStatus> updateGroupVersion(List groupsUniqueId, boolean inTransaction) { Either, StorageOperationStatus> result = null; @@ -395,85 +379,388 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); - titanGenericDao.commit(); + titanDao.commit(); } } } + }*/ + +/** + * Update GroupDefinition metadata + * @param componentId + * @param user + * @param componentType + * @param updatedGroup + * @param inTransaction + * @return + */ + public Either validateAndUpdateGroupMetadata( + String componentId, + User user, + ComponentTypeEnum componentType, + GroupDefinition updatedGroup, + boolean inTransaction) { + + Either result = null; + try{ + // Validate user exist + Either validateUserExists = validateUserExists(user.getUserId(), UPDATE_GROUP, inTransaction); + if (validateUserExists.isRight()) { + result = Either.right(validateUserExists.right().value()); + return result; + } + // Validate component exist + Either validateComponent = validateComponentExists(componentId, componentType, null); + if (validateComponent.isRight()) { + result = Either.right(validateComponent.right().value()); + return result; + } + org.openecomp.sdc.be.model.Component component = validateComponent.left().value(); + // validate we can work on component + Either canWork = validateCanWorkOnComponent(component, user.getUserId()); + if (canWork.isRight()) { + result = Either.right(canWork.right().value()); + return result; + } + List currentGroups = component.getGroups(); + if(CollectionUtils.isEmpty(currentGroups)){ + log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue())); + return result; + } + // Validate groups exists in the component + Optional currentGroupOpt = currentGroups.stream().filter(g -> g.getUniqueId().equals(updatedGroup.getUniqueId())).findAny(); + if(!currentGroupOpt.isPresent()){ + log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue())); + return result; + } + GroupDefinition currentGroup = currentGroupOpt.get(); + Either lockResult = lockComponent(componentId, component, "Update GroupDefinition Metadata"); + if (lockResult.isRight()) { + result = Either.right(lockResult.right().value()); + return result; + } + // Validate group type is vfModule + if (!currentGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) { + log.error("Failed to update the metadata of group {}. Group type is {} and different then: {}", currentGroup.getName(), currentGroup.getType(), Constants.DEFAULT_GROUP_VF_MODULE); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_TYPE, updatedGroup.getType()); + result = Either.right(responseFormat); + return result; + } + result = updateGroupMetadata(component, currentGroup, updatedGroup); + return result; + + } finally { + if(result.isLeft()){ + titanDao.commit(); + } else { + titanDao.rollback(); + } + graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); + } + } + + private Either updateGroupMetadata(Component component, GroupDefinition currentGroup, GroupDefinition updatedGroup) { + String currentGroupName = currentGroup.getName(); + Either result = validateAndUpdateGroupMetadata(currentGroup, updatedGroup); + + if(result.isRight()){ + log.debug("Failed to validate a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName()); + } + if(result.isLeft()){ + result = updateGroup(component, currentGroup, currentGroupName); + } + return result; + } + + private Either updateGroup(Component component, GroupDefinition updatedGroup, String currentGroupName) { + Either handleGroupRes; + Either result = null; + if(updatedGroup.getName().equals(currentGroupName)){ + handleGroupRes = groupsOperation.updateGroup(component, updatedGroup); + if(handleGroupRes.isRight()){ + log.debug("Failed to update a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value()))); + } + } else { + StorageOperationStatus deleteStatus = groupsOperation.deleteGroup(component, currentGroupName); + if(deleteStatus != StorageOperationStatus.OK){ + log.debug("Failed to delete the group {} from component {}. ", updatedGroup.getName(), component.getName()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteStatus))); + } + handleGroupRes = groupsOperation.addGroup(component, updatedGroup); + if(handleGroupRes.isRight()){ + log.debug("Failed to add the group {} to component {}. ", updatedGroup.getName(), component.getName()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value()))); + } + } + if(result == null){ + result = Either.left(updatedGroup); + } + return result; } /** - * Update GroupDefinition metadata - * + * Validate and Update Group Property * @param componentId + * @param groupUniqueId * @param user - * @param groupId * @param componentType - * @param groupUpdate + * @param groupPropertiesToUpdate * @param inTransaction * @return */ - public Either updateGroupMetadata(String componentId, User user, String groupUniqueId, ComponentTypeEnum componentType, GroupDefinition groupUpdate, boolean inTransaction) { - - Either result = null; + public Either, ResponseFormat> validateAndUpdateGroupProperties( + String componentId, + String groupUniqueId, + User user, + ComponentTypeEnum componentType, + List groupPropertiesToUpdate, boolean inTransaction) { + + Either, ResponseFormat> result = Either.left(groupPropertiesToUpdate); + try{ + Optional optionalGroupConnectedToVf = null; + GroupDefinition currentGroup = null; + StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, componentType.getNodeType()); + if( lockResult != StorageOperationStatus.OK ){ + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( + lockResult, componentType), componentId)); + } + if( result.isLeft() ){ + //VF exist because lock succedded + Resource vf = (Resource) toscaOperationFacade.getToscaElement(componentId).left().value(); + optionalGroupConnectedToVf = + //All groups on resource + vf.getGroups().stream(). + //Filter in group sent is part of VF groups + filter( e -> e.getUniqueId().equals(groupUniqueId)). + //Collect + findAny(); + if( !optionalGroupConnectedToVf.isPresent() ){ + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, + groupUniqueId, vf.getName(), ComponentTypeEnum.RESOURCE.getValue())); + } + } + + if( result.isLeft() ){ + currentGroup = optionalGroupConnectedToVf.get(); + result = validateGroupPropertyAndResetEmptyValue(currentGroup, groupPropertiesToUpdate); + } + if( result.isLeft() ){ + result = updateGroupPropertiesValue(componentId, currentGroup, groupPropertiesToUpdate, inTransaction); + if (result.isRight()) { + BeEcompErrorManager.getInstance().logBeSystemError("Update GroupProperties"); + log.debug("failed to update Vf {}", componentId); + } + } - // Validate user and validate group belongs to component - List groups = new ArrayList<>(); - groups.add(groupUpdate); - Either validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, user.getUserId(), componentType, groups, inTransaction); - if (validateGroupsBeforeUpdate.isRight()) { - result = Either.right(validateGroupsBeforeUpdate.right().value()); - return result; } - Component component = validateGroupsBeforeUpdate.left().value(); + catch(Exception e){ + log.debug("Error in validateAndUpdateGroupProperty {}", e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + finally{ + graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); + } + return result; + } + private void resetEmptyValueWithDefaults(List groupPropertiesToUpdate, GroupDefinition originalGroup) { + Map originalProperties = + //Stream of original properties from group + originalGroup.convertToGroupProperties().stream(). + //Collecting to map with name as key + collect(Collectors.toMap(e -> e.getName(), e -> e)); + for( GroupProperty gp : groupPropertiesToUpdate){ + if( StringUtils.isEmpty(gp.getValue())){ + gp.setValue(originalProperties.get(gp.getName()).getDefaultValue()); + } + } + + } - // Get the GroupDefinition object - Either groupStatus = groupOperation.getGroup(groupUniqueId); - if (groupStatus.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(groupStatus.right().value(), ComponentTypeEnum.SERVICE), "")); + private Either, ResponseFormat> validateGroupPropertyAndResetEmptyValue( + GroupDefinition originalGroup, List groupPropertiesToUpdate) { + + Either, ResponseFormat> ret = validateOnlyValueChanged(groupPropertiesToUpdate, originalGroup); + if (ret.isLeft()) { + resetEmptyValueWithDefaults(groupPropertiesToUpdate, originalGroup); } - GroupDefinition currentGroup = groupStatus.left().value(); + if (ret.isLeft()) { + // Validate Type Match Value + Optional optionalError = + //Stream of group properties + groupPropertiesToUpdate.stream(). + //Validate each and map to returned Strorage status value + map( e -> groupOperation .validateAndUpdatePropertyValue(e)). + //Keep only failed result if there is such + filter( e -> e != StorageOperationStatus.OK). + //collect + findFirst(); + if( optionalError.isPresent()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(optionalError.get()); + ret = Either.right(componentsUtils.getResponseFormat(actionStatus)); + } - // Validate group type is vfModule - if (!currentGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) { - log.error("Group update metadata: Group type is different then: {}", Constants.DEFAULT_GROUP_VF_MODULE); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_TYPE, groupUpdate.getType()); - return Either.right(responseFormat); } + if (ret.isLeft()) { + // Validate min max ect... + ret = validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup); + } - Either validationRsponse = validateAndUpdateGroupMetadata(currentGroup, groupUpdate); - if (validationRsponse.isRight()) { - log.info("Group update metadata: validations field."); - return validationRsponse; + return ret; + } + private Either, ResponseFormat> validatePropertyBusinessLogic( + List groupPropertiesToUpdate, GroupDefinition originalGroup) { + + Either, ResponseFormat> ret = Either.left(groupPropertiesToUpdate); + + Map nameValueMap = new HashMap<>(); + for(GroupProperty gp : groupPropertiesToUpdate){ + //Filter out non special properties which does not have Enum + final PropertyNames gpEnum = PropertyNames.findName(gp.getName()); + if( gpEnum != null ){ + nameValueMap.put(gpEnum, gp.getValue()); + } + } + + if ( !MapUtils.isEmpty(nameValueMap) ) { + + if (nameValueMap.containsKey(PropertyNames.INITIAL_COUNT) || nameValueMap.containsKey(PropertyNames.MAX_INSTANCES) + || nameValueMap.containsKey(PropertyNames.MIN_INSTANCES)) { + + + Map oldValueMap = prepareMapWithOriginalProperties(originalGroup); + + Either eitherValid = validateMinMaxAndInitialCountPropertyLogicVF(nameValueMap, + oldValueMap); + if (eitherValid.isRight()) { + ret = Either.right(eitherValid.right().value()); + } + } + if (ret.isLeft() && (nameValueMap.containsKey(PropertyNames.VF_MODULE_DESCRIPTION) + || nameValueMap.containsKey(PropertyNames.VF_MODULE_LABEL))) { + + Optional optionalError = + //Stream of group Properties + groupPropertiesToUpdate.stream(). + //Filter in only properties that needs text validation + filter(e -> enumHasValueFilter(e.getName(), + enumName -> PropertyNames.findName(enumName), + PropertyNames.VF_MODULE_DESCRIPTION, PropertyNames.VF_MODULE_LABEL)). + //validate text properties + map( e -> validateFreeText(e)). + //filter in only errors if exist + filter( e -> e.isRight()). + //map the Either value to the Error + map( e -> e.right().value()) + //collect + .findFirst(); + if( optionalError.isPresent() ){ + ret = Either.right(optionalError.get()); + } + + } } - GroupDefinition groupToUpdate = validationRsponse.left().value(); - // lock resource - Either lockResult = lockComponent(componentId, component, "Update GroupDefinition Metadata"); - if (lockResult.isRight()) { - return Either.right(lockResult.right().value()); + return ret; + } + + private Map prepareMapWithOriginalProperties(GroupDefinition originalGroup) { + Map oldValueMap = new HashMap<>(); + PropertyNames[] propertiesToCheck = new PropertyNames[] { PropertyNames.INITIAL_COUNT, + PropertyNames.MAX_INSTANCES, PropertyNames.MIN_INSTANCES }; + + for(GroupProperty gp : originalGroup.convertToGroupProperties()){ + if( enumHasValueFilter(gp.getName(), enumName -> PropertyNames.findName(enumName), propertiesToCheck)){ + oldValueMap.put(PropertyNames.findName(gp.getName()), gp.getValue()); + } } - try { - Either updateResponse = groupOperation.updateGroupName(groupUniqueId, groupUpdate.getName(), inTransaction); - if (updateResponse.isRight()) { - titanGenericDao.rollback(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Update GroupDefinition Metadata"); - BeEcompErrorManager.getInstance().logBeSystemError("Update GroupDefinition Metadata"); - log.debug("failed to update sevice {}", groupToUpdate.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - titanGenericDao.commit(); - return Either.left(updateResponse.left().value()); - } finally { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); + if( StringUtils.isEmpty(oldValueMap.get(PropertyNames.MAX_INSTANCES)) ){ + oldValueMap.put(PropertyNames.MAX_INSTANCES, String.valueOf(Integer.MAX_VALUE)); + } + return oldValueMap; + } + + private Either, ResponseFormat> validateOnlyValueChanged( + List groupPropertiesToUpdate, GroupDefinition originalGroup) { + + Either, ResponseFormat> ret = Either.left(groupPropertiesToUpdate); + if( CollectionUtils.isEmpty(groupPropertiesToUpdate) ){ + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, StringUtils.EMPTY)); + } + else if (CollectionUtils.isEmpty(originalGroup.getProperties())) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, + groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName())); + } else { + Map namePropertyMap = + //Original Group Properties Stream + originalGroup.convertToGroupProperties().stream(). + //Collect to map with name as key + collect(Collectors.toMap(e -> e.getName(), e -> e)); + + Optional optionalMissingProperty = + //Group Properties to be updated Stream + groupPropertiesToUpdate.stream(). + //Filter in property that is not contained in original if there is such + filter(e -> !namePropertyMap.containsKey(e.getName())). + //collect + findFirst(); + + if (optionalMissingProperty.isPresent()) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, + optionalMissingProperty.get().getName())); + } + else{ + Optional optionalNonValueChange = + //groups to be updated stream + groupPropertiesToUpdate.stream(). + //filter in only properties with non-value (illegal) change + filter( e -> !isOnlyGroupPropertyValueChanged(e, namePropertyMap.get(e.getName()))). + //Collect + findFirst(); + if (optionalNonValueChange.isPresent()) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY, + optionalNonValueChange.get().getName())); + + } + } + } + return ret; } + /** + * if groupProperty are the same or if only value is different returns true, otherwise returns false. + * @param groupProperty + * @param groupProperty2 + * @return + */ + private boolean isOnlyGroupPropertyValueChanged(GroupProperty groupProperty, GroupProperty groupProperty2) { + //Create 2 duplicates for groupPropery and reset their values + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + try { + GroupProperty groupPropertyDuplicate = new GroupProperty(groupProperty); + groupPropertyDuplicate.setValue(null); + groupPropertyDuplicate.setSchema(null); + groupPropertyDuplicate.setParentUniqueId(null); +// GroupProperty groupProperty2Duplicate = gson.fromJson(JsonParserUtils.jsonToString(groupProperty2), GroupProperty.class); + GroupProperty groupProperty2Duplicate = new GroupProperty(groupProperty2); + groupProperty2Duplicate.setValue(null); + groupProperty2Duplicate.setSchema(null); + groupProperty2Duplicate.setParentUniqueId(null); + return groupPropertyDuplicate.equals(groupProperty2Duplicate) && StringUtils.equals(groupPropertyDuplicate.getValueUniqueUid(), groupProperty2Duplicate.getValueUniqueUid()); + } catch (Exception e) { + log.debug("Failed validate group properties. ", e); + return false; + } + } /** * Validate and update GroupDefinition metadata * @@ -481,7 +768,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param currentGroup * @param groupUpdate * @return - */ + **/ private Either validateAndUpdateGroupMetadata(GroupDefinition currentGroup, GroupDefinition groupUpdate) { // Check if to update, and update GroupDefinition name. Either response = validateAndUpdateGroupName(currentGroup, groupUpdate); @@ -577,7 +864,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - public Either, ResponseFormat> associateArtifactsToGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { + /*public Either, ResponseFormat> associateArtifactsToGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { Either, ResponseFormat> result = null; @@ -634,7 +921,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { boolean isChanged = componentArtifacts.removeAll(artifactsToAssociate); if (isChanged) {// I.e. At least one artifact is already // associated to the group - log.debug("Some of the artifacts already associated to group {}", groupDefinition.getUniqueId()); + log.debug("Some of the artifacts already associated to group {}" , groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_ASSOCIATED, componentGroup.getName())); } } @@ -661,10 +948,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); - titanGenericDao.commit(); + titanDao.commit(); } } @@ -675,9 +962,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } } - } + }*/ - public Either, ResponseFormat> associateMembersToGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { + /*public Either, ResponseFormat> associateMembersToGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { Either, ResponseFormat> result = null; @@ -739,10 +1026,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); - titanGenericDao.commit(); + titanDao.commit(); } } @@ -753,7 +1040,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } } - } + }*/ /** * associate artifacts to a given group @@ -778,8 +1065,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return result; } - User user = validateUserExists.left().value(); - // Validate component exist org.openecomp.sdc.be.model.Component component = null; String realComponentId = componentId; @@ -790,85 +1075,88 @@ public class GroupBusinessLogic extends BaseBusinessLogic { componentParametersView.setIgnoreGroups(false); componentParametersView.setIgnoreArtifacts(false); componentParametersView.setIgnoreUsers(false); - componentParametersView.setIgnoreComponentInstances(false); - Either validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView, userId, null, user); + Either validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); return result; } component = validateComponent.left().value(); - // validate we can work on component - /* - * Either canWork = validateCanWorkOnComponent( component, userId); if (canWork.isRight()) { result = Either.right(canWork.right().value()); return result; } - */ - List groups = component.getGroups(); - Optional findAny = groups.stream().filter(p -> p.getUniqueId().equals(groupId)).findAny(); - if (findAny.isPresent()) { - GroupDefinition group = findAny.get(); - Boolean isBase = null;// Constants.IS_BASE; - List props = group.getProperties(); - if (props != null && !props.isEmpty()) { - Optional isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); - if (isBasePropOp.isPresent()) { - GroupProperty propIsBase = isBasePropOp.get(); - isBase = Boolean.parseBoolean(propIsBase.getValue()); + Either groupEither = findGroupOnComponent(component, groupId); + + if (groupEither.isRight()) { + log.debug("Faild to find group {} under component {}", groupId, component.getUniqueId()); + BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "group " + groupId + " not found under component " + component.getUniqueId(), ErrorSeverity.INFO); + String componentTypeForResponse = getComponentTypeForResponse(component); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse)); + return result; + } + GroupDefinition group = groupEither.left().value(); + + + Boolean isBase = null;// Constants.IS_BASE; + List props = group.convertToGroupProperties(); + if (props != null && !props.isEmpty()) { + Optional isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); + if (isBasePropOp.isPresent()) { + GroupProperty propIsBase = isBasePropOp.get(); + isBase = Boolean.parseBoolean(propIsBase.getValue()); - } else { - BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO); - // return - // Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } else { + BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO); + // return + // Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } } + } - List artifacts = new ArrayList(); - List artifactsIds = group.getArtifacts(); - if (artifactsIds != null && !artifactsIds.isEmpty()) { - Either, ResponseFormat> getArtifacts = getArtifactsBelongsToComponent(component, artifactsIds, GET_GROUP); - if (getArtifacts.isRight()) { - log.debug("Faild to find artifacts in group {} under component {}", groupId, component.getUniqueId()); - // result = Either.right(getArtifacts.right().value()); - // return result; - } else { - - List artifactsFromComponent = getArtifacts.left().value(); - if (artifactsFromComponent != null && !artifactsFromComponent.isEmpty()) { - for (ArtifactDefinition artifactDefinition : artifactsFromComponent) { - ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition); - artifacts.add(artifactDefinitionInfo); - } - } + List artifacts = new ArrayList<>(); + List artifactsFromComponent = new ArrayList<>(); + List artifactsIds = group.getArtifacts(); + + Map deploymentArtifacts = null; + if(MapUtils.isNotEmpty(component.getDeploymentArtifacts())){ + deploymentArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(a -> a.getUniqueId(), a -> a)); + } + + if (artifactsIds != null && !artifactsIds.isEmpty()) { + for(String id: artifactsIds){ + if (MapUtils.isEmpty(deploymentArtifacts) || !deploymentArtifacts.containsKey(id)) { + log.debug("Failed to get artifact {} . Status is {} ", id, StorageOperationStatus.NOT_FOUND); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND)); + result = Either.right(responseFormat); + return result; + } + artifactsFromComponent.add(deploymentArtifacts.get(id)); + } + if (!artifactsFromComponent.isEmpty()) { + for (ArtifactDefinition artifactDefinition : artifactsFromComponent) { + ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition); + artifacts.add(artifactDefinitionInfo); } } - GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group); - resultInfo.setIsBase(isBase); - if (!artifacts.isEmpty()) - resultInfo.setArtifacts(artifacts); - result = Either.left(resultInfo); + } + GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group); + resultInfo.setIsBase(isBase); + if (!artifacts.isEmpty()) + resultInfo.setArtifacts(artifacts); - return result; + result = Either.left(resultInfo); - } else { - log.debug("Faild to find group {} under component {}", groupId, component.getUniqueId()); - BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "group " + groupId + " not found under component " + component.getUniqueId(), ErrorSeverity.INFO); - String componentTypeForResponse = getComponentTypeForResponse(component); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse)); - return result; + return result; - } } finally { if (false == inTransaction) { if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); - titanGenericDao.commit(); + titanDao.commit(); } } @@ -877,6 +1165,21 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } + private Either findGroupOnComponent(Component component, String groupId) { + + Either result = null; + if(CollectionUtils.isNotEmpty(component.getGroups())){ + Optional foundGroup = component.getGroups().stream().filter(g -> g.getUniqueId().equals(groupId)).findFirst(); + if(foundGroup.isPresent()){ + result = Either.left(foundGroup.get()); + } + } + if(result == null){ + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + return result; + } + /** * @param componentId * @param userId @@ -895,7 +1198,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic { result = Either.right(validateUserExists.right().value()); return result; } - User user = validateUserExists.left().value(); // Validate component exist String realComponentId = componentId; @@ -907,7 +1209,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false); - Either validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView, userId, null, user); + Either validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); @@ -945,14 +1247,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return Either.left(component); } - private ResponseFormat validateGroupsInComponent(List groups, org.openecomp.sdc.be.model.Component component) { - - Function getByName = s -> s.getName(); - - return validateGroupsInComponentByFunc(groups, component, getByName); - - } - /** * @param groups * @param component @@ -1014,7 +1308,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - public Either, ResponseFormat> dissociateArtifactsFromGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { + /*public Either, ResponseFormat> dissociateArtifactsFromGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { Either, ResponseFormat> result = null; @@ -1073,13 +1367,13 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (false == containsAll) { // At least one artifact is // not associated to the // group - log.debug("Some of the artifacts already dissociated to group {}", groupDefinition.getUniqueId()); + log.debug("Some of the artifacts already dissociated to group {}" , groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, componentGroup.getName())); } } else { if (artifactsSizeInGroup == 0) { if (artifactsToDissociate != null && false == artifactsToDissociate.isEmpty()) { - log.debug("No artifact is found under the group {}", groupDefinition.getUniqueId()); + log.debug("No artifact is found under the group {}" , groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, componentGroup.getName())); } } @@ -1107,10 +1401,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); - titanGenericDao.commit(); + titanDao.commit(); } } @@ -1121,9 +1415,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } - } + }*/ - public Either, ResponseFormat> createGroups(String componentId, String userId, ComponentTypeEnum componentType, List groupDefinitions, boolean shouldLockComp, boolean inTransaction) { + /*public Either, ResponseFormat> createGroups(String componentId, String userId, ComponentTypeEnum componentType, List groupDefinitions, boolean shouldLockComp, boolean inTransaction) { Either, ResponseFormat> result = null; @@ -1131,9 +1425,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic { org.openecomp.sdc.be.model.Component component = null; try { - if (groupDefinitions != null && false == groupDefinitions.isEmpty()) { + if (groupDefinitions != null && !groupDefinitions.isEmpty()) { - if (shouldLockComp == true && inTransaction == true) { + if (shouldLockComp && inTransaction) { BeEcompErrorManager.getInstance().logInternalFlowError("createGroups", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock component since we are in a middle of another // transaction. @@ -1157,7 +1451,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false); - Either validateComponent = validateComponentExists(componentId, componentType, componentParametersView, userId, null, user); + Either validateComponent = validateComponentExists(componentId, componentType, componentParametersView); if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); @@ -1181,7 +1475,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { for (GroupDefinition groupDefinition : groupDefinitions) { Either createGroup = this.createGroup(component, user, componentType, groupDefinition, true); if (createGroup.isRight()) { - log.debug("Failed to create group {}.", groupDefinition); + log.debug("Failed to create group {}." , groupDefinition ); result = Either.right(createGroup.right().value()); return result; } @@ -1199,10 +1493,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); - titanGenericDao.commit(); + titanDao.commit(); } } @@ -1219,7 +1513,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { Either result = null; - log.debug("Going to create group {}", groupDefinition); + log.trace("Going to create group {}" , groupDefinition); try { @@ -1314,10 +1608,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); - titanGenericDao.commit(); + titanDao.commit(); } } @@ -1351,8 +1645,23 @@ public class GroupBusinessLogic extends BaseBusinessLogic { updatedGroups.add(updateGroupNameRes.left().value()); } return updateGroupNamesRes; - } + }*/ + + private Either, ResponseFormat> updateGroupPropertiesValue(String componentId, + GroupDefinition currentGroup, List groupPropertyToUpdate, boolean inTransaction) { + Either, ResponseFormat> result; + Either, StorageOperationStatus> eitherUpdate = groupsOperation + .updateGroupPropertiesOnComponent(componentId, currentGroup, groupPropertyToUpdate); + if (eitherUpdate.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(eitherUpdate.right().value()); + result = Either.right(componentsUtils.getResponseFormat(actionStatus)); + } else { + result = Either.left(eitherUpdate.left().value()); + } + return result; + } + public Either validateGenerateVfModuleGroupNames(List allGroups, String resourceSystemName, int startGroupCounter) { Either validateGenerateGroupNamesRes = Either.left(true); Collections.sort(allGroups, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2)); @@ -1438,7 +1747,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return counter; } - public Either, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List groups, String resourceSystemName, boolean inTransaction) { + public Either, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List groups, Component component, boolean inTransaction) { List updatedGroups = new ArrayList<>(); Either, ResponseFormat> result = Either.left(updatedGroups); @@ -1451,27 +1760,25 @@ public class GroupBusinessLogic extends BaseBusinessLogic { int counter; if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(oldGroupName).matches()) { counter = Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]); - newGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), counter); + newGroupNameRes = validateGenerateVfModuleGroupName(component.getSystemName(), group.getDescription(), counter); if (newGroupNameRes.isRight()) { log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value()); result = Either.right(newGroupNameRes.right().value()); break; } newGroupName = newGroupNameRes.left().value(); - updateGroupNameRes = groupOperation.updateGroupName(group.getUniqueId(), newGroupName, inTransaction); - if (updateGroupNameRes.isRight()) { - log.debug("Failed to update vf module group name for group {} . Status is {} ", oldGroupName, updateGroupNameRes.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupNameRes.right().value())); - result = Either.right(responseFormat); - break; - } + group.setName(newGroupName); + } updatedGroups.add(group); + } + + result = Either.left(updatedGroups); return result; } - public Either, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions, boolean inTransaction) { + /*public Either, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions, boolean inTransaction) { List generatedGroups = new ArrayList<>(); Either, ResponseFormat> result = Either.left(generatedGroups); @@ -1497,16 +1804,710 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); - titanGenericDao.rollback(); + titanDao.rollback(); + } else { + log.debug("Going to execute commit on create group."); + titanDao.commit(); + } + + } + + } + + }*/ + + public Either getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, String componentInstanceId, String groupInstId, String userId, boolean inTransaction) { + Either result = null; + + // Validate user exist + Either validateUserExists = validateUserExists(userId, UPDATE_GROUP, true); + + if (validateUserExists.isRight()) { + result = Either.right(validateUserExists.right().value()); + return result; + } + + // Validate component exist + org.openecomp.sdc.be.model.Component component = null; + String realComponentId = componentId; + + try { + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreUsers(false); + componentParametersView.setIgnoreComponentInstances(false); + componentParametersView.setIgnoreArtifacts(false); + + Either validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); + if (validateComponent.isRight()) { + result = Either.right(validateComponent.right().value()); + return result; + } + component = validateComponent.left().value(); + Either, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(component, componentInstanceId, groupInstId); + + if (findComponentInstanceAndGroupInstanceRes.isRight()) { + log.debug("Failed to get group {} . Status is {} ", groupInstId, findComponentInstanceAndGroupInstanceRes.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findComponentInstanceAndGroupInstanceRes.right().value())); + result = Either.right(responseFormat); + return result; + } + + GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight(); + ComponentInstance componentInstance = findComponentInstanceAndGroupInstanceRes.left().value().getLeft(); + + Boolean isBase = null;// Constants.IS_BASE; + List props = group.convertToGroupInstancesProperties(); + if (props != null && !props.isEmpty()) { + Optional isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); + if (isBasePropOp.isPresent()) { + GroupProperty propIsBase = isBasePropOp.get(); + isBase = Boolean.parseBoolean(propIsBase.getValue()); + + } else { + BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO); + // return + // Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + + } + } + + List artifacts = new ArrayList<>(); + List artifactsFromComponent = new ArrayList<>(); + List artifactsIds = group.getArtifacts(); + if (artifactsIds != null && !artifactsIds.isEmpty()) { + + for(String id: artifactsIds){ + Either artifactEither = artifactsOperation.getArtifactById(componentInstance.getComponentUid(), id); + if (artifactEither.isRight()) { + log.debug("Failed to get artifact {} . Status is {} ", id, artifactEither.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactEither.right().value())); + result = Either.right(responseFormat); + return result; + } + artifactsFromComponent.add(artifactEither.left().value()); + } + if (!artifactsFromComponent.isEmpty()) { + for (ArtifactDefinition artifactDefinition : artifactsFromComponent) { + ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition); + artifacts.add(artifactDefinitionInfo); + } + } + + + } + GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group); + resultInfo.setIsBase(isBase); + if (!artifacts.isEmpty()) + resultInfo.setArtifacts(artifacts); + + result = Either.left(resultInfo); + + return result; + + + } finally { + + if (false == inTransaction) { + + if (result == null || result.isRight()) { + log.debug("Going to execute rollback on create group."); + titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); - titanGenericDao.commit(); + titanDao.commit(); + } + + } + + } + } + + private Either, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(Component component, String componentInstanceId, String groupInstId) { + + Either, StorageOperationStatus> result = null; + if(CollectionUtils.isNotEmpty(component.getComponentInstances())){ + Optional foundGroup; + Optional foundComponent = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst(); + if(foundComponent.isPresent() && CollectionUtils.isNotEmpty(foundComponent.get().getGroupInstances())){ + foundGroup = foundComponent.get().getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstId)).findFirst(); + if(foundGroup.isPresent()){ + result = Either.left(new ImmutablePair<>(foundComponent.get(), foundGroup.get())); + } + } + } + if(result == null){ + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + return result; + } + + private int getLatestIntProperty(Map newValues, Map parentValues, + PropertyNames propertyKey) { + String value; + if( newValues.containsKey(propertyKey) ){ + value = newValues.get(propertyKey); + } + else{ + value = parentValues.get(propertyKey); + } + return Integer.valueOf(value); + } + + private boolean isPropertyChanged(Map newValues, Map parentValues, + final PropertyNames minInstances) { + return newValues.containsKey(minInstances) && newValues.containsKey(minInstances) && !newValues.get(minInstances).equals(parentValues.get(minInstances)); + } + + private Either validateMinMaxAndInitialCountPropertyLogicVF( + Map newValues, Map parentValues) { + + int latestMaxInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MAX_INSTANCES); + int latestInitialCount = getLatestIntProperty(newValues, parentValues, PropertyNames.INITIAL_COUNT); + int latestMinInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MIN_INSTANCES); + Either result = Either.left(true); + + if (isPropertyChanged(newValues, parentValues, PropertyNames.INITIAL_COUNT) && result.isLeft()) { + if (latestInitialCount > latestMaxInstances || latestInitialCount < latestMinInstances) { + result = Either.right( + componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, + PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances), + String.valueOf(latestMaxInstances))); + } + } + if (isPropertyChanged(newValues, parentValues, PropertyNames.MAX_INSTANCES) && result.isLeft()) { + if (latestMaxInstances < latestInitialCount) { + result = Either.right(componentsUtils.getResponseFormat( + ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, + PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount))); + } + + } + if (isPropertyChanged(newValues, parentValues, PropertyNames.MIN_INSTANCES) && result.isLeft()) { + if (latestMinInstances > latestInitialCount) { + result = Either.right(componentsUtils.getResponseFormat( + ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, + PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount))); + } + + } + return result; + } + private Either validateMinMaxAndInitialCountPropertyLogic(Map newValues, Map currValues, Map parentValues) { + + Either result; + for(Entry entry : newValues.entrySet()){ + PropertyNames currPropertyName = entry.getKey(); + if(currPropertyName == PropertyNames.MIN_INSTANCES){ + String minValue = parentValues.get(PropertyNames.MIN_INSTANCES); + String maxValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); + result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), + new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), + new ImmutablePair(PropertyNames.MAX_INSTANCES, maxValue)); + if(result.isRight()){ + return result; + } + } + else if(currPropertyName == PropertyNames.INITIAL_COUNT){ + String minValue = newValues.containsKey(PropertyNames.MIN_INSTANCES) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.MIN_INSTANCES); + String maxValue = newValues.containsKey(PropertyNames.MAX_INSTANCES) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.MAX_INSTANCES); + result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), + new ImmutablePair(PropertyNames.MIN_INSTANCES,minValue), + new ImmutablePair(PropertyNames.MAX_INSTANCES, maxValue)); + if(result.isRight()){ + return result; + } + } + else if(currPropertyName == PropertyNames.MAX_INSTANCES){ + String minValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); + String maxValue = parentValues.get(PropertyNames.MAX_INSTANCES); + result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), + new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), + new ImmutablePair(PropertyNames.MAX_INSTANCES, maxValue)); + if(result.isRight()){ + return result; } + } + } + return Either.left(true); + } + private Either validateValueInRange(ImmutablePair newValue, ImmutablePair min, ImmutablePair max) { + Either result; + final String warnMessage = "Failed to validate {} as property value of {}. It must be not higher than {}, and not lower than {}."; + int newValueInt = parseIntValue(newValue.getValue(), newValue.getKey()); + int minInt = parseIntValue(min.getValue(), min.getKey()); + int maxInt = parseIntValue(max.getValue(), max.getKey()); + if(newValueInt < 0 || minInt < 0 || maxInt < 0){ + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY)); + } + else if (newValueInt < minInt || newValueInt > maxInt) { + log.debug(warnMessage, newValue.getValue(), newValue.getKey().getPropertyName(), min.getValue(), max.getValue()); + result = Either.right(componentsUtils.getResponseFormat( + ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, + newValue.getKey().getPropertyName(), maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue())); + }else{ + result = Either.left(true); + } + return result; + } + + private int parseIntValue(String value, PropertyNames propertyName) { + int result; + if(propertyName == PropertyNames.MAX_INSTANCES ){ + result = convertIfUnboundMax(value); + } else if (NumberUtils.isNumber(value)) { + result = Integer.parseInt(value); + } else{ + result = -1; + } + return result; + } + +/** + * validates received new property values and updates group instance in case of success + * @param oldGroupInstance + * @param groupInstanceId + * @param newProperties + * @param inTransaction + * @return + */ + public Either validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List newProperties, boolean inTransaction) { + + Either actionResult = null; + Either updateGroupInstanceResult = null; + Either, ResponseFormat> validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties); + if(validateRes.isRight()){ + log.debug("Failed to validate group instance {} properties before update. ", oldGroupInstance.getName()); + actionResult = Either.right(validateRes.right().value()); + } + if(actionResult == null){ + List validatedReducedNewProperties = validateRes.left().value(); + updateGroupInstanceResult = groupsOperation.updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties); + if(updateGroupInstanceResult.isRight()){ + log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName()); + actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value()))); + } + } + if(actionResult == null){ + actionResult = Either.left(updateGroupInstanceResult.left().value()); + } + return actionResult; + } + + private Either, ResponseFormat> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List newProperties) { + + Either validationRes = null; + Either, ResponseFormat> actionResult; + Map existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(p->p.getName(),p->p)); + Map newPropertyValues = new EnumMap<>(PropertyNames.class); + List reducedProperties = new ArrayList<>(); + String currPropertyName; + try{ + for(GroupInstanceProperty currNewProperty : newProperties){ + currPropertyName = currNewProperty.getName(); + validationRes = handleAndAddProperty(reducedProperties, newPropertyValues, currNewProperty, existingProperties.get(currPropertyName)); + if(validationRes.isRight()){ + log.debug("Failed to handle property {} of group instance {}. ", currPropertyName, oldGroupInstance.getName()); + break; + } } + if(validationRes == null || validationRes.isLeft()){ + Map existingPropertyValues = new EnumMap<>(PropertyNames.class); + Map parentPropertyValues = new EnumMap<>(PropertyNames.class); + fillValuesAndParentValuesFromExistingProperties(existingProperties, existingPropertyValues, parentPropertyValues); + validationRes = validateMinMaxAndInitialCountPropertyLogic(newPropertyValues, existingPropertyValues, parentPropertyValues); + } + if(validationRes.isLeft()){ + actionResult = Either.left(reducedProperties); + } else { + actionResult = Either.right(validationRes.right().value()); + } + } catch( Exception e){ + log.error("Exception occured during validation and reducing group instance properties. The message is {}", e.getMessage(), e); + actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return actionResult; + } + private void fillValuesAndParentValuesFromExistingProperties(Map existingProperties, + Map propertyValues, Map parentPropertyValues) { + PropertyNames[] allPropertyNames = PropertyNames.values(); + for(PropertyNames name : allPropertyNames){ + if(isUpdatable(name)){ + propertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getValue())); + parentPropertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getParentValue())); + } } + } + private Either handleAndAddProperty(List reducedProperties, Map newPropertyValues, + GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) { + + Either validationRes = null; + String currPropertyName = currNewProperty.getName(); + PropertyNames propertyName = PropertyNames.findName(currPropertyName); + try{ + if(currExistingProperty == null){ + log.warn("The value of property with the name {} cannot be updated. The property not found on group instance. ", currPropertyName); + } + else if(isUpdatable(propertyName)){ + validationRes = validateAndUpdatePropertyValue(currNewProperty, currExistingProperty); + if(validationRes.isRight()){ + log.debug("Failed to validate property value {} of property {}. ", currNewProperty.getValue() , currPropertyName); + } else { + addPropertyUpdatedValues(reducedProperties, propertyName, newPropertyValues, currNewProperty, currExistingProperty); + } + } + else{ + validateImmutableProperty(currExistingProperty, currNewProperty); + } + if(validationRes == null){ + validationRes = Either.left(true); + } + } catch( Exception e){ + log.error("Exception occured during handle and adding property. The message is {}", e.getMessage(), e); + validationRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return validationRes; } + private boolean isUpdatable(PropertyNames updatablePropertyName) { + return updatablePropertyName != null && + updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber(); + } + + private void addPropertyUpdatedValues(List reducedProperties, PropertyNames propertyName, Map newPropertyValues, + GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { + + String newValue = newProperty.getValue(); + if(!newValue.equals(String.valueOf(existingProperty.getValue()))){ + newProperty.setValueUniqueUid(existingProperty.getValueUniqueUid()); + reducedProperties.add(newProperty); + } + if(!isEmptyMinInitialCountValue(propertyName, newValue)){ + newPropertyValues.put(propertyName, newValue); + } + } + + private boolean isEmptyMinInitialCountValue(PropertyNames propertyName, String newValue) { + boolean result = false; + if((propertyName == PropertyNames.MIN_INSTANCES || propertyName == PropertyNames.INITIAL_COUNT) && !NumberUtils.isNumber(newValue)){ + result = true; + } + return result; + } + + private int convertIfUnboundMax(String value) { + + int result; + if(!NumberUtils.isNumber(value)){ + result = Integer.MAX_VALUE; + } + else{ + result = Integer.parseInt(value); + } + return result; + } + + private Either validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { + + Either validationRes = null; + String parentValue = existingProperty.getParentValue(); + + newProperty.setParentValue(parentValue); + if(StringUtils.isEmpty(newProperty.getValue())){ + newProperty.setValue(parentValue); + } + if(StringUtils.isEmpty(existingProperty.getValue())){ + existingProperty.setValue(parentValue); + } + StorageOperationStatus status = groupOperation.validateAndUpdatePropertyValue(newProperty); + if(status != StorageOperationStatus.OK){ + log.debug("Failed to validate property value {} of property with name {}. Status is {}. ", newProperty.getValue(), newProperty.getName(), status); + validationRes = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + } + if(validationRes == null){ + validationRes = Either.left(true); + } + return validationRes; + } + + private void validateImmutableProperty(GroupProperty oldProperty, GroupProperty newProperty) { + if(oldProperty.getValue() == null && newProperty.getValue() != null || oldProperty.getValue()!=null && !oldProperty.getValue().equals(newProperty.getValue())){ + log.warn("The value of property with the name {} cannot be updated on service level. Going to ignore new property value {}. ",oldProperty.getName(), newProperty.getValue()); + } + } + + public Either, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions) { + + Map groups = new HashMap<>(); + //Map groupsPropertiesMap = new HashMap<>(); + Either, ResponseFormat> result = null; + Either, StorageOperationStatus> createGroupsResult = null; + Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + + } + + //handle groups and convert to tosca data + if (groupDefinitions != null && !groupDefinitions.isEmpty()) { + for (GroupDefinition groupDefinition : groupDefinitions) { + Either handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value()); + if (handleGroupRes.isRight()) { + result = Either.right(handleGroupRes.right().value()); + break; + } + GroupDefinition handledGroup = handleGroupRes.left().value(); + groups.put(handledGroup.getName(), new GroupDataDefinition(handledGroup)); + + } + } + if(result == null){ + createGroupsResult = groupsOperation.createGroups(component, user, componentType, groups); + if(createGroupsResult.isRight()){ + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); + } + } + if(result == null){ + result = Either.left(createGroupsResult.left().value()); + } + return result; + } + + public Either, ResponseFormat> addGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions) { + + + Either, ResponseFormat> result = null; + Either, StorageOperationStatus> createGroupsResult = null; + List groups = new ArrayList<>(); + + Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + + } + + //handle groups and convert to tosca data + if (groupDefinitions != null && !groupDefinitions.isEmpty()) { + for (GroupDefinition groupDefinition : groupDefinitions) { + Either handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value()); + if (handleGroupRes.isRight()) { + result = Either.right(handleGroupRes.right().value()); + break; + } + GroupDefinition handledGroup = handleGroupRes.left().value(); + groups.add(new GroupDataDefinition(handledGroup)); + } + } + if(result == null){ + createGroupsResult = groupsOperation.addGroups(component, user, componentType, groups); + if(createGroupsResult.isRight()){ + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); + } + } + if(result == null){ + result = Either.left(createGroupsResult.left().value()); + } + return result; + } + + public Either, ResponseFormat> deleteGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions) { + + + Either, ResponseFormat> result = null; + Either, StorageOperationStatus> createGroupsResult = null; + + createGroupsResult = groupsOperation.deleteGroups(component, user, componentType, groupDefinitions.stream().map(x-> new GroupDataDefinition(x)).collect(Collectors.toList())); + if(createGroupsResult.isRight()){ + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); + } + + if(result == null){ + result = Either.left(createGroupsResult.left().value()); + } + return result; + } + + /** + * Update specific group version + * + * @param groupDefinition + * @param inTransaction + * @return + */ + public Either, ResponseFormat> updateGroups(Component component, ComponentTypeEnum componentType, List groupDefinitions) { + + Either, ResponseFormat> result = null; + Either, StorageOperationStatus> createGroupsResult = null; + + createGroupsResult = groupsOperation.updateGroups(component, componentType, groupDefinitions.stream().map(x-> new GroupDataDefinition(x)).collect(Collectors.toList())); + if(createGroupsResult.isRight()){ + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); + } + + if(result == null){ + result = Either.left(createGroupsResult.left().value()); + } + return result; + } + + public Either handleGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, Map allDAtaTypes) { + + Either result = null; + + log.trace("Going to create group {}" , groupDefinition); + // 3. verify group not already exist + List groups = component.getGroups(); + boolean found = false; + if (groups != null && false == groups.isEmpty()) { + + GroupDefinition existGroupDef = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinition.getName())).findFirst().orElse(null); + + found = existGroupDef != null; + } + if (true == found) { + String componentTypeForResponse = getComponentTypeForResponse(component); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinition.getName(), component.getNormalizedName(), componentTypeForResponse)); + return result; + } + // 4. verify type of group exist + String groupType = groupDefinition.getType(); + if (groupType == null || groupType.isEmpty()) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupDefinition.getName())); + return result; + } + Either getGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType, true); + if (getGroupType.isRight()) { + StorageOperationStatus status = getGroupType.right().value(); + if (status == StorageOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType)); + return result; + } else { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + return result; + } + } + // 6. verify the component instances type are allowed according to + // the member types in the group type + GroupTypeDefinition groupTypeDefinition = getGroupType.left().value(); + + Either areValidMembers = verifyComponentInstancesAreValidMembers(component, componentType, groupDefinition.getName(), groupType, groupDefinition.getMembers(), groupTypeDefinition.getMembers()); + + if (areValidMembers.isRight()) { + ResponseFormat responseFormat = areValidMembers.right().value(); + result = Either.right(responseFormat); + return result; + } + // 7. verify the artifacts belongs to the component + Either areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP); + if (areValidArtifacts.isRight()) { + ResponseFormat responseFormat = areValidArtifacts.right().value(); + result = Either.right(responseFormat); + return result; + } + List groupTypeProperties = groupTypeDefinition.getProperties(); + + List properties = groupDefinition.convertToGroupProperties(); + List updatedGroupTypeProperties = new ArrayList<>(); + if (properties != null && false == properties.isEmpty()) { + + if (groupTypeProperties == null || true == groupTypeProperties.isEmpty()) { + BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.MATCH_NOT_FOUND)))); + } + + Map groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); + + Either addPropertyResult = null; + int i = 1; + for (GroupProperty prop : properties) { + addPropertyResult = handleProperty(prop, groupTypePropertiesMap.get(prop.getName()), i, allDAtaTypes); + if(addPropertyResult.isRight()){ + BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "failed to validate property", ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyResult.right().value())))); + } + updatedGroupTypeProperties.add(addPropertyResult.left().value()); + + i++; + } + } + if(groupDefinition.getUniqueId() == null){ + String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinition.getName()); + groupDefinition.setUniqueId(uid); + } + groupDefinition.convertFromGroupProperties(updatedGroupTypeProperties); + groupDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); + groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID()); + groupDefinition.setVersion(INITIAL_VERSION); + groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId()); + + return Either.left(groupDefinition); + } + + + + public Either handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map allDataTypes) { + + if (prop == null) { + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + + PropertyDataDefinition propDataDef = prop; + String propertyType = propDataDef.getType(); + String value = groupProperty.getValue(); + + Either checkInnerType = propertyOperation.checkInnerType(propDataDef); + if (checkInnerType.isRight()) { + TitanOperationStatus status = checkInnerType.right().value(); + return Either.right(status); + } + + String innerType = checkInnerType.left().value(); + + + log.debug("Before validateAndUpdatePropertyValue"); + Either isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes); + log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid); + + String newValue = value; + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (res == false) { + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + + String uniqueId = UniqueIdBuilder.buildGroupPropertyValueUid((String) prop.getUniqueId(), index); + + groupProperty.setUniqueId(uniqueId); + groupProperty.setValue(newValue); + groupProperty.setType(prop.getType()); + groupProperty.setDefaultValue(prop.getDefaultValue()); + groupProperty.setDescription(prop.getDescription()); + groupProperty.setSchema(prop.getSchema()); + groupProperty.setPassword(prop.isPassword()); + groupProperty.setParentUniqueId(prop.getUniqueId()); + + + log.debug("Before adding property value to graph {}", groupProperty); + + + return Either.left(groupProperty); + } + + + + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java index 81dfc1a256..e535214d70 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java @@ -39,7 +39,6 @@ import javax.servlet.ServletContext; import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineClusterHealth; import org.openecomp.sdc.be.components.distribution.engine.UebHealthCheckCall; import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.IEsHealthCheckDao; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.impl.WebAppContextWrapper; @@ -102,7 +101,7 @@ public class HealthCheckBusinessLogic { lastBeHealthCheckInfos = getBeHealthCheckInfos(); - log.debug("After initializing lastBeHealthCheckInfos :{}", lastBeHealthCheckInfos); + log.debug("After initializing lastBeHealthCheckInfos: {}", lastBeHealthCheckInfos); healthCheckScheduledTask = new HealthCheckScheduledTask(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java index 68569ebc3b..66c1868223 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java @@ -20,8 +20,8 @@ package org.openecomp.sdc.be.components.impl; -import org.openecomp.sdc.be.config.Configuration.DeploymentArtifactTypeConfig; +import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; public interface IDeploymentArtifactTypeConfigGetter { - DeploymentArtifactTypeConfig getDeploymentArtifactConfig(); + ArtifactTypeConfig getDeploymentArtifactConfig(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java index 94a7340ff7..33390e7e98 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java @@ -32,7 +32,6 @@ import java.util.function.Consumer; import java.util.function.Function; import org.apache.commons.lang3.StringEscapeUtils; -import org.apache.commons.lang3.text.translate.CharSequenceTranslator; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; @@ -48,6 +47,7 @@ import org.openecomp.sdc.common.util.GsonFactory; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Representer; import org.yaml.snakeyaml.resolver.Resolver; @@ -65,13 +65,20 @@ public final class ImportUtils { private static CustomResolver customResolver = new CustomResolver(); private static class CustomResolver extends Resolver { + @Override protected void addImplicitResolvers() { - // avoid implicit resolvers + // avoid implicit resolvers for strings that can be interpreted as boolean values + addImplicitResolver(Tag.STR, EMPTY, ""); + addImplicitResolver(Tag.STR, NULL, null); + addImplicitResolver(Tag.NULL, NULL, "~nN\0"); + addImplicitResolver(Tag.NULL, EMPTY, null); + addImplicitResolver(Tag.YAML, YAML, "!&*"); } } + @SuppressWarnings("unchecked") public static Either, ResultStatusEnum> getHeatParamsWithoutImplicitTypes(String heatDecodedPayload, String artifactType) { - Map heatData = (Map) new Yaml(new Constructor(), new Representer(), new DumperOptions(), customResolver).load(heatDecodedPayload); + Map heatData = (Map) new Yaml(new Constructor(), new Representer(), new DumperOptions(), customResolver).load(heatDecodedPayload); return getHeatParameters(heatData, artifactType); } @@ -82,6 +89,7 @@ public final class ImportUtils { public static final String VENDOR_NAME = "ATT (Tosca)"; public static final String VENDOR_RELEASE = "1.0.0.wd03"; public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE = LifecycleStateEnum.CERTIFIED; + public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT; public static final boolean NORMATIVE_TYPE_HIGHEST_VERSION = true; // public static final String ABSTRACT_CATEGORY = "Generic/Abstract"; public static final String ABSTRACT_CATEGORY_NAME = "Generic"; @@ -92,7 +100,6 @@ public final class ImportUtils { public static final List TOSCA_DEFINITION_VERSIONS = Arrays.asList(new String[] { "tosca_simple_yaml_1_0_0", "tosca_simple_profile_for_nfv_1_0_0", "tosca_simple_yaml_1_0" }); public static final List TOSCA_YML_CSAR_VALID_SUFFIX = Arrays.asList(new String[] { ".yml", ".yaml", ".csar" }); public static final String UI_JSON_PAYLOAD_NAME = "payloadName"; - public static final String ABSTRACT_NODE = "abstact"; } public enum ResultStatusEnum { @@ -172,10 +179,7 @@ public final class ImportUtils { else if (elementType == ToscaElementTypeEnum.ALL) { if (elementValue != null) { returnedList.add(String.valueOf(elementValue)); - } else { - returnedList.add(elementValue); - } - + } } } @@ -622,7 +626,7 @@ public final class ImportUtils { Iterator> propertiesNameValue = jsonProperties.entrySet().iterator(); while (propertiesNameValue.hasNext()) { Entry propertyNameValue = propertiesNameValue.next(); - if (propertyNameValue.getValue() instanceof Map) { + if (propertyNameValue.getValue() instanceof Map || propertyNameValue.getValue() instanceof List) { if (!artifactType.equals(ArtifactTypeEnum.HEAT_ENV.getType())) { @SuppressWarnings("unchecked") Either propertyStatus = createModuleHeatParameter((Map) propertyNameValue.getValue()); @@ -695,7 +699,7 @@ public final class ImportUtils { return null; } ToscaPropertyType validType = ToscaPropertyType.isValidType(type); - if (validType == null || validType.equals(ToscaPropertyType.MAP) || validType.equals(ToscaPropertyType.LIST)) { + if (validType == null || validType.equals(ToscaPropertyType.JSON) ||validType.equals(ToscaPropertyType.MAP) || validType.equals(ToscaPropertyType.LIST)) { return gson.toJson(value); } return value.toString(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java index 129110e13f..3b6e0f7a76 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java @@ -28,7 +28,7 @@ import java.util.stream.Collectors; import org.apache.commons.codec.binary.Base64; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.config.Configuration.DeploymentArtifactTypeConfig; +import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; @@ -79,7 +79,7 @@ public class InformationDeployedArtifactsBusinessLogic { * String message = (response.isLeft()) ? "informationalDeployable artifact {} is valid" : "informationalDeployable artifact {} is not valid"; log.debug(message, artifactInfo.getArtifactName()); return response; } * * private void validatePayloadContent(Wrapper responseFormatWrapper, ArtifactDefinition artifactToVerify) { ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactToVerify.getArtifactType()); if( artifactType == - * ArtifactTypeEnum.YANG_XML ){ String rawPayloadData = artifactToVerify.getPayloadData(); String xmlToParse = Base64.isBase64(rawPayloadData) ? new String(org.apache.commons.codec.binary.Base64.decodeBase64(rawPayloadData )) : rawPayloadData; + * ArtifactTypeEnum.YANG_XML ){ String rawPayloadData = artifactToVerify.getPayloadData(); String xmlToParse = new String(org.apache.commons.codec.binary.Base64.decodeBase64(rawPayloadData )); * * boolean isXmlValid = artifactBusinessLogic.isValidXml(xmlToParse.getBytes()); if( !isXmlValid ){ ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus. INVALID_XML, * artifactToVerify.getArtifactType()); responseFormatWrapper.setInnerElement(responseFormat); log.debug("Xml is not valid for artifact : {}", artifactToVerify.getArtifactName()); } } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java index 7d0624440e..8ffee1fd34 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java @@ -21,57 +21,95 @@ package org.openecomp.sdc.be.components.impl; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; - +import java.util.UUID; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.json.simple.JSONObject; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.ComponentInstInputsMap; +import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.operations.api.IResourceOperation; + import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.InputsOperation; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter; +import org.openecomp.sdc.be.resources.data.InputValueData; import org.openecomp.sdc.be.resources.data.InputsData; +import org.openecomp.sdc.be.resources.data.PropertyValueData; +import org.openecomp.sdc.be.resources.data.UniqueIdData; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor; import org.springframework.stereotype.Component; +import org.yaml.snakeyaml.Yaml; +import com.google.gson.Gson; +import com.thinkaurelius.titan.core.TitanVertex; + +import fj.Function; import fj.data.Either; @Component("inputsBusinessLogic") public class InputsBusinessLogic extends BaseBusinessLogic { private static final String CREATE_INPUT = "CreateInput"; + private static final String UPDATE_INPUT = "UpdateInput"; private static Logger log = LoggerFactory.getLogger(InputsBusinessLogic.class.getName()); - @Autowired - private IResourceOperation resourceOperation = null; - - @javax.annotation.Resource - private InputsOperation inputsOperation = null; + @javax.annotation.Resource private PropertyOperation propertyOperation = null; + @Autowired private ComponentsUtils componentsUtils; + + private static final String GET_INPUT = "get_input"; + + private static String ASSOCIATING_INPUT_TO_PROP = "AssociatingInputToComponentInstanceProperty"; + private Gson gson = new Gson(); + /** * associate inputs to a given component with paging @@ -82,28 +120,64 @@ public class InputsBusinessLogic extends BaseBusinessLogic { * @param amount * @return */ - public Either, ResponseFormat> getInputs(String userId, String componentId, String fromName, - int amount) { + public Either, ResponseFormat> getInputs(String userId, String componentId, String fromName, int amount) { Either resp = validateUserExists(userId, "get Inputs", false); if (resp.isRight()) { return Either.right(resp.right().value()); } - - Either, StorageOperationStatus> inputsEitherRes = inputsOperation - .getInputsOfComponent(componentId, fromName, amount); - if (inputsEitherRes.isRight()) { - if (inputsEitherRes.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - return Either.left(new ArrayList()); - } - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(inputsEitherRes.right().value()); - log.debug("Failed to get inputs under component {}, error: {}", componentId, actionStatus.name()); + + + ComponentParametersView filters = new ComponentParametersView(); + filters.disableAll(); + filters.setIgnoreInputs(false); + + Either getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name()); return Either.right(componentsUtils.getResponseFormat(actionStatus)); - + } + org.openecomp.sdc.be.model.Component component = getComponentEither.left().value(); + List inputs = component.getInputs(); + + return Either.left(inputs); - return Either.left(inputsEitherRes.left().value()); + } + + public Either, ResponseFormat> getComponentInstanceInputs(String userId, String componentId, String componentInstanceId,String fromName, int amount) { + + Either resp = validateUserExists(userId, "get Inputs", false); + + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + + ComponentParametersView filters = new ComponentParametersView(); + filters.disableAll(); + filters.setIgnoreInputs(false); + filters.setIgnoreComponentInstances(false); + filters.setIgnoreComponentInstancesInputs(false); + + Either getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name()); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + org.openecomp.sdc.be.model.Component component = getComponentEither.left().value(); + Map> ciInputs = component.getComponentInstancesInputs(); + if(!ciInputs.containsKey(componentInstanceId)){ + ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND; + log.debug("Failed to found component instance inputs {}, error: {}", componentInstanceId, actionStatus.name()); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + + return Either.left(ciInputs.get(componentInstanceId)); } @@ -116,62 +190,239 @@ public class InputsBusinessLogic extends BaseBusinessLogic { * @return */ - public Either, ResponseFormat> getComponentInstancePropertiesByInputId( - String userId, String instanceId, String inputId) { + public Either, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId, String instanceId, String inputId) { Either resp = validateUserExists(userId, "get Properties by input", false); if (resp.isRight()) { return Either.right(resp.right().value()); } + String parentId = componentId; + org.openecomp.sdc.be.model.Component component = null; + ComponentParametersView filters = new ComponentParametersView(); + filters.disableAll(); + filters.setIgnoreComponentInstances(false); + + if(!instanceId.equals(inputId)){ + + + Either getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters); + + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name()); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + component = getComponentEither.left().value(); + Optional ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(instanceId)).findAny(); + if(ciOp.isPresent()){ + parentId = ciOp.get().getComponentUid(); + } + + } + + filters.setIgnoreInputs(false); + + filters.setIgnoreComponentInstancesProperties(false); + filters.setIgnoreComponentInstancesInputs(false); + filters.setIgnoreProperties(false); + + Either getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters); + + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name()); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + component = getComponentEither.left().value(); + + Optional op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst(); + if(!op.isPresent()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus.name()); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + + return Either.left(getComponentInstancePropertiesByInputId(component, inputId)); - Either, StorageOperationStatus> propertiesEitherRes = inputsOperation - .getComponentInstancePropertiesByInputId(instanceId, inputId); - if (propertiesEitherRes.isRight()) { + } + + public Either updateInputValue(ComponentTypeEnum componentType, String componentId, InputDefinition input, String userId, boolean shouldLockComp, boolean inTransaction) { + + Either result = null; + org.openecomp.sdc.be.model.Component component = null; + + + try { + Either resp = validateUserExists(userId, "get input", false); - if (propertiesEitherRes.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - return Either.left(new ArrayList()); + if (resp.isRight()) { + result = Either.right(resp.right().value()); + return result; } - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(propertiesEitherRes.right().value()); - log.debug("Failed to get inputs under component {}, error: {}", instanceId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreInputs(false); + componentParametersView.setIgnoreUsers(false); - } + Either validateComponent = validateComponentExists(componentId, componentType, componentParametersView); - return Either.left(propertiesEitherRes.left().value()); + if (validateComponent.isRight()) { + result = Either.right(validateComponent.right().value()); + return result; + } + component = validateComponent.left().value(); - } + if (shouldLockComp) { + Either lockComponent = lockComponent(component, UPDATE_INPUT); + if (lockComponent.isRight()) { + result = Either.right(lockComponent.right().value()); + return result; + } + } - public Either, ResponseFormat> getInputsForComponentInput(String userId, - String componentId, String inputId) { - Either resp = validateUserExists(userId, "get Inputs by input", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } + Either canWork = validateCanWorkOnComponent(component, userId); + if (canWork.isRight()) { + result = Either.right(canWork.right().value()); + return result; + } - Either, StorageOperationStatus> inputsEitherRes = inputsOperation - .getComponentInstanceInputsByInputId(componentId, inputId); - if (inputsEitherRes.isRight()) { + Either, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); + if (allDataTypes.isRight()) { + result = Either.right(allDataTypes.right().value()); + return result; + } - if (inputsEitherRes.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - return Either.left(new ArrayList()); + Map dataTypes = allDataTypes.left().value(); + + Optional op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(input.getUniqueId())).findFirst(); + if(!op.isPresent()){ + ActionStatus actionStatus = ActionStatus.COMPONENT_NOT_FOUND; + log.debug("Failed to found input {} under component {}, error: {}", input.getUniqueId(), componentId, actionStatus.name()); + result = Either.right(componentsUtils.getResponseFormat(actionStatus)); + return result; + } + InputDefinition currentInput = op.get(); + + String innerType = null; + String propertyType = currentInput.getType(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + log.debug("The type of the property {} is {}", currentInput.getUniqueId(), propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = currentInput.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + innerType = propDef.getType(); } + // Specific Update Logic + + Either isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, input.getDefaultValue(), true, innerType, allDataTypes.left().value()); + + String newValue = currentInput.getDefaultValue(); + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (res == false) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + + currentInput.setDefaultValue(newValue); + + Either status = toscaOperationFacade.updateInputOfComponent(component, currentInput); + + if(status.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status.right().value()); + result = Either.right(componentsUtils.getResponseFormat(actionStatus, "")); + return result; + } + + + result = Either.left(status.left().value()); + + return result; + + + }finally { + + if (false == inTransaction) { + + if (result == null || result.isRight()) { + log.debug("Going to execute rollback on create group."); + titanDao.rollback(); + } else { + log.debug("Going to execute commit on create group."); + titanDao.commit(); + } - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(inputsEitherRes.right().value()); - log.debug("Failed to get inputs for input under component {}, error: {}", componentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + // unlock resource + if (shouldLockComp && component != null) { + graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); + } + + } - } - return Either.left(inputsEitherRes.left().value()); + } + + public Either, ResponseFormat> getInputsForComponentInput(String userId, String componentId, String inputId) { + Either resp = validateUserExists(userId, "get Properties by input", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + String parentId = componentId; + org.openecomp.sdc.be.model.Component component = null; + ComponentParametersView filters = new ComponentParametersView(); + filters.disableAll(); + filters.setIgnoreComponentInstances(false); + filters.setIgnoreInputs(false); + filters.setIgnoreComponentInstancesInputs(false); + filters.setIgnoreProperties(false); + + Either getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters); + + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name()); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + component = getComponentEither.left().value(); + + Optional op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst(); + if(!op.isPresent()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus.name()); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + + return Either.left(getComponentInstanceInputsByInputId(component, inputId)); } - public Either, ResponseFormat> createMultipleInputs(String userId, String componentId, - ComponentTypeEnum componentType, ComponentInstInputsMap componentInstInputsMapUi, boolean shouldLockComp, - boolean inTransaction) { + public Either, ResponseFormat> createMultipleInputs(String userId, String componentId, ComponentTypeEnum componentType, ComponentInstInputsMap componentInstInputsMapUi, boolean shouldLockComp, boolean inTransaction) { Either, ResponseFormat> result = null; org.openecomp.sdc.be.model.Component component = null; + + Map> inputsValueToCreateMap = new HashMap<>(); + Map> propertiesToCreateMap = new HashMap<>(); + Map inputsToCreate = new HashMap<>(); + try { Either resp = validateUserExists(userId, "get Properties by input", false); @@ -180,15 +431,15 @@ public class InputsBusinessLogic extends BaseBusinessLogic { return result; } - User user = resp.left().value(); ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); - componentParametersView.setIgnoreGroups(false); - componentParametersView.setIgnoreArtifacts(false); + componentParametersView.setIgnoreInputs(false); + componentParametersView.setIgnoreComponentInstancesInputs(false); + componentParametersView.setIgnoreComponentInstances(false); + componentParametersView.setIgnoreComponentInstancesProperties(false); componentParametersView.setIgnoreUsers(false); - Either validateComponent = validateComponentExists( - componentId, componentType, componentParametersView, userId, null, user); + Either validateComponent = validateComponentExists(componentId, componentType, componentParametersView); if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); @@ -210,40 +461,120 @@ public class InputsBusinessLogic extends BaseBusinessLogic { return result; } - Either, ResponseFormat> allDataTypes = getAllDataTypes( - applicationDataTypeCache); + Either, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); if (allDataTypes.isRight()) { result = Either.right(allDataTypes.right().value()); return result; } Map dataTypes = allDataTypes.left().value(); - - Either, StorageOperationStatus> createInputsResult = this.inputsOperation - .addInputsToComponent(componentId, componentType.getNodeType(), componentInstInputsMapUi, - dataTypes); - - if (createInputsResult.isRight()) { - ActionStatus actionStatus = componentsUtils - .convertFromStorageResponse(createInputsResult.right().value()); - log.debug("Failed to create inputs under component {}, error: {}", componentId, actionStatus.name()); - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); + Map origComponentMap = new HashMap<>(); + + + ////////////////////////////////////////////////////////////////////////////////////////////////////// + + List resList = new ArrayList(); + Map> newInputsMap = componentInstInputsMapUi.getComponentInstanceInputsMap(); + List ciList = component.getComponentInstances(); + if (newInputsMap != null && !newInputsMap.isEmpty()) { + int index = 0; + for (Entry> entry : newInputsMap.entrySet()) { + List inputsValueToCreate = new ArrayList<>(); + String compInstId = entry.getKey(); + + Optional op = ciList.stream().filter(ci -> ci.getUniqueId().equals(compInstId)).findAny(); + if(!op.isPresent()){ + ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; + log.debug("Failed to find component instance {} under component {}", compInstId, componentId); + result = Either.right(componentsUtils.getResponseFormat(actionStatus)); + return result; + } + ComponentInstance ci = op.get(); + String compInstname = ci.getNormalizedName(); + Either origComponentEither = getOriginComponent(ci, origComponentMap); + if(origComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(origComponentEither.right().value()); + log.debug("Failed to create inputs value under component {}, error: {}", componentId, actionStatus.name()); + result = Either.right(componentsUtils.getResponseFormat(actionStatus)); + return result; + } + org.openecomp.sdc.be.model.Component origComponent = origComponentEither.left().value(); + + List inputs = entry.getValue(); + + if (inputs != null && !inputs.isEmpty()) { + + for (InputDefinition input : inputs) { + + StorageOperationStatus status = addInputsToComponent(componentId, inputsToCreate, allDataTypes.left().value(), resList, index, inputsValueToCreate, compInstId, compInstname, origComponent, input); + if(status != StorageOperationStatus.OK ){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(status); + log.debug("Failed to create inputs value under component {}, error: {}", componentId, actionStatus.name()); + result = Either.right(componentsUtils.getResponseFormat(actionStatus)); + return result; + } + + } + } + if(!inputsValueToCreate.isEmpty()){ + inputsValueToCreateMap.put(compInstId, inputsValueToCreate); + } + } + + } + + Map> newInputsPropsMap = componentInstInputsMapUi.getComponentInstanceProperties(); + if (newInputsPropsMap != null && !newInputsPropsMap.isEmpty()) { + + result = createInputsFromProperty(component, origComponentMap, inputsToCreate, propertiesToCreateMap, dataTypes, resList, newInputsPropsMap); + + if (result.isRight()) { + log.debug("Failed to create inputs of resource for id {} error {}", component.getUniqueId(), result.right().value()); + return result; + } + resList = result.left().value(); + + } + + + Either, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.addInputsToComponent(inputsToCreate, component.getUniqueId()); + if(assotiateInputsEither.isRight()){ + log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value()))); return result; - } - result = Either.left(createInputsResult.left().value()); - + + Either>, StorageOperationStatus> assotiatePropsEither = toscaOperationFacade.addComponentInstancePropertiesToComponent(component, propertiesToCreateMap, component.getUniqueId()); + if(assotiatePropsEither.isRight()){ + log.debug("Failed to add inputs values under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value()))); + return result; + } + + Either>, StorageOperationStatus> addciInputsEither = toscaOperationFacade.addComponentInstanceInputsToComponent(inputsValueToCreateMap, component.getUniqueId()); + if(addciInputsEither.isRight()){ + log.debug("Failed to add inputs values under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value()))); + return result; + } + + + + + result = Either.left(resList); return result; + /////////////////////////////////////////////////////////////////////////////////////////// + } finally { if (false == inTransaction) { if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); - titanGenericDao.commit(); + titanDao.commit(); } } @@ -256,9 +587,59 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } - public Either, ResponseFormat> createInputs(String componentId, String userId, - ComponentTypeEnum componentType, List inputsDefinitions, boolean shouldLockComp, - boolean inTransaction) { + private StorageOperationStatus addInputsToComponent(String componentId, Map inputsToCreate, Map allDataTypes, List resList, int index, + List inputsValueToCreate, String compInstId, String compInstname, org.openecomp.sdc.be.model.Component origComponent, InputDefinition input) { + + Either, ResponseFormat> result; + String innerType = null; + InputDefinition oldInput = origComponent.getInputs().stream().filter(ciIn -> ciIn.getUniqueId().equals(input.getUniqueId())).findAny().get(); + String serviceInputName = compInstname + "_" + input.getName(); + input.setName(serviceInputName); + + JSONObject jobject = new JSONObject(); + jobject.put(GET_INPUT, input.getName()); + + ComponentInstanceInput inputValue = new ComponentInstanceInput(oldInput, jobject.toJSONString(), null); + + Either validatevalueEiter = validateInputValueBeforeCreate(inputValue, jobject.toJSONString(), false, innerType, allDataTypes); + if (validatevalueEiter.isRight()) { + + return validatevalueEiter.right().value(); + } + + String uniqueId = UniqueIdBuilder.buildResourceInstanceInputValueUid(compInstId, index++); + inputValue.setUniqueId(uniqueId); + inputValue.setValue(validatevalueEiter.left().value()); + + + input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, input.getName())); + input.setSchema(oldInput.getSchema()); + input.setDefaultValue(oldInput.getDefaultValue()); + input.setConstraints(oldInput.getConstraints()); + input.setDescription(oldInput.getDescription()); + input.setHidden(oldInput.isHidden()); + input.setImmutable(oldInput.isImmutable()); + input.setDefinition(oldInput.isDefinition()); + input.setRequired(oldInput.isRequired()); + inputsToCreate.put(input.getName(), input); + + + + List getInputValues = new ArrayList<>(); + GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition(); + getInputValueDataDefinition.setInputId(input.getUniqueId()); + getInputValueDataDefinition.setInputName(input.getName()); + getInputValues.add(getInputValueDataDefinition); + inputValue.setGetInputValues(getInputValues); + + inputsValueToCreate.add(inputValue); + input.setInputs(inputsValueToCreate); + + resList.add(input); + return StorageOperationStatus.OK; + } + + public Either, ResponseFormat> createInputs(String componentId, String userId, ComponentTypeEnum componentType, List inputsDefinitions, boolean shouldLockComp, boolean inTransaction) { Either, ResponseFormat> result = null; @@ -268,8 +649,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { if (inputsDefinitions != null && false == inputsDefinitions.isEmpty()) { if (shouldLockComp == true && inTransaction == true) { - BeEcompErrorManager.getInstance().logInternalFlowError("createGroups", - "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance().logInternalFlowError("createGroups", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock component since we are in a middle of another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; @@ -285,8 +665,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { User user = validateUserExists.left().value(); - Either validateComponent = validateComponentExists( - componentId, componentType, inTransaction, false); + Either validateComponent = validateComponentExists(componentId, componentType, null); if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); return result; @@ -305,8 +684,9 @@ public class InputsBusinessLogic extends BaseBusinessLogic { result = Either.right(canWork.right().value()); return result; } + Map inputs = inputsDefinitions.stream().collect(Collectors.toMap( o -> o.getName(), o -> o)); - result = createInputsInGraph(inputsDefinitions, component, user, inTransaction); + result = createInputsInGraph(inputs, component, user, inTransaction); } return result; @@ -317,10 +697,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic { if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); - titanGenericDao.commit(); + titanDao.commit(); } } @@ -333,66 +713,99 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } - public Either, ResponseFormat> createInputsInGraph(List inputsDefinitions, - org.openecomp.sdc.be.model.Component component, User user, boolean inTransaction) { - Either, ResponseFormat> result; - List inputs = new ArrayList(); - for (InputDefinition inputDefinition : inputsDefinitions) { - // String resourceId, String inputName, InputDefinition - // newInputDefinition, String userId, boolean inTransaction - Either createInput = createInput(component, user, - component.getComponentType(), inputDefinition.getName(), inputDefinition, inTransaction); - if (createInput.isRight()) { - log.debug("Failed to create group {}.", createInput); - result = Either.right(createInput.right().value()); - return result; + public Either, ResponseFormat> createInputsInGraph(Map inputs, org.openecomp.sdc.be.model.Component component, User user, boolean inTransaction) { + + List resList = inputs.values().stream().collect(Collectors.toList()); + Either, ResponseFormat> result = Either.left(resList); + List resourceProperties = component.getInputs(); + + if(inputs != null && !inputs.isEmpty()){ + Either, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); + if (allDataTypes.isRight()) { + return Either.right(allDataTypes.right().value()); + } + + Map dataTypes = allDataTypes.left().value(); + + for (Map.Entry inputDefinition : inputs.entrySet()) { + String inputName = inputDefinition.getKey(); + inputDefinition.getValue().setName(inputName); + + Either preparedInputEither = prepareAndValidateInputBeforeCreate(inputDefinition.getValue(), dataTypes); + if(preparedInputEither.isRight()){ + return Either.right(preparedInputEither.right().value()); + } + + } + if (resourceProperties != null) { + Map generatedInputs = resourceProperties.stream().collect(Collectors.toMap(i -> i.getName(), i -> i)); + Either, String> mergeEither = PropertyDataDefinition.mergeProperties(generatedInputs, inputs, false); + if(mergeEither.isRight()){ + return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value())); + } + inputs = mergeEither.left().value(); + } + + Either, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.createAndAssociateInputs(inputs, component.getUniqueId()); + if(assotiateInputsEither.isRight()){ + log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value()))); } - InputDefinition createdGroup = createInput.left().value(); - inputs.add(createdGroup); + result = Either.left(assotiateInputsEither.left().value()); + } - result = Either.left(inputs); + + return result; } /** * Delete input from service * - * @param component - * @param user * @param componentType * @param inputId - * @param inTransaction + * @param component + * @param user + * * @return */ - public Either deleteInput(String componentType, String componentId, String userId, String inputId, boolean inTransaction) { + public Either deleteInput(String componentType, String componentId, String userId, String inputId) { + Either deleteEither = null; if (log.isDebugEnabled()) log.debug("Going to delete input id: {}", inputId); // Validate user (exists) Either userEither = validateUserExists(userId, "Delete input", true); if (userEither.isRight()) { - return Either.right(userEither.right().value()); + deleteEither = Either.right(userEither.right().value()); + return deleteEither; } // Get component using componentType, componentId - Either componentEither = serviceOperation.getComponent(componentId, true); + + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreInputs(false); + componentParametersView.setIgnoreComponentInstances(false); + componentParametersView.setIgnoreComponentInstancesInputs(false); + componentParametersView.setIgnoreComponentInstancesProperties(false); + componentParametersView.setIgnoreUsers(false); + + Either componentEither = toscaOperationFacade.getToscaElement(componentId, componentParametersView); if (componentEither.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentEither.right().value()))); + deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentEither.right().value()))); + return deleteEither; } org.openecomp.sdc.be.model.Component component = componentEither.left().value(); // Validate inputId is child of the component - // And get the inputDefinition for the response - InputDefinition inputDefinition = null; Optional optionalInput = component.getInputs().stream(). // filter by ID filter(input -> input.getUniqueId().equals(inputId)). // Get the input findAny(); - if (optionalInput.isPresent()) { - inputDefinition = optionalInput.get(); - } else { + if (!optionalInput.isPresent()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId)); } @@ -400,75 +813,118 @@ public class InputsBusinessLogic extends BaseBusinessLogic { Either lockResultEither = lockComponent(componentId, component, "deleteInput"); if (lockResultEither.isRight()) { ResponseFormat responseFormat = lockResultEither.right().value(); - return Either.right(responseFormat); + deleteEither = Either.right(responseFormat); + return deleteEither; } // Delete input operations - Either deleteEither = Either.right(StorageOperationStatus.GENERAL_ERROR); + + InputDefinition inputForDelete = optionalInput.get(); try { - deleteEither = inputsOperation.deleteInput(inputId); - if (deleteEither.isRight()){ + StorageOperationStatus status = toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName()); + if(status != StorageOperationStatus.OK){ log.debug("Component id: {} delete input id: {} failed", componentId, inputId); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteEither.right().value()), component.getName())); + deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName())); + return deleteEither; } - return Either.left(inputDefinition); + + List inputsValue= getComponentInstanceInputsByInputId(component, inputId); + Map> insInputsMatToDelete = new HashMap<>(); + + if(inputsValue != null && !inputsValue.isEmpty()){ + for(ComponentInstanceInput inputValue: inputsValue){ + List inputList = null; + String ciId = inputValue.getComponentInstanceId(); + if(!insInputsMatToDelete.containsKey(ciId)){ + inputList = new ArrayList<>(); + }else{ + inputList = insInputsMatToDelete.get(ciId); + } + inputList.add(inputValue); + insInputsMatToDelete.put(ciId, inputList); + } + status = toscaOperationFacade.deleteComponentInstanceInputsToComponent(insInputsMatToDelete, component.getUniqueId()); + if(status != StorageOperationStatus.OK){ + log.debug("Component id: {} delete component instance input id: {} failed", componentId, inputId); + deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName())); + return deleteEither; + } + } + + // US848813 delete service input that relates to VL / CP property + + List propertiesValue = getComponentInstancePropertiesByInputId(component, inputId); + if(propertiesValue != null && !propertiesValue.isEmpty()){ + //propertyList = propertyValueStatus.left().value(); + for(ComponentInstanceProperty propertyValue: propertiesValue){ + + String value = propertyValue.getValue(); + Map mappedToscaTemplate = (Map) new Yaml().load(value); + + resetInputName(mappedToscaTemplate, inputForDelete.getName()); + + value = gson.toJson(mappedToscaTemplate); + propertyValue.setValue(value); + String compInstId = propertyValue.getComponentInstanceId(); + propertyValue.setRules(null); + List getInputsValues = propertyValue.getGetInputValues(); + if(getInputsValues != null && !getInputsValues.isEmpty()){ + Optional op = getInputsValues.stream().filter(gi -> gi.getInputId().equals(inputForDelete.getUniqueId())).findAny(); + if(op.isPresent()){ + getInputsValues.remove(op.get()); + } + } + propertyValue.setGetInputValues(getInputsValues); + if(status != StorageOperationStatus.OK){ + log.debug("Component id: {} delete component instance property {} id: {} failed", componentId, propertyValue.getUniqueId(), inputId); + deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName())); + return deleteEither; + } + Either findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(propertyValue.getPath(), propertyValue.getUniqueId(), propertyValue.getDefaultValue()); + if (findDefaultValue.isRight()) { + deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())))); + return deleteEither; + + } + String defaultValue = findDefaultValue.left().value(); + propertyValue.setDefaultValue(defaultValue); + log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue); + status = toscaOperationFacade.updateComponentInstanceProperty(component, compInstId, propertyValue); + if(status != StorageOperationStatus.OK){ + log.debug("Component id: {} update component instance property {} id: {} failed", componentId, propertyValue.getUniqueId(), inputId); + deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName())); + return deleteEither; + } + + } + } + + + deleteEither = Either.left(inputForDelete); + return deleteEither; } finally { - if (deleteEither.isRight()) { + if (deleteEither == null || deleteEither.isRight()) { log.debug("Component id: {} delete input id: {} failed", componentId, inputId); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("Component id: {} delete input id: {} success", componentId, inputId); - titanGenericDao.commit(); + titanDao.commit(); } unlockComponent(deleteEither, component); } } - /** - * Create new property on resource in graph - * - * @param resourceId - * @param propertyName - * @param newPropertyDefinition - * @param userId - * @return Either - */ - - private Either createInput(org.openecomp.sdc.be.model.Component component, - User user, ComponentTypeEnum componentType, String inputName, InputDefinition newInputDefinition, - boolean inTransaction) { - - Either result = null; - if (log.isDebugEnabled()) - log.debug("Going to create input {}", newInputDefinition); - - try { - - // verify property not exist in resource - List resourceProperties = component.getInputs(); - - if (resourceProperties != null) { - if (inputsOperation.isInputExist(resourceProperties, component.getUniqueId(), inputName)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, "")); - } - } + private Either prepareAndValidateInputBeforeCreate(InputDefinition newInputDefinition, Map dataTypes) { + - Either, ResponseFormat> allDataTypes = getAllDataTypes( - applicationDataTypeCache); - if (allDataTypes.isRight()) { - return Either.right(allDataTypes.right().value()); - } - - Map dataTypes = allDataTypes.left().value(); - - // validate input default values - Either defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, - dataTypes); - if (defaultValuesValidation.isRight()) { - return Either.right(defaultValuesValidation.right().value()); - } - // convert property - ToscaPropertyType type = getType(newInputDefinition.getType()); + // validate input default values + Either defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, dataTypes); + if (defaultValuesValidation.isRight()) { + return Either.right(defaultValuesValidation.right().value()); + } + // convert property + ToscaPropertyType type = getType(newInputDefinition.getType()); + if (type != null) { PropertyValueConverter converter = type.getConverter(); // get inner type String innerType = null; @@ -482,29 +938,81 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } String convertedValue = null; if (newInputDefinition.getDefaultValue() != null) { - convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, - allDataTypes.left().value()); + convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, dataTypes); newInputDefinition.setDefaultValue(convertedValue); } } + } + return Either.left(newInputDefinition); + } + + public boolean isInputExist(List inputs, String resourceUid, String inputName) { + + if (inputs == null) { + return false; + } + + for (InputDefinition propertyDefinition : inputs) { + String parentUniqueId = propertyDefinition.getParentUniqueId(); + String name = propertyDefinition.getName(); + + if (parentUniqueId.equals(resourceUid) && name.equals(inputName)) { + return true; + } + } - // add the new property to resource on graph - // need to get StorageOpaerationStatus and convert to ActionStatus - // from componentsUtils - Either either = inputsOperation.addInput(inputName, newInputDefinition, - component.getUniqueId(), componentType.getNodeType()); - if (either.isRight()) { - return Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(either.right().value()), component.getName())); + return false; + + } + + + public Either getInputsAndPropertiesForComponentInput(String userId, String componentId, String inputId, boolean inTransaction) { + Either result = null; + try { + + Either resp = validateUserExists(userId, "get Properties by input", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); } - // @TODO commit - // inputsOperation.getTitanGenericDao().commit(); - InputDefinition createdInputyDefinition = inputsOperation - .convertInputDataToInputDefinition(either.left().value()); - createdInputyDefinition.setName(inputName); - createdInputyDefinition.setParentUniqueId(component.getUniqueId()); + Either, StorageOperationStatus> propertiesEitherRes = null; + + ComponentParametersView filters = new ComponentParametersView(); + filters.disableAll(); + filters.setIgnoreComponentInstances(false); + filters.setIgnoreInputs(false); + filters.setIgnoreComponentInstancesInputs(false); + filters.setIgnoreComponentInstancesProperties(false); + filters.setIgnoreProperties(false); + Either getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name()); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + org.openecomp.sdc.be.model.Component component = getComponentEither.left().value(); + Optional op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst(); + if(!op.isPresent()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found input {} under component {}, error: {}", inputId, componentId, actionStatus.name()); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + + InputDefinition resObj = op.get(); + + List inputCIInput = getComponentInstanceInputsByInputId(component, inputId) ; + + resObj.setInputs(inputCIInput); + + + List inputProps = getComponentInstancePropertiesByInputId(component, inputId) ; + + resObj.setProperties(inputProps); + + + result = Either.left(resObj); - return Either.left(createdInputyDefinition); + return result; } finally { @@ -512,10 +1020,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic { if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); - titanGenericDao.commit(); + titanDao.commit(); } } @@ -523,4 +1031,318 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } } + + private List getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){ + List resList = new ArrayList<>(); + Map> ciPropertiesMap = component.getComponentInstancesProperties(); + if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){ + ciPropertiesMap.forEach(new BiConsumer>() { + @Override + public void accept(String s, List ciPropList) { + String ciName = ""; + Optional ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny(); + if(ciOp.isPresent()) + ciName = ciOp.get().getName(); + if (ciPropList != null && !ciPropList.isEmpty()) { + for(ComponentInstanceProperty prop: ciPropList){ + List inputsValues = prop.getGetInputValues(); + if(inputsValues != null && !inputsValues.isEmpty()){ + for(GetInputValueDataDefinition inputData: inputsValues){ + if(inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId().equals(inputId))){ + prop.setComponentInstanceId(s); + prop.setComponentInstanceName(ciName); + resList.add(prop); + break; + } + } + } + + } + } + } + }); + } + return resList; + + } + + private List getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){ + List resList = new ArrayList<>(); + Map> ciInputsMap = component.getComponentInstancesInputs(); + if(ciInputsMap != null && !ciInputsMap.isEmpty()){ + ciInputsMap.forEach(new BiConsumer>() { + @Override + public void accept(String s, List ciPropList) { + String ciName = ""; + Optional ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny(); + if(ciOp.isPresent()) + ciName = ciOp.get().getName(); + if (ciPropList != null && !ciPropList.isEmpty()) { + for(ComponentInstanceInput prop: ciPropList){ + List inputsValues = prop.getGetInputValues(); + if(inputsValues != null && !inputsValues.isEmpty()){ + for(GetInputValueDataDefinition inputData: inputsValues){ + if(inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId().equals(inputId))){ + prop.setComponentInstanceId(s); + prop.setComponentInstanceName(ciName); + resList.add(prop); + break; + } + } + } + + } + } + } + }); + } + return resList; + + } + + private Either getOriginComponent(ComponentInstance ci, Map origComponentMap){ + Either result = null; + String compInstname = ci.getNormalizedName(); + + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreInputs(false); + org.openecomp.sdc.be.model.Component origComponent = null; + if(!origComponentMap.containsKey(ci.getComponentUid())){ + Either componentFound = toscaOperationFacade.getToscaElement(ci.getComponentUid(), componentParametersView); + + if (componentFound.isRight()) { + result = Either.right(componentFound.right().value()); + return result; + } + origComponent = componentFound.left().value(); + origComponentMap.put(origComponent.getUniqueId(), origComponent); + }else{ + origComponent = origComponentMap.get(ci.getComponentUid()); + } + result = Either.left(origComponent); + return result; + } + + + + private Either, ResponseFormat> createInputsFromProperty(org.openecomp.sdc.be.model.Component component, Map origComponentMap, Map inputsToCreate, Map> propertiesToCreateMap, Map dataTypes, List resList, Map> newInputsPropsMap) { + List ciList = component.getComponentInstances(); + String componentId = component.getUniqueId(); + for (Entry> entry : newInputsPropsMap.entrySet()) { + List propertiesToCreate = new ArrayList<>(); + String compInstId = entry.getKey(); + List properties = entry.getValue(); + + Optional op = ciList.stream().filter(ci -> ci.getUniqueId().equals(compInstId)).findAny(); + if(!op.isPresent()){ + ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; + log.debug("Failed to find component instance {} under component {}", compInstId, componentId); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + ComponentInstance ci = op.get(); + String compInstname = ci.getNormalizedName(); + Either origComponentEither = getOriginComponent(ci, origComponentMap); + if(origComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(origComponentEither.right().value()); + log.debug("Failed to create inputs value under component {}, error: {}", componentId, actionStatus.name()); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + org.openecomp.sdc.be.model.Component origComponent = origComponentEither.left().value(); + + + //String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty()); + + String inputName = compInstname; + + if (properties != null && !properties.isEmpty()) { + for (ComponentInstancePropInput propInput : properties) { + Either createInputRes = createInputForComponentInstance(component, origComponent,ci, inputsToCreate, propertiesToCreate, dataTypes, inputName, propInput); + + if (createInputRes.isRight()) { + log.debug("Failed to create input of resource instance for id {} error {}", compInstId, createInputRes.right().value()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createInputRes.right().value()))); + + } + + resList.add(createInputRes.left().value()); + + } + propertiesToCreateMap.put(compInstId, propertiesToCreate); + } + + } + return Either.left(resList); + } + + private Either createInputForComponentInstance(org.openecomp.sdc.be.model.Component component,org.openecomp.sdc.be.model.Component orignComponent, ComponentInstance ci, Map inputsToCreate, List propertiesToCreate, Map dataTypes, String inputName, ComponentInstancePropInput propInput) { + String propertiesName = propInput.getPropertiesName() ; + PropertyDefinition selectedProp = propInput.getInput(); + String[] parsedPropNames = propInput.getParsedPropNames(); + + if(parsedPropNames != null){ + for(String str: parsedPropNames){ + inputName += "_" + str; + } + } else { + inputName += "_" + propInput.getName(); + } + + InputDefinition input = null; + ComponentInstanceProperty prop = propInput; + + if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){ + input = new InputDefinition(selectedProp); + }else{ + input = new InputDefinition(prop); + input.setName(inputName + "_" + prop.getName()); + + } + input.setName(inputName); + input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(component.getUniqueId(), input.getName())); + input.setInputPath(propertiesName); + + JSONObject jobject = new JSONObject(); + + + if(prop.getValue() == null || prop.getValue().isEmpty()){ + if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){ + + jobject = createJSONValueForProperty(parsedPropNames.length -1, parsedPropNames, jobject, inputName); + prop.setValue(jobject.toJSONString()); + + }else{ + + jobject.put(GET_INPUT, input.getName()); + prop.setValue(jobject.toJSONString()); + + } + + }else{ + + String value = prop.getValue(); + Object objValue = new Yaml().load(value); + if( objValue instanceof Map || objValue instanceof List ){ + if(propertiesName == null ||propertiesName.isEmpty()){ + jobject.put(GET_INPUT, input.getName()); + prop.setValue(jobject.toJSONString()); + prop.setRules(null); + + }else{ + Map mappedToscaTemplate = (Map) objValue; + createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName); + + String json = gson.toJson(mappedToscaTemplate); + prop.setValue(json); + prop.setRules(null); + } + + }else{ + jobject.put(GET_INPUT, input.getName()); + prop.setValue(jobject.toJSONString()); + prop.setRules(null); + } + + } + prop.setComponentInstanceId(ci.getUniqueId()); + prop.setComponentInstanceName(ci.getName()); + + List getInputValues = new ArrayList<>(); + GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition(); + getInputValueDataDefinition.setInputId(input.getUniqueId()); + getInputValueDataDefinition.setInputName(input.getName()); + getInputValues.add(getInputValueDataDefinition); + prop.setGetInputValues(getInputValues); + + propertiesToCreate.add(prop); + + inputsToCreate.put(input.getName(), input); + + return Either.left(input); + + } + + private JSONObject createJSONValueForProperty (int i, String [] parsedPropNames, JSONObject ooj, String inputName){ + + while(i >= 1){ + if( i == parsedPropNames.length -1){ + JSONObject jobProp = new JSONObject(); + jobProp.put(GET_INPUT, inputName); + ooj.put(parsedPropNames[i], jobProp); + i--; + return createJSONValueForProperty (i, parsedPropNames, ooj, inputName); + }else{ + JSONObject res = new JSONObject(); + res.put(parsedPropNames[i], ooj); + i --; + res = createJSONValueForProperty (i, parsedPropNames, res, inputName); + return res; + } + } + + return ooj; + } + + public void resetInputName(Map lhm1, String inputName){ + for (Map.Entry entry : lhm1.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + if (value instanceof String && ((String) value).equalsIgnoreCase(inputName) && key.equals(GET_INPUT)) { + value = ""; + lhm1.remove(key); + } else if (value instanceof Map) { + Map subMap = (Map)value; + resetInputName(subMap, inputName); + } else { + continue; + } + + } + } + + private Map createInputValue(Map lhm1, int index, String[] inputNames, String inputName){ + while(index < inputNames.length){ + if(lhm1.containsKey(inputNames[index])){ + Object value = lhm1.get(inputNames[index]); + if (value instanceof Map){ + if(index == inputNames.length -1){ + ((Map) value).put(GET_INPUT, inputName); + return ((Map) value); + + }else{ + index++; + return createInputValue((Map)value, index, inputNames, inputName); + } + }else{ + Map jobProp = new HashMap<>(); + if(index == inputNames.length -1){ + jobProp.put(GET_INPUT, inputName); + lhm1.put(inputNames[index], jobProp); + return lhm1; + }else{ + lhm1.put(inputNames[index], jobProp); + index++; + return createInputValue(jobProp, index, inputNames, inputName); + } + } + }else{ + Map jobProp = new HashMap<>(); + lhm1.put(inputNames[index], jobProp); + if(index == inputNames.length -1){ + jobProp.put(GET_INPUT, inputName); + return jobProp; + }else{ + index++; + return createInputValue(jobProp, index, inputNames, inputName); + } + } + } + return lhm1; + } + + + + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java index 780980ba08..e7d051290f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java @@ -113,7 +113,7 @@ public class InterfaceLifecycleTypeImportManager { operation.setDescription((String) opProp.get("description")); operations.put(entry.getKey(), operation); } - interfaceDef.setOperations(operations); + interfaceDef.setOperationsMap(operations); return interfaceDef; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java index 3a54513b0b..96f7eec2d8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java @@ -28,7 +28,6 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -40,6 +39,7 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.GroupingDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -47,9 +47,9 @@ import org.openecomp.sdc.be.model.operations.impl.ProductOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; @@ -89,6 +89,9 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { @Autowired private ICacheMangerOperation cacheManagerOperation; + + @Autowired + ToscaOperationFacade toscaOperationFacade; public Either createProduct(Product product, User user) { AuditingActionEnum actionEnum = AuditingActionEnum.CREATE_RESOURCE; @@ -136,7 +139,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { log.debug("Product name locked is {}, status = {}", product.getSystemName(), lockResult); try { - Either createProductEither = productOperation.createProduct(product); + Either createProductEither = toscaOperationFacade.createToscaComponent(product); if (createProductEither.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(createProductEither.right().value()), product, typeEnum); @@ -259,8 +262,10 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { return Either.right(resp.right().value()); } - Either dataModelResponse = productOperation.validateComponentNameExists(productName); - + Either dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(productName, null, ComponentTypeEnum.PRODUCT); + // DE242223 + titanDao.commit(); + if (dataModelResponse.isLeft()) { Map result = new HashMap<>(); result.put("isValid", dataModelResponse.left().value()); @@ -325,7 +330,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { contacts.add(modifierUserId); } - // passed - setting all contacts user ids to lowercase + // passed - setting all contacts userIds to lowercase List tempContacts = contacts.stream().map(e -> e.toLowerCase()).collect(Collectors.toList()); ValidationUtils.removeDuplicateFromList(tempContacts); product.setContacts(tempContacts); @@ -336,7 +341,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { private Either validateGrouping(User user, Product product, AuditingActionEnum actionEnum) { List categories = product.getCategories(); if (categories == null || categories.isEmpty()) { - log.debug("Grouping list is empty for product {}", product.getName()); + log.debug("Grouping list is empty for product: {}", product.getName()); return Either.left(true); } Map>> nonDuplicatedCategories = new HashMap>>(); @@ -345,7 +350,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { String catName = cat.getName(); if (ValidationUtils.validateStringNotEmpty(catName) == false) { // error missing cat name - log.debug("Missing category name for product {}", product.getName()); + log.debug("Missing category name for product: {}", product.getName()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.PRODUCT.getValue()); componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); return Either.right(responseFormat); @@ -382,7 +387,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { String groupName = group.getName(); if (ValidationUtils.validateStringNotEmpty(groupName) == false) { // error missing grouping for sub cat name and cat - log.debug("Missing or empty groupng name for sub-category {} for category {} in product {}", subCatName, catName, product.getName()); + log.debug("Missing or empty groupng name for sub-category: {} for categor: {} in product: {}", subCatName, catName, product.getName()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); return Either.right(responseFormat); @@ -390,7 +395,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { if (!subcatEntry.contains(groupName)) { subcatEntry.add(groupName); } else { - log.debug("Grouping [ {} ] already exist for category [ {} ] and subcategory [ {} ]", groupName, catName, subCatName); + log.debug("Grouping: {}, already exist for category: {} and subcategory: {}", groupName, catName, subCatName); } } } @@ -495,7 +500,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { return Either.right(eitherCreator.right().value()); } - Either storageStatus = productOperation.getComponent(productId, false); + Either storageStatus = toscaOperationFacade.getToscaElement(productId); if (storageStatus.isRight()) { log.debug("failed to get resource by id {}", productId); @@ -521,7 +526,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { return Either.right(eitherCreator.right().value()); } - Either storageStatus = productOperation.deleteProduct(productId, false); + Either storageStatus = toscaOperationFacade.deleteToscaComponent(productId); if (storageStatus.isRight()) { log.debug("failed to delete resource by id {}", productId); @@ -635,7 +640,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { return Either.right(responseFormat); } - Either storageStatus = productOperation.getComponent(productId, false); + Either storageStatus = toscaOperationFacade.getToscaElement(productId); if (storageStatus.isRight()) { if (storageStatus.right().value().equals(StorageOperationStatus.NOT_FOUND)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.name().toLowerCase())); @@ -645,8 +650,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { Product currentProduct = storageStatus.left().value(); - if (!ComponentValidationUtils.canWorkOnComponent(productId, productOperation, user.getUserId())) { - log.info("Restricted operation for user {} on product {}", user.getUserId(), currentProduct.getCreatorUserId()); + if (!ComponentValidationUtils.canWorkOnComponent(productId, toscaOperationFacade, user.getUserId())) { + log.info("Restricted operation for user: {}, on product: {}" , user.getUserId(), currentProduct.getCreatorUserId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } @@ -663,14 +668,13 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { return Either.right(lockResult.right().value()); } try { - Either updateResponse = productOperation.updateComponent(productToUpdate, true); + Either updateResponse = toscaOperationFacade.updateToscaElement(productToUpdate); if (updateResponse.isRight()) { - productOperation.rollback(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Update Product Metadata"); + toscaOperationFacade.rollback(); log.debug("failed to update product {}", productToUpdate.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } - productOperation.commit(); + toscaOperationFacade.commit(); return Either.left(updateResponse.left().value()); } finally { graphLockOperation.unlockComponent(productId, NodeTypeEnum.Product); @@ -791,7 +795,6 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { private Either validateAndUpdateCategory(User user, Product currentProduct, Product updatedProduct) { List categoryUpdated = updatedProduct.getCategories(); - List categoryCurrent = currentProduct.getCategories(); Either validatCategoryResponse = validateGrouping(user, updatedProduct, null); if (validatCategoryResponse.isRight()) { @@ -854,7 +857,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { if (resp.isRight()) { return Either.right(resp.right().value()); } - Either storageStatus = productOperation.getProductByNameAndVersion(productName, productVersion, false); + Either storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.PRODUCT, productName, productVersion); if (storageStatus.isRight()) { log.debug("failed to get service by name {} and version {}", productName, productVersion); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.PRODUCT), productName)); @@ -881,7 +884,11 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { this.cacheManagerOperation = cacheManagerOperation; } - public void setProductOperation(ProductOperation productOperation) { - this.productOperation = productOperation; + @Override + public Either getUiComponentDataTransferByComponentId(String componentId, + List dataParamsToReturn) { + // TODO Auto-generated method stub + return null; } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java index 46188012d8..ab0969358c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java @@ -22,7 +22,6 @@ package org.openecomp.sdc.be.components.impl; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.operations.impl.ComponentOperation; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Component; @@ -42,18 +41,10 @@ public class ProductComponentInstanceBusinessLogic extends ComponentInstanceBusi return NodeTypeEnum.Service; } - @Override - protected ComponentOperation getContainerComponentOperation() { - return productOperation; - } - - @Override - protected ComponentOperation getCompInstOriginComponentOperation() { - return serviceOperation; - } - @Override protected ComponentTypeEnum getComponentTypeOfComponentInstance() { + // TODO Auto-generated method stub return ComponentTypeEnum.SERVICE_INSTANCE; } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java index 1e6b1c1d82..e0d531d622 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java @@ -20,40 +20,60 @@ package org.openecomp.sdc.be.components.impl; +import java.lang.reflect.Type; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.function.Supplier; import javax.servlet.ServletContext; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.IComplexDefaultValue; +import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IResourceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter; +import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter; +import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator; import org.openecomp.sdc.be.resources.data.EntryData; import org.openecomp.sdc.be.resources.data.PropertyData; import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.reflect.TypeToken; + import fj.data.Either; @Component("propertyBusinessLogic") @@ -63,11 +83,15 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { private static Logger log = LoggerFactory.getLogger(PropertyBusinessLogic.class.getName()); + private static final String EMPTY_VALUE = null; + + private DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); + @javax.annotation.Resource private IResourceOperation resourceOperation = null; - @javax.annotation.Resource - private PropertyOperation propertyOperation = null; + @Autowired + private ToscaOperationFacade toscaOperationFacade; @javax.annotation.Resource private ComponentsUtils componentsUtils; @@ -114,7 +138,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { try { // Get the resource from DB - Either status = getResource(resourceId); + Either status = toscaOperationFacade.getToscaElement(resourceId); if (status.isRight()) { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); return result; @@ -132,8 +156,8 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { List resourceProperties = resource.getProperties(); if (resourceProperties != null) { - if (propertyOperation.isPropertyExist(resourceProperties, resourceId, propertyName)) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, "")); + if (isPropertyExist(resourceProperties, resourceId, propertyName, newPropertyDefinition.getType())) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, propertyName)); return result; } } @@ -177,13 +201,13 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { // add the new property to resource on graph // need to get StorageOpaerationStatus and convert to ActionStatus // from componentsUtils - Either either = propertyOperation.addProperty(propertyName, newPropertyDefinition, resourceId); + Either either = toscaOperationFacade.addPropertyToResource(propertyName, newPropertyDefinition, resource); if (either.isRight()) { result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); return result; } - PropertyDefinition createdPropertyDefinition = propertyOperation.convertPropertyDataToPropertyDefinition(either.left().value(), propertyName, resourceId); + PropertyDefinition createdPropertyDefinition = either.left().value(); EntryData property = new EntryData(propertyName, createdPropertyDefinition); result = Either.left(property); return result; @@ -202,7 +226,6 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { * @param resourceId * @param propertyId * @param userId - * TODO * @return */ public Either, ResponseFormat> getProperty(String resourceId, String propertyId, String userId) { @@ -213,7 +236,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { } // Get the resource from DB - Either status = getResource(resourceId); + Either status = toscaOperationFacade.getToscaElement(resourceId); if (status.isRight()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); } @@ -244,9 +267,9 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either, ResponseFormat> deleteProperty(String resourceId, String propertyId, String userId) { + public Either, ResponseFormat> deleteProperty(String resourceId, String propertyId, String userId) { - Either, ResponseFormat> result = null; + Either, ResponseFormat> result = null; Either resp = validateUserExists(userId, "delete Property", false); if (resp.isRight()) { @@ -263,12 +286,12 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { try { // Get the resource from DB - Either status = getResource(resourceId); - if (status.isRight()) { + Either getResourceRes = toscaOperationFacade.getToscaElement(resourceId); + if (getResourceRes.isRight()) { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); return result; } - Resource resource = status.left().value(); + Resource resource = getResourceRes.left().value(); // verify that resource is checked-out and the user is the last // updater @@ -283,21 +306,14 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { result = Either.right(statusGetProperty.right().value()); return result; } - String propertyName = statusGetProperty.left().value().getKey(); - // delete property of resource from graph - // TODO: need to get StorageOperationStatus - Either either = propertyOperation.deleteProperty(propertyId); - // Either either = - // propertyOperation.deletePropertyFromGraph(propertyId); - if (either.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); + StorageOperationStatus status = toscaOperationFacade.deletePropertyOfResource(resource, statusGetProperty.left().value().getKey()); + if (status != StorageOperationStatus.OK) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), resource.getName())); return result; } // propertyOperation.getTitanGenericDao().commit(); - PropertyDefinition createdPropertyDefinition = propertyOperation.convertPropertyDataToPropertyDefinition(either.left().value(), propertyName, resourceId); - EntryData property = new EntryData(propertyName, createdPropertyDefinition); - result = Either.left(property); + result = Either.left(statusGetProperty.left().value()); return result; } finally { @@ -320,14 +336,12 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { Either, ResponseFormat> result = null; - // Get the resource from DB - Either status = getResource(resourceId); + Either status = toscaOperationFacade.getToscaElement(resourceId); if (status.isRight()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); } Resource resource = status.left().value(); - // verify that resource is checked-out and the user is the last updater if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } @@ -340,8 +354,6 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { } try { - - // verify property exist in resource Either, ResponseFormat> statusGetProperty = getProperty(resourceId, propertyId, userId); if (statusGetProperty.isRight()) { result = Either.right(statusGetProperty.right().value()); @@ -355,37 +367,222 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { return result; } Map dataTypes = allDataTypes.left().value(); - // validate property default values + Either defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes); if (defaultValuesValidation.isRight()) { result = Either.right(defaultValuesValidation.right().value()); return result; } - // add the new property to resource on graph - // TODO: convert TitanOperationStatus to Storgae... - Either either = propertyOperation.updateProperty(propertyId, newPropertyDefinition, dataTypes); - // Either either = - // propertyOperation.updatePropertyFromGraph(propertyId, - // newPropertyDefinition); + Either either = handleProperty(propertyId, newPropertyDefinition, dataTypes); if (either.isRight()) { log.debug("Problem while updating property with id {}. Reason - {}", propertyId, either.right().value()); result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); return result; - // return Either.right(ActionStatus.GENERAL_ERROR); } - PropertyDefinition createdPropertyDefinition = propertyOperation.convertPropertyDataToPropertyDefinition(either.left().value(), propertyName, resourceId); - EntryData property = new EntryData(propertyName, createdPropertyDefinition); + + either = toscaOperationFacade.updatePropertyOfResource(resource, newPropertyDefinition); + if (either.isRight()) { + result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); + return result; + } + + EntryData property = new EntryData(propertyName, either.left().value()); result = Either.left(property); return result; } finally { commitOrRollback(result); - // unlock component graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); } } + + private boolean isPropertyExist(List properties, String resourceUid, String propertyName, String propertyType) { + boolean result = false; + if (!CollectionUtils.isEmpty(properties)) { + for (PropertyDefinition propertyDefinition : properties) { + + if ( propertyDefinition.getName().equals(propertyName) && + (propertyDefinition.getParentUniqueId().equals(resourceUid) || !propertyDefinition.getType().equals(propertyType)) ) { + result = true; + break; + } + } + } + return result; + } + + private PropertyDefinition convertPropertyDataToPropertyDefinition(PropertyData propertyDataResult, String propertyName, String resourceId) { + log.debug("The object returned after create property is {}", propertyDataResult); + PropertyDefinition propertyDefResult = new PropertyDefinition(propertyDataResult.getPropertyDataDefinition()); + propertyDefResult.setConstraints(convertConstraints(propertyDataResult.getConstraints())); + propertyDefResult.setName(propertyName); + propertyDefResult.setParentUniqueId(resourceId); + return propertyDefResult; + } + + private List convertConstraints(List constraints) { + + if (constraints == null || constraints.size() == 0) { + return null; + } + + List list = new ArrayList(); + Type constraintType = new TypeToken() { + }.getType(); + + Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); + + for (String constraintJson : constraints) { + PropertyConstraint propertyConstraint = gson.fromJson(constraintJson, constraintType); + list.add(propertyConstraint); + } + + return list; + } + + private Either handleProperty(String propertyId, PropertyDefinition newPropertyDefinition, Map dataTypes) { + + StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(newPropertyDefinition, dataTypes); + if (validateAndUpdateProperty != StorageOperationStatus.OK) { + return Either.right(validateAndUpdateProperty); + } + + return Either.left(newPropertyDefinition); + } + + private StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map dataTypes) { + + log.trace("Going to validate property type and value. {}", propertyDefinition); + + String propertyType = propertyDefinition.getType(); + String value = propertyDefinition.getDefaultValue(); + + ToscaPropertyType type = getType(propertyType); + if (type == null) { + + DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); + if (dataTypeDefinition == null) { + log.debug("The type {} of property cannot be found.", propertyType); + return StorageOperationStatus.INVALID_TYPE; + } + + StorageOperationStatus status = validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes); + + return status; + + } + String innerType = null; + + Either checkInnerType = getInnerType(type, () -> propertyDefinition.getSchema()); + if (checkInnerType.isRight()) { + return StorageOperationStatus.INVALID_TYPE; + } + innerType = checkInnerType.left().value(); + + log.trace("After validating property type {}", propertyType); + + boolean isValidProperty = isValidValue(type, value, innerType, dataTypes); + if (false == isValidProperty) { + log.info("The value {} of property from type {} is invalid", value, type); + return StorageOperationStatus.INVALID_VALUE; + } + + PropertyValueConverter converter = type.getConverter(); + + if (isEmptyValue(value)) { + log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE); + propertyDefinition.setDefaultValue(EMPTY_VALUE); + } else if (false == isEmptyValue(value)) { + String convertedValue = converter.convert(value, innerType, dataTypes); + propertyDefinition.setDefaultValue(convertedValue); + } + return StorageOperationStatus.OK; + } + + protected StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType, + + String value, DataTypeDefinition dataTypeDefinition, Map dataTypes) { + + ImmutablePair validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes); + + if (validateResult.right.booleanValue() == false) { + log.debug("The value {} of property from type {} is invalid", propertyType, propertyType); + return StorageOperationStatus.INVALID_VALUE; + } + + JsonElement jsonElement = validateResult.left; + + log.trace("Going to update value in property definition {} {}" , propertyDefinition.getName() , (jsonElement != null ? jsonElement.toString() : null)); + + updateValue(propertyDefinition, jsonElement); + + return StorageOperationStatus.OK; + } + + protected void updateValue(IComplexDefaultValue propertyDefinition, JsonElement jsonElement) { + + propertyDefinition.setDefaultValue(getValueFromJsonElement(jsonElement)); + + } + + protected String getValueFromJsonElement(JsonElement jsonElement) { + String value = null; + + if (jsonElement == null || jsonElement.isJsonNull()) { + value = EMPTY_VALUE; + } else { + if (jsonElement.toString().isEmpty()) { + value = ""; + } else { + value = jsonElement.toString(); + } + } + + return value; + } + + protected Either getInnerType(ToscaPropertyType type, Supplier schemeGen) { + String innerType = null; + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + + SchemaDefinition def = schemeGen.get();// propDataDef.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + innerType = propDef.getType(); + } + return Either.left(innerType); + } + protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map dataTypes) { + if (isEmptyValue(value)) { + return true; + } + + PropertyTypeValidator validator = type.getValidator(); + + boolean isValid = validator.isValid(value, innerType, dataTypes); + if (true == isValid) { + return true; + } else { + return false; + } + + } + + public boolean isEmptyValue(String value) { + if (value == null) { + return true; + } + return false; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java index ddc03e14e8..ffcb87c99c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java @@ -20,10 +20,14 @@ package org.openecomp.sdc.be.components.impl; +import static org.openecomp.sdc.be.tosca.CsarUtils.ARTIFACTS_PATH; +import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN; + import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -40,8 +44,10 @@ import java.util.stream.Collectors; import javax.servlet.ServletContext; import org.apache.commons.codec.binary.Base64; +import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; -import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperation; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; @@ -49,13 +55,17 @@ import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum; import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; +import org.openecomp.sdc.be.config.Configuration.VfModuleProperty; +import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum; import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils; +import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; +import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; @@ -64,15 +74,14 @@ import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.info.ArtifactTemplateInfo; import org.openecomp.sdc.be.info.MergedArtifactInfo; import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GetInputValueInfo; import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.GroupProperty; import org.openecomp.sdc.be.model.GroupTypeDefinition; @@ -84,6 +93,7 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Operation; import org.openecomp.sdc.be.model.ParsedToscaYamlInfo; import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.RelationshipImpl; import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.RequirementDefinition; @@ -98,29 +108,24 @@ import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.heat.HeatParameterType; -import org.openecomp.sdc.be.model.operations.api.IArtifactOperation; import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation; -import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation; import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.api.IPropertyOperation; -import org.openecomp.sdc.be.model.operations.api.IResourceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.CapabilityInstanceOperation; import org.openecomp.sdc.be.model.operations.impl.CsarOperation; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.be.model.operations.impl.GroupOperation; import org.openecomp.sdc.be.model.operations.impl.InputsOperation; -import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; -import org.openecomp.sdc.be.resources.data.ResourceMetadataData; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.servlets.RepresentationUtils; +import org.openecomp.sdc.be.tosca.CsarUtils; +import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo; +import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; import org.openecomp.sdc.be.user.IUserBusinessLogic; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.be.user.UserBusinessLogic; @@ -129,6 +134,8 @@ import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.config.EcompErrorName; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.kpi.api.ASDCKpiApi; import org.openecomp.sdc.common.util.GeneralUtility; @@ -140,9 +147,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.WebApplicationContext; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; -import org.yaml.snakeyaml.representer.Representer; -import org.yaml.snakeyaml.resolver.Resolver; import com.google.gson.Gson; import com.google.gson.JsonElement; @@ -156,13 +160,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes"; public static final String INITIAL_VERSION = "0.1"; - Pattern STR_REPLACE_PATTERN = Pattern.compile("^[ ]*\\{[ ]*" + "str_replace" + "="); - Pattern TOKEN_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "token" + "="); - Pattern GET_PROPERTY_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_property" + "="); - Pattern CONCAT_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "concat" + "="); + private Pattern STR_REPLACE_PATTERN = Pattern.compile("^[ ]*\\{[ ]*" + "str_replace" + "="); + private Pattern TOKEN_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "token" + "="); + private Pattern GET_PROPERTY_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_property" + "="); + private Pattern CONCAT_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "concat" + "="); private static Logger log = LoggerFactory.getLogger(ResourceBusinessLogic.class.getName()); + private static Pattern pattern = Pattern.compile("\\..(.*?)\\.."); + + /** + * Default constructor + */ public ResourceBusinessLogic() { log.debug("ResourceBusinessLogic started"); } @@ -173,9 +182,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { @Autowired private IInterfaceLifecycleOperation interfaceTypeOperation = null; - @Autowired - private IComponentInstanceOperation componentInstanceOperation; - @Autowired private LifecycleBusinessLogic lifecycleBusinessLogic; @@ -193,23 +199,21 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { @Autowired private GroupBusinessLogic groupBusinessLogic; + @Autowired private InputsBusinessLogic inputsBusinessLogic; @javax.annotation.Resource private InputsOperation inputOperation; - @Autowired - private GroupOperation groupOperation; + // @Autowired + // private GroupOperation groupOperation; @Autowired private IHeatParametersOperation heatParametersOperation; - @Autowired - private IArtifactOperation artifactOperation; - - @Autowired - private CapabilityInstanceOperation capabilityInstanceOperation; + // @Autowired + // private IArtifactOperation artifactOperation; @Autowired private CompositionBusinessLogic compositionBusinessLogic; @@ -217,6 +221,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { @Autowired private ICacheMangerOperation cacheManagerOperation; + @Autowired + private ApplicationDataTypeCache dataTypeCache; + private Gson gson = new Gson(); public CsarOperation getCsarOperation() { @@ -227,14 +234,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { this.csarOperation = csarOperation; } - public IResourceOperation getResourceOperation() { - return this.resourceOperation; - } - - public void setResourceOperation(ResourceOperation resourceOperation) { - this.resourceOperation = resourceOperation; - } - public LifecycleBusinessLogic getLifecycleBusinessLogic() { return lifecycleBusinessLogic; } @@ -300,7 +299,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (resp.isRight()) { return Either.right(resp.right().value()); } - IResourceOperation dataModel = getResourceOperation(); Boolean isHighest = null; switch (highestFilter) { case ALL: @@ -314,17 +312,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { default: break; } + Either, StorageOperationStatus> getResponse = toscaOperationFacade.getAllCertifiedResources(getAbstract, isHighest); - Either, StorageOperationStatus> dataModelResponse = dataModel.getAllCertifiedResources(getAbstract, isHighest); - - if (dataModelResponse.isLeft()) { - log.debug("Retrived Resource successfully."); - return Either.left(dataModelResponse.left().value()); + if (getResponse.isRight()) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResponse.right().value()))); } - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value())); - - return Either.right(responseFormat); + return Either.left(getResponse.left().value()); } public Either, ResponseFormat> validateResourceNameExists(String resourceName, ResourceTypeEnum resourceTypeEnum, String userId) { @@ -334,9 +328,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.right(resp.right().value()); } - IResourceOperation dataModel = getResourceOperation(); - - Either dataModelResponse = dataModel.validateResourceNameExists(resourceName, resourceTypeEnum); + Either dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE); + // DE242223 + titanDao.commit(); if (dataModelResponse.isLeft()) { Map result = new HashMap<>(); @@ -350,7 +344,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.right(responseFormat); } - public Either createResource(Resource resource, User user, Map csarUIPayload, String payloadName) { + public Either createResource(Resource resource, AuditingActionEnum auditingAction, User user, Map csarUIPayload, String payloadName) { Either createResourceResponse = validateResourceBeforeCreate(resource, user, false); if (createResourceResponse.isRight()) { return createResourceResponse; @@ -366,26 +360,26 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (csarUUID != null && !csarUUID.isEmpty()) { // check if VF with the same Csar UUID or with he same name already // exists - Either, StorageOperationStatus> validateCsarUuidUniquenessRes = resourceOperation.validateCsarUuidUniqueness(csarUUID); + Either validateCsarUuidUniquenessRes = toscaOperationFacade.validateCsarUuidUniqueness(csarUUID); if (validateCsarUuidUniquenessRes.isRight()) { log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, resource.getSystemName()); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateCsarUuidUniquenessRes.right().value()))); } - List existingResourceRes = validateCsarUuidUniquenessRes.left().value(); - if (existingResourceRes != null && existingResourceRes.size() > 0) { - log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF {}", resource.getSystemName(), csarUUID, existingResourceRes.get(0).getMetadataDataDefinition().getName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, existingResourceRes.get(0).getMetadataDataDefinition().getName()); - componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null); + Integer existingResourceRes = validateCsarUuidUniquenessRes.left().value(); + if (existingResourceRes.intValue() > 0) { + log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", resource.getSystemName(), csarUUID); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID); + componentsUtils.auditResource(errorResponse, user, resource, "", "", auditingAction, null); return Either.right(errorResponse); } log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID); - createResourceResponse = createResourceFromCsar(resource, user, AuditingActionEnum.CREATE_RESOURCE, false, Either.left(csarUIPayload), csarUUID); + createResourceResponse = createResourceFromCsar(resource, user, Either.left(csarUIPayload), csarUUID); return createResourceResponse; } - return createResourceByDao(resource, user, AuditingActionEnum.CREATE_RESOURCE, false); + return createResourceByDao(resource, user, auditingAction, false, false, null); } public Either validateAndUpdateResourceFromCsar(Resource resource, User user, Map csarUIPayload, String payloadName, String resourceUniqueId) { @@ -448,7 +442,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { // "Error: The VSP with UUID %1 was already imported for VF %2. Please // select another or update the existing VF." %1 - csarUUID, %2 - VF // name - Either resourceLinkedToCsarRes = resourceOperation.getLatestResourceByCsarOrName(csarUUID, resource.getSystemName()); + Either resourceLinkedToCsarRes = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName()); if (resourceLinkedToCsarRes.isRight()) { if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) { log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID, resource.getSystemName()); @@ -476,7 +470,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } private Resource getResourceByUniqueId(Wrapper responseWrapper, String resourceUniqueId) { - Either oldResourceRes = resourceOperation.getResource(resourceUniqueId); + Either oldResourceRes = toscaOperationFacade.getToscaElement(resourceUniqueId); if (oldResourceRes.isRight()) { log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId, oldResourceRes.right().value()); responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(oldResourceRes.right().value()))); @@ -505,7 +499,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } String lockedResourceId = oldRresource.getUniqueId(); - List createdArtifacts = new ArrayList(); + List createdArtifacts = new ArrayList<>(); + List nodeTypesNewCreatedArtifacts = new ArrayList<>(); Either, StorageOperationStatus> csar = null; if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) { @@ -542,29 +537,33 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } Either result = null; + String yamlFileName = toscaYamlCsarStatus.left().value().getKey(); + Either, ResponseFormat> parseNodeTypeInfoYamlEither = null; try { Either, ResponseFormat> prepareForUpdate = null; Resource preparedResource = null; - if (isUpdateYaml) { - prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, user, true, false); + Either>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(csar.left().value(), csarUUID, yamlFileName, oldRresource, user, true); + if (findNodeTypesArtifactsToHandleRes.isRight()) { + log.debug("failed to find node types for update with artifacts during import csar {}. ", csarUUID); + result = Either.right(findNodeTypesArtifactsToHandleRes.right().value()); + return result; + } + Map>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes.left().value(); + if (isUpdateYaml || !nodeTypesArtifactsToHandle.isEmpty()) { + prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, user, true, false); if (prepareForUpdate.isRight()) { log.debug("Failed to prepare resource for update : {}", prepareForUpdate.right().value()); result = Either.right(prepareForUpdate.right().value()); return result; } preparedResource = prepareForUpdate.left().value().left; - String yamlFileName = toscaYamlCsarStatus.left().value().getKey(); + String yamlFileContents = toscaYamlCsarStatus.left().value().getValue(); log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents); - // Either, ResponseFormat> - // parseNodeTypeInfoYamlEither = - // createResourcesFromYamlNodeTypesList(yamlFileName,preparedResource, - // yamlFileContents, user,false); - - Either, ResponseFormat> parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, user, yamlFileContents, csar.left().value(), false); + parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, user, yamlFileContents, csar.left().value(), false, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts); if (parseNodeTypeInfoYamlEither.isRight()) { ResponseFormat responseFormat = parseNodeTypeInfoYamlEither.right().value(); componentsUtils.auditResource(responseFormat, user, preparedResource, "", "", updateResource, null); @@ -638,12 +637,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { result = Either.right(dataModelResponse.right().value()); return result; } - preparedResource = dataModelResponse.left().value(); - } - Either createdCsarArtifactsEither = handleCsarArtifacts(preparedResource, user, csarUUID, csar.left().value(), createdArtifacts, ArtifactOperation.Update, false, true); + Either createdCsarArtifactsEither = handleCsarArtifacts(preparedResource, user, csarUUID, csar.left().value(), createdArtifacts, + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), false, true); if (createdCsarArtifactsEither.isRight()) { return createdCsarArtifactsEither; @@ -658,8 +656,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } finally { if (result == null || result.isRight()) { log.warn("operation failed. do rollback"); - titanGenericDao.rollback(); - if (!createdArtifacts.isEmpty()) { + titanDao.rollback(); + if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) { + createdArtifacts.addAll(nodeTypesNewCreatedArtifacts); StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts); if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes); @@ -669,7 +668,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } else { log.debug("operation success. do commit"); - titanGenericDao.commit(); + titanDao.commit(); } log.debug("unlock resource {}", lockedResourceId); graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource); @@ -677,7 +676,318 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } - public Either createResourceFromCsar(Resource resource, User user, AuditingActionEnum createResource, boolean inTransaction, Either, StorageOperationStatus> csarUIPayload, String csarUUID) { + private Either>>, ResponseFormat> findNodeTypesArtifactsToHandle(Map csar, String csarUUID, String yamlFileName, Resource oldResource, User user, + boolean inTransaction) { + + Map> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar); + Map>> nodeTypesArtifactsToHandle = new HashMap<>(); + Either>>, ResponseFormat> nodeTypesArtifactsToHandleRes; + + try { + nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle); + List>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlFileName, oldResource.getSystemName()); + validateNodeTypeIdentifiers(extractedVfcsArtifacts, extractedVfcToscaNames); + Either>, ResponseFormat> curNodeTypeArtifactsToHandleRes = null; + EnumMap> curNodeTypeArtifactsToHandle = null; + log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(), csarUUID); + + for (ImmutablePair>, String> currVfcToscaNameEntry : extractedVfcToscaNames) { + String currVfcToscaName = currVfcToscaNameEntry.getValue(); + log.debug("Going to fetch node type with tosca name {}. ", currVfcToscaName); + + Either curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName); + Resource curNodeType = null; + if (curVfcRes.isRight() && curVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) { + log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, curVfcRes.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(curVfcRes.right().value()), csarUUID); + componentsUtils.auditResource(responseFormat, user, oldResource, "", "", AuditingActionEnum.CREATE_RESOURCE, null); + nodeTypesArtifactsToHandleRes = Either.right(responseFormat); + break; + } else if (curVfcRes.isLeft()) { + curNodeType = curVfcRes.left().value(); + } + if (!MapUtils.isEmpty(extractedVfcsArtifacts)) { + List currArtifacts = new ArrayList<>(); + for (String currNamespace : currVfcToscaNameEntry.getKey().getValue()) { + if (extractedVfcsArtifacts.containsKey(currNamespace)) { + handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace)); + } + } + curNodeTypeArtifactsToHandleRes = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts); + if (curNodeTypeArtifactsToHandleRes.isRight()) { + nodeTypesArtifactsToHandleRes = Either.right(curNodeTypeArtifactsToHandleRes.right().value()); + break; + } + curNodeTypeArtifactsToHandle = curNodeTypeArtifactsToHandleRes.left().value(); + + } else if (curNodeType != null) { + // delete all artifacts if have not received artifacts from csar + curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); + List artifactsToDelete = new ArrayList<>(); + // delete all informational artifacts + artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toList())); + // delete all deployment artifacts + artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values()); + if (!artifactsToDelete.isEmpty()) { + curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete); + } + } + if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) { + nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey().getKey(), curNodeTypeArtifactsToHandle); + } + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + nodeTypesArtifactsToHandleRes = Either.right(responseFormat); + log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e); + } + return nodeTypesArtifactsToHandleRes; + } + + private void validateNodeTypeIdentifiers(Map> extractedVfcsArtifacts, List>, String>> extractedVfcToscaNames) { + if (extractedVfcsArtifacts != null) { + List validIdentifiers = new ArrayList<>(); + if (extractedVfcToscaNames != null) { + extractedVfcToscaNames.stream().forEach(pair -> { + validIdentifiers.addAll(pair.getKey().getValue()); + validIdentifiers.add(pair.getKey().getKey()); + }); + } + for (String curIdentifier : extractedVfcsArtifacts.keySet()) { + if (validIdentifiers != null && !validIdentifiers.contains(curIdentifier)) + log.warn("Warning - VFC identification {} provided in the Artifacts folder of the CSAR is not valid. ", curIdentifier); + } + } + } + + private Either>, ResponseFormat> findNodeTypeArtifactsToHandle(Resource curNodeType, List extractedArtifacts) { + + Either>, ResponseFormat> nodeTypeArtifactsToHandleRes = null; + EnumMap> nodeTypeArtifactsToHandle = null; + Wrapper responseWrapper = new Wrapper<>(); + try { + List artifactsToUpload = new ArrayList<>(extractedArtifacts); + List artifactsToUpdate = new ArrayList<>(); + List artifactsToDelete = new ArrayList<>(); + if (curNodeType != null) { + Map existingArtifacts = new HashMap<>(); + if (curNodeType.getDeploymentArtifacts() != null) { + existingArtifacts.putAll(curNodeType.getDeploymentArtifacts()); + } + if (curNodeType.getArtifacts() != null) { + existingArtifacts.putAll(curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()))); + } + for (ArtifactDefinition currNewArtifact : extractedArtifacts) { + ArtifactDefinition foundArtifact; + + if (!existingArtifacts.isEmpty()) { + foundArtifact = existingArtifacts.values().stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null); + if (foundArtifact != null) { + if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) { + if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) { + foundArtifact.setPayload(currNewArtifact.getPayloadData()); + foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData())); + foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(currNewArtifact.getPayloadData())); + artifactsToUpdate.add(foundArtifact); + } + existingArtifacts.remove(foundArtifact.getArtifactLabel()); + artifactsToUpload.remove(currNewArtifact); + } else { + log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName()); + ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), + foundArtifact.getArtifactType()); + responseWrapper.setInnerElement(responseFormat); + break; + } + } + } + } + if (responseWrapper.isEmpty()) { + artifactsToDelete.addAll(existingArtifacts.values()); + } + } + if (responseWrapper.isEmpty()) { + if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) { + nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); + if (!artifactsToUpload.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload); + if (!artifactsToUpdate.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate); + if (!artifactsToDelete.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete); + } + nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle); + } + if (!responseWrapper.isEmpty()) { + nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement()); + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + responseWrapper.setInnerElement(responseFormat); + log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); + } + return nodeTypeArtifactsToHandleRes; + } + + /** + * Changes resource life cycle state to checked out + * + * @param resource + * @param user + * @param inTransaction + * @return + */ + private Either checkoutResource(Resource resource, User user, boolean inTransaction) { + Either checkoutResourceRes; + try { + if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + log.debug("************* Going to change life cycle state of resource {} to not certified checked out. ", resource.getName()); + Either checkoutRes = lifecycleBusinessLogic.changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, + new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true); + if (checkoutRes.isRight()) { + log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", resource.getComponentType().getNodeType(), resource.getUniqueId(), checkoutRes.right().value().getStatus()); + checkoutResourceRes = Either.right(checkoutRes.right().value()); + } else { + checkoutResourceRes = Either.left((Resource) checkoutRes.left().value()); + } + } else { + checkoutResourceRes = Either.left(resource); + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + checkoutResourceRes = Either.right(responseFormat); + log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e); + } + return checkoutResourceRes; + } + + /** + * Handles Artifacts of NodeType + * + * @param nodeTypeResource + * @param nodeTypeArtifactsToHandle + * @param vfcsNewCreatedArtifacts + * @param user + * @param inTransaction + * @return + */ + public Either, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource, Map> nodeTypeArtifactsToHandle, List vfcsNewCreatedArtifacts, + User user, boolean inTransaction) { + Either, ResponseFormat> handleNodeTypeArtifactsRequestRes; + Either, ResponseFormat> handleNodeTypeArtifactsRes = null; + Either changeStateResponse; + try { + changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction); + if (changeStateResponse.isRight()) { + return Either.right(changeStateResponse.right().value()); + } + nodeTypeResource = changeStateResponse.left().value(); + + List handledNodeTypeArtifacts = new ArrayList<>(); + log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName()); + for (Entry> curOperationEntry : nodeTypeArtifactsToHandle.entrySet()) { + ArtifactOperationEnum curOperation = curOperationEntry.getKey(); + List curArtifactsToHandle = curOperationEntry.getValue(); + if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) { + log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName()); + handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic.handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, vfcsNewCreatedArtifacts, + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, curOperation), false, inTransaction); + if (handleNodeTypeArtifactsRequestRes.isRight()) { + handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value()); + break; + } + if (curOperation == ArtifactOperationEnum.Create) { + vfcsNewCreatedArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value()); + } + handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value()); + } + } + if (handleNodeTypeArtifactsRes == null) { + handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts); + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleNodeTypeArtifactsRes = Either.right(responseFormat); + log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e); + } + return handleNodeTypeArtifactsRes; + } + + private List>, String>> extractVfcToscaNames(Map csar, String yamlFileName, String vfResourceName) { + List>, String>> vfcToscaNames = new ArrayList<>(); + Map nodeTypes; + if (csar != null) { + nodeTypes = new HashMap<>(); + putNodeTypesFromYaml(csar, yamlFileName, nodeTypes); + putNodeTypesFromYaml(csar, Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE, nodeTypes); + putNodeTypesFromYaml(csar, Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE, nodeTypes); + + if (!nodeTypes.isEmpty()) { + Iterator> nodesNameEntry = nodeTypes.entrySet().iterator(); + while (nodesNameEntry.hasNext()) { + Entry nodeType = nodesNameEntry.next(); + addVfcToscaNameFindSubstitutes(csar, vfResourceName, vfcToscaNames, nodeType.getKey()); + } + } + } + return vfcToscaNames; + } + + @SuppressWarnings("unchecked") + private void putNodeTypesFromYaml(Map csar, String yamlFileName, Map nodeTypes) { + + if (csar.containsKey(yamlFileName)) { + Map mappedToscaTemplate; + Either, ResultStatusEnum> eitherNodeTypes; + mappedToscaTemplate = (Map) new Yaml().load(new String(csar.get(yamlFileName), StandardCharsets.UTF_8)); + eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); + if (eitherNodeTypes.isLeft()) { + nodeTypes.putAll(eitherNodeTypes.left().value()); + } + } + } + + private void addVfcToscaNameFindSubstitutes(Map csar, String vfResourceName, List>, String>> vfcToscaNames, String nodeTypeFullName) { + + String toscaResourceName = buildNestedVfcToscaResourceName(vfResourceName, nodeTypeFullName); + String nodeTypeTemplateYamlName = buildNestedSubstituteYamlName(nodeTypeFullName); + List relatedVfcsToscaNameSpaces = new ArrayList<>(); + relatedVfcsToscaNameSpaces.add(buildNestedVfcToscaNamespace(nodeTypeFullName)); + if (csar.containsKey(nodeTypeTemplateYamlName)) { + addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, relatedVfcsToscaNameSpaces); + } + ImmutablePair> toscaNameSpacesHierarchy = new ImmutablePair<>(nodeTypeFullName, relatedVfcsToscaNameSpaces); + vfcToscaNames.add(new ImmutablePair<>(toscaNameSpacesHierarchy, toscaResourceName)); + } + + private void addSubstituteToscaNamespacesRecursively(Map csar, String yamlFileName, List toscaNameSpaces) { + + Map nodeTypes = new HashMap<>(); + + if (csar.containsKey(yamlFileName)) { + putNodeTypesFromYaml(csar, yamlFileName, nodeTypes); + } + if (!nodeTypes.isEmpty()) { + Iterator> nodesNameEntry = nodeTypes.entrySet().iterator(); + while (nodesNameEntry.hasNext()) { + Entry nodeType = nodesNameEntry.next(); + String nodeTypeFullName = nodeType.getKey(); + String toscaNameSpace = buildNestedVfcToscaNamespace(nodeTypeFullName); + if (toscaNameSpaces.contains(toscaNameSpace)) { + break; + } + toscaNameSpaces.add(toscaNameSpace); + + String nodeTypeTemplateYamlName = buildNestedSubstituteYamlName(nodeTypeFullName); + + if (csar.containsKey(nodeTypeTemplateYamlName)) { + addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, toscaNameSpaces); + } + } + } + } + + public Either createResourceFromCsar(Resource resource, User user, Either, StorageOperationStatus> csarUIPayload, String csarUUID) { log.trace("************* created successfully from YAML, resource TOSCA "); Either, StorageOperationStatus> csar = null; @@ -793,7 +1103,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } - public Either, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, String resourceYml, User user, boolean needLock) { + public Either, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, String resourceYml, User user, boolean needLock, + Map>> nodeTypesArtifactsToHandle, List nodeTypesNewCreatedArtifacts) { Map mappedToscaTemplate = (Map) new Yaml().load(resourceYml); @@ -818,8 +1129,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { while (nodesNameValue.hasNext()) { Entry nodeType = nodesNameValue.next(); + Map> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey()); log.trace("************* Going to create node {}", nodeType.getKey()); - Either, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, user, mapToConvert, resource, needLock); + Either, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, user, mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts); log.trace("************* finished to create node {}", nodeType.getKey()); if (resourceCreated.isRight()) { return Either.right(resourceCreated.right().value()); @@ -842,7 +1154,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return nameWithouNamespacePrefix.substring(resourceType.length()); } - private Either, ResponseFormat> createNodeTypeResourceFromYaml(String yamlName, Entry nodeNameValue, User user, Map mapToConvert, Resource resourceVf, boolean needLock) { + private Either, ResponseFormat> createNodeTypeResourceFromYaml(String yamlName, Entry nodeNameValue, User user, Map mapToConvert, Resource resourceVf, boolean needLock, + Map> nodeTypeArtifactsToHandle, List nodeTypesNewCreatedArtifacts) { Either resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user); if (resourceMetaData.isRight()) { @@ -858,8 +1171,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Map singleVfc = new HashMap<>(); String actualName = this.getNodeTypeActualName(nodeNameValue.getKey()); - if (!actualName.startsWith(ImportUtils.Constants.ABSTRACT_NODE)) { - actualName = "." + ImportUtils.Constants.ABSTRACT_NODE + actualName; + if (!actualName.startsWith(Constants.ABSTRACT)) { + actualName = "." + Constants.ABSTRACT + actualName; } // Setting tosca name @@ -875,7 +1188,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } user = eitherCreator.left().value(); - return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock); + return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts); } public Either validateResourceCreationFromNodeType(Resource resource, User creator) { @@ -887,11 +1200,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.left(true); } - public Either, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock) { + public Either, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock, + Map> nodeTypeArtifactsToHandle, List nodeTypesNewCreatedArtifacts) { LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR); Function> validator = (resource) -> this.validateResourceCreationFromNodeType(resource, creator); - return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock); + return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts); } private Either fillResourceMetadata(String yamlName, Resource resourceVf, String nodeTypeName, User user) { @@ -915,7 +1229,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { resourceType = ResourceTypeEnum.VFC.name().toLowerCase(); } // validating type - if (!ResourceTypeEnum.contains(resourceType.toUpperCase())) { + if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) { log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values()); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeTypeName); return Either.right(responseFormat); @@ -956,7 +1270,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Map csar, List createdArtifacts, String topologyTemplateYaml) { boolean result = true; - + boolean inTransaction = true; + Map createdVfcs = new HashMap<>(); + List nodeTypesNewCreatedArtifacts = new ArrayList<>(); Either lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource"); if (lockResult.isRight()) { ResponseFormat responseFormat = lockResult.right().value(); @@ -966,7 +1282,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { try { log.trace("************* createResourceFromYaml before full create resource {}", yamlName); - Either createResourcesEither = createResourceTransaction(resource, user, actionEnum, isNormative, true); + Either genericResourceEither = fetchAndSetDerivedFromGenericType(resource); + if (genericResourceEither.isRight()) { + result = false; + return genericResourceEither; + } + Either createResourcesEither = createResourceTransaction(resource, user, isNormative, inTransaction); log.trace("************* createResourceFromYaml after full create resource {}", yamlName); if (createResourcesEither.isRight()) { result = false; @@ -975,9 +1296,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { resource = createResourcesEither.left().value(); // add groups to resource log.trace("************* Going to add inputs from yaml {}", yamlName); + if (resource.shouldGenerateInputs()) + generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value()); Map inputs = parsedToscaYamlInfo.getInputs(); - Either createInputsOnResource = createInputsOnResource(resource, user, inputs, true); + Either createInputsOnResource = createInputsOnResource(resource, user, inputs, inTransaction); if (createInputsOnResource.isRight()) { result = false; return createInputsOnResource; @@ -987,7 +1310,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Map uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances(); log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName); - createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, user, uploadComponentInstanceInfoMap, actionEnum, topologyTemplateYaml, csar, csarUUID); + createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, user, uploadComponentInstanceInfoMap, actionEnum, topologyTemplateYaml, csar, csarUUID, nodeTypesNewCreatedArtifacts, createdVfcs); log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName); if (createResourcesEither.isRight()) { result = false; @@ -1019,14 +1342,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { log.trace("************* Finished to add groups from yaml {}", yamlName); log.trace("************* Going to add artifacts from yaml {}", yamlName); - Either createdCsarArtifactsEither = this.handleCsarArtifacts(resource, user, csarUUID, csar, createdArtifacts, ArtifactOperation.Create, false, true); + Either createdCsarArtifactsEither = this.handleCsarArtifacts(resource, user, csarUUID, csar, createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), false, + inTransaction); log.trace("************* Finished to add artifacts from yaml {}", yamlName); if (createdCsarArtifactsEither.isRight()) { result = false; return createdCsarArtifactsEither; } - resource = createdCsarArtifactsEither.left().value(); + resource = createdCsarArtifactsEither.left().value(); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); ASDCKpiApi.countCreatedResourcesKPI(); @@ -1035,8 +1359,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } finally { if (!result) { log.warn("operation failed. do rollback"); - titanGenericDao.rollback(); - if (!createdArtifacts.isEmpty()) { + titanDao.rollback(); + if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) { + createdArtifacts.addAll(nodeTypesNewCreatedArtifacts); StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts); if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes); @@ -1047,7 +1372,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } else { log.debug("operation success. do commit"); - titanGenericDao.commit(); + titanDao.commit(); } graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource); @@ -1057,7 +1382,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } private Either createGroupsOnResource(Resource resource, User user, Map groups) { - if (groups != null && false == groups.isEmpty()) { + if (groups != null && !groups.isEmpty()) { Either, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource); if (mergeGroupsUsingResource.isRight()) { @@ -1065,22 +1390,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.right(mergeGroupsUsingResource.right().value()); } List groupsAsList = mergeGroupsUsingResource.left().value(); - - // Either, ResponseFormat> createGroups = - // groupBusinessLogic.createGroups( - // resource.getUniqueId(), user.getUserId(), - // ComponentTypeEnum.RESOURCE, groupsAsList, false, - // true); - // In this method we assume all instances exists in resource - Either, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsAsList, true); + Either, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsAsList); if (createGroups.isRight()) { return Either.right(createGroups.right().value()); } } else { return Either.left(resource); } - - Either updatedResource = resourceOperation.getResource(resource.getUniqueId(), true); + Either updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); if (updatedResource.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); return Either.right(responseFormat); @@ -1122,42 +1439,31 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } else groupsToCreate.addAll(groupsAsList); - + Either, ResponseFormat> prepareGroups = null; if (!groupsToCreate.isEmpty()) { - Either, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate, true); - if (createGroups.isRight()) { - return Either.right(createGroups.right().value()); + if (groupsFromResource != null && !groupsFromResource.isEmpty()) { + prepareGroups = groupBusinessLogic.addGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate); + } else { + prepareGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate); + } + + if (prepareGroups.isRight()) { + return Either.right(prepareGroups.right().value()); } } if (!groupsToDelete.isEmpty()) { - for (GroupDefinition group : groupsToDelete) { - Either deleteGroupEither = groupOperation.deleteGroup(group.getUniqueId(), true); - if (deleteGroupEither.isRight()) { - StorageOperationStatus storageOperationStatus = deleteGroupEither.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus); - log.debug("Failed to delete group {} under component {}, error: {}", group.getUniqueId(), resource.getNormalizedName(), actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - } + prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToDelete); + if (prepareGroups.isRight()) { + return Either.right(prepareGroups.right().value()); } } - if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) { - Either, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateMembersToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupsToUpdate, false, true); - if (assotiateGroupEither.isRight()) { - log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value()); - return Either.right(assotiateGroupEither.right().value()); - - } - List updatedGroups = assotiateGroupEither.left().value(); - List groupsId = updatedGroups.stream().map(e -> e.getUniqueId()).collect(Collectors.toList()); - - Either, StorageOperationStatus> updateVersionEither = groupBusinessLogic.updateGroupVersion(groupsId, true); - if (updateVersionEither.isRight()) { - log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updateVersionEither.right().value()), resource); - return Either.right(responseFormat); + if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) { + prepareGroups = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsToUpdate); + if (prepareGroups.isRight()) { + return Either.right(prepareGroups.right().value()); } } @@ -1165,7 +1471,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.left(resource); } - Either updatedResource = resourceOperation.getResource(resource.getUniqueId(), true); + Either updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); if (updatedResource.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); return Either.right(responseFormat); @@ -1175,13 +1481,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { private Either createInputsOnResource(Resource resource, User user, Map inputs, boolean inTransaction) { if (inputs != null && false == inputs.isEmpty()) { - List inputsAsList = new ArrayList(); - for (Entry entry : inputs.entrySet()) { - InputDefinition input = entry.getValue(); - input.setName(entry.getKey()); - inputsAsList.add(input); - } - Either, ResponseFormat> createGroups = inputsBusinessLogic.createInputsInGraph(inputsAsList, resource, user, inTransaction); + + Either, ResponseFormat> createGroups = inputsBusinessLogic.createInputsInGraph(inputs, resource, user, inTransaction); if (createGroups.isRight()) { return Either.right(createGroups.right().value()); } @@ -1189,7 +1490,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.left(resource); } - Either updatedResource = resourceOperation.getResource(resource.getUniqueId(), true); + Either updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); if (updatedResource.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); return Either.right(responseFormat); @@ -1204,6 +1505,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { List componentInstances = component.getComponentInstances(); if (groups != null) { + Either validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups); + if (validateCyclicGroupsDependencies.isRight()) { + return FunctionalInterfaces.convertEitherRight(validateCyclicGroupsDependencies); + } for (Entry entry : groups.entrySet()) { String groupName = entry.getKey(); @@ -1219,7 +1524,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (componentInstances == null || true == componentInstances.isEmpty()) { String membersAstString = compInstancesNames.stream().collect(Collectors.joining(",")); - log.debug("The members {} in group {} cannot be found in component {}. There are no component instances", membersAstString, groupName, component.getNormalizedName()); + log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString, groupName, component.getNormalizedName()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component))); } // Find all component instances with the member names @@ -1235,7 +1540,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } compInstancesNames.removeAll(foundMembers); String membersAstString = compInstancesNames.stream().collect(Collectors.joining(",")); - log.debug("The members {} in group {} cannot be found in component {}", membersAstString, groupName, component.getNormalizedName()); + log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component))); } @@ -1248,19 +1553,116 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.left(result); } + /** + * This Method validates that there is no cyclic group dependencies. meaning group A as member in group B which is member in group A + * + * @param allGroups + * @return + */ + private Either validateCyclicGroupsDependencies(Map allGroups) { + + Either result = Either.left(true); + try { + Iterator> allGroupsItr = allGroups.entrySet().iterator(); + while (allGroupsItr.hasNext() && result.isLeft()) { + Entry groupAEntry = allGroupsItr.next(); + // Fetches a group member A + String groupAName = groupAEntry.getKey(); + // Finds all group members in group A + Set allGroupAMembersNames = new HashSet<>(); + fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames); + // If A is a group member of itself found cyclic dependency + if (allGroupAMembersNames.contains(groupAName)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName); + result = Either.right(responseFormat); + } + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + result = Either.right(responseFormat); + log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e); + } + return result; + } + + /** + * This Method fills recursively the set groupMembers with all the members of the given group which are also of type group. + * + * @param groupName + * @param allGroups + * @param allGroupMembers + * @return + */ + private void fillAllGroupMemebersRecursivly(String groupName, Map allGroups, Set allGroupMembers) { + + // Found Cyclic dependency + if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) { + return; + } + GroupDefinition groupDefinition = allGroups.get(groupName); + // All Members Of Current Group Resource Instances & Other Groups + Set currGroupMembers = groupDefinition.getMembers().keySet(); + // Filtered Members Of Current Group containing only members which + // are groups + List currGroupFilteredMembers = currGroupMembers.stream(). + // Keep Only Elements of type group and not Resource Instances + filter(innerGroupName -> allGroups.containsKey(innerGroupName)). + // Add Filtered Elements to main Set + peek(innerGroupName -> allGroupMembers.add(innerGroupName)). + // Collect results + collect(Collectors.toList()); + + // Recursively call the method for all the filtered group members + for (String innerGroupName : currGroupFilteredMembers) { + fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers); + } + + } + + private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map allGroups, Set allGroupMembers) { + + boolean stop = false; + // In Case Not Group Stop + if (!allGroups.containsKey(groupName)) { + stop = true; + } + // In Case Group Has no members stop + if (!stop) { + GroupDefinition groupDefinition = allGroups.get(groupName); + stop = MapUtils.isEmpty(groupDefinition.getMembers()); + + } + // In Case all group members already contained stop + if (!stop) { + final Set allMembers = allGroups.get(groupName).getMembers().keySet(); + Set membersOfTypeGroup = allMembers.stream(). + // Filter In Only Group members + filter(innerGroupName -> allGroups.containsKey(innerGroupName)). + // Collect + collect(Collectors.toSet()); + stop = allGroupMembers.containsAll(membersOfTypeGroup); + } + return stop; + } + private Either createRIAndRelationsFromYaml(String yamlName, Resource resource, User user, Map uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum, - String topologyTemplateYaml, Map csar, String csarUUID) { + String topologyTemplateYaml, Map csar, String csarUUID, List nodeTypesNewCreatedArtifacts, Map createdVfcs) { Either result; Either createResourcesInstancesEither; + + Map>> nodeTypesArtifactsToCreate = findNodeTypeArtifactsToCreate(csar, yamlName, resource); + log.debug("************* Going to create all nodes {}", yamlName); - Either, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, user, topologyTemplateYaml, csar, false); + Either, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, user, topologyTemplateYaml, csar, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts); log.debug("************* Finished to create all nodes {}", yamlName); if (createdResourcesFromdNodeTypeMap.isRight()) { log.debug("failed to resources from node types status is {}", createdResourcesFromdNodeTypeMap.right().value()); return Either.right(createdResourcesFromdNodeTypeMap.right().value()); } + createdVfcs.putAll(createdResourcesFromdNodeTypeMap.left().value()); + log.debug("************* Going to create all resource instances {}", yamlName); createResourcesInstancesEither = createResourceInstances(user, yamlName, resource, uploadComponentInstanceInfoMap, true, false, createdResourcesFromdNodeTypeMap.left().value()); @@ -1292,17 +1694,66 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return result; } - private Either, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, User user, String topologyTemplateYaml, Map csar, boolean needLock) { + private Map>> findNodeTypeArtifactsToCreate(Map csar, String yamlName, Resource resource) { + + Map> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar); + List>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlName, resource.getSystemName()); + validateNodeTypeIdentifiers(extractedVfcsArtifacts, extractedVfcToscaNames); + Map>> nodeTypesArtifactsToHandle = null; + if (!extractedVfcsArtifacts.isEmpty() && !extractedVfcToscaNames.isEmpty()) { + for (ImmutablePair>, String> currToscaNamePair : extractedVfcToscaNames) { + EnumMap> curNodeTypeArtifacts = null; + String currVfcToscaNamespace = currToscaNamePair.getKey().getKey(); + List relatedVfcs = currToscaNamePair.getKey().getValue(); + List currArtifactList = null; + + for (String currSubstitute : relatedVfcs) { + if (extractedVfcsArtifacts.containsKey(currSubstitute)) { + if (MapUtils.isEmpty(curNodeTypeArtifacts)) { + curNodeTypeArtifacts = new EnumMap<>(ArtifactOperationEnum.class); + currArtifactList = new ArrayList<>(); + curNodeTypeArtifacts.put(ArtifactOperationEnum.Create, currArtifactList); + } else { + currArtifactList = curNodeTypeArtifacts.get(ArtifactOperationEnum.Create); + } + handleAndAddExtractedVfcsArtifacts(currArtifactList, extractedVfcsArtifacts.get(currSubstitute)); + } + } + + if (nodeTypesArtifactsToHandle == null) { + nodeTypesArtifactsToHandle = new HashMap<>(); + } + nodeTypesArtifactsToHandle.put(currVfcToscaNamespace, curNodeTypeArtifacts); + } + } + return nodeTypesArtifactsToHandle; + } + + private void handleAndAddExtractedVfcsArtifacts(List vfcArtifacts, List artifactsToAdd) { + List vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName()).collect(Collectors.toList()); + artifactsToAdd.stream().forEach(a -> { + if (!vfcArtifactNames.contains(a.getArtifactName())) { + vfcArtifacts.add(a); + } else { + log.error("Can't upload two artifact with the same name {}. ", a.getArtifactName()); + } + }); + + } + + private Either, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, User user, String topologyTemplateYaml, Map csar, boolean needLock, + Map>> nodeTypesArtifactsToHandle, List nodeTypesNewCreatedArtifacts) { Map createdResourcesFromdNodeTypeMap = new HashMap<>(); Either, ResponseFormat> result = Either.left(createdResourcesFromdNodeTypeMap); - String yamlFileName = Constants.GLOBAL_SUBSTITUTION_TYPE_SERVICE_TEMPLATE; + String yamlFileName = Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE; if (csar != null && csar.containsKey(yamlFileName)) { byte[] yamlFileBytes = csar.get(yamlFileName); String globalTypesYaml = new String(yamlFileBytes, StandardCharsets.UTF_8); - Either, ResponseFormat> createdNodeTypesFromGlobalTypesTemplateEither = this.createResourcesFromYamlNodeTypesList(yamlFileName, resource, globalTypesYaml, user, needLock); + Either, ResponseFormat> createdNodeTypesFromGlobalTypesTemplateEither = this.createResourcesFromYamlNodeTypesList(yamlFileName, resource, globalTypesYaml, user, needLock, nodeTypesArtifactsToHandle, + nodeTypesNewCreatedArtifacts); if (createdNodeTypesFromGlobalTypesTemplateEither.isRight()) { ResponseFormat responseFormat = createdNodeTypesFromGlobalTypesTemplateEither.right().value(); componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); @@ -1311,7 +1762,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { createdResourcesFromdNodeTypeMap.putAll(createdNodeTypesFromGlobalTypesTemplateEither.left().value()); } - Either, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, topologyTemplateYaml, user, needLock); + Either, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, topologyTemplateYaml, user, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts); if (createdNodeTypeFromMainTemplateEither.isRight()) { ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value(); componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); @@ -1327,14 +1778,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return result; } - private Either handleCsarArtifacts(Resource resource, User user, String csarUUID, Map csar, List createdArtifacts, ArtifactOperation artifactOperation, boolean shouldLock, + private Either handleCsarArtifacts(Resource resource, User user, String csarUUID, Map csar, List createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock, boolean inTransaction) { if (csar != null) { String vendorLicenseModelId = null; String vfLicenseModelId = null; - if (artifactOperation.equals(ArtifactOperation.Update)) { + if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Update) { Map deploymentArtifactsMap = resource.getDeploymentArtifacts(); if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) { for (Entry artifactEntry : deploymentArtifactsMap.entrySet()) { @@ -1346,17 +1797,24 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } - createOrUpdateLicenseArtifact(resource, user, csarUUID, csar, Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, - Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, shouldLock, inTransaction); - createOrUpdateLicenseArtifact(resource, user, csarUUID, csar, Constants.VF_LICENSE_MODEL, ArtifactTypeEnum.VF_LICENSE.getType(), Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, - vfLicenseModelId, artifactOperation, shouldLock, inTransaction); + // Specific Behavior for license artifacts + createOrUpdateSingleNonMetaArtifact(resource, user, csarUUID, csar, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, + Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, shouldLock, inTransaction); + createOrUpdateSingleNonMetaArtifact(resource, user, csarUUID, csar, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, + Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, shouldLock, inTransaction); + + Either eitherCreateResult = createOrUpdateNonMetaArtifacts(csarUUID, csar, resource, user, createdArtifacts, shouldLock, inTransaction, artifactOperation); + if (eitherCreateResult.isRight()) { + return Either.right(eitherCreateResult.right().value()); + } + Either, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csar, csarUUID, componentsUtils); if (artifacsMetaCsarStatus.isLeft()) { String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey(); String artifactsContents = artifacsMetaCsarStatus.left().value().getValue(); Either createArtifactsFromCsar = Either.left(resource); - if (artifactOperation.equals(ArtifactOperation.Create)) + if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) createArtifactsFromCsar = createResourceArtifactsFromCsar(csarUUID, csar, resource, user, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction); else createArtifactsFromCsar = updateResourceArtifactsFromCsar(csarUUID, csar, resource, user, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction); @@ -1371,19 +1829,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (groupsToDelete != null && !groupsToDelete.isEmpty()) { Set artifactsToDelete = new HashSet(); - for (GroupDefinition group : groupsToDelete) { - List artifacts = group.getArtifacts(); - if (artifacts != null) { - artifactsToDelete.addAll(artifacts); - Either deleteGroupEither = groupOperation.deleteGroup(group.getUniqueId(), inTransaction); - if (deleteGroupEither.isRight()) { - StorageOperationStatus storageOperationStatus = deleteGroupEither.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus); - log.debug("Failed to delete group {} under component {}, error: {}", group.getUniqueId(), resource.getNormalizedName(), actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - } - } + /* + * for (GroupDefinition group : groupsToDelete) { List artifacts = group.getArtifacts(); if (artifacts != null) { artifactsToDelete.addAll(artifacts); Either deleteGroupEither = + * groupOperation.deleteGroup(group.getUniqueId(), inTransaction); if (deleteGroupEither.isRight()) { StorageOperationStatus storageOperationStatus = deleteGroupEither.right().value(); ActionStatus actionStatus = + * componentsUtils.convertFromStorageResponse(storageOperationStatus); log.debug("Failed to delete group {} under component {}, error: {}", group.getUniqueId(), resource.getNormalizedName(), actionStatus.name()); return + * Either.right(componentsUtils.getResponseFormat(actionStatus)); } } } + */ for (String artifactId : artifactsToDelete) { Either, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null, null, shouldLock, inTransaction); @@ -1391,31 +1842,31 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { log.debug("Couldn't delete artifact {}", artifactId); return Either.right(handleDelete.right().value()); } - } - Either eitherGerResource = resourceOperation.getResource(resource.getUniqueId(), inTransaction); - if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); + Either eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); + if (eitherGetResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); return Either.right(responseFormat); } - resource = eitherGerResource.left().value(); + resource = eitherGetResource.left().value(); } } } return Either.left(resource); } - private Either createOrUpdateLicenseArtifact(Resource resource, User user, String csarUUID, Map csar, String artifactFileName, String artifactType, String artifactLabel, String artifactDisplayName, - String artifactDescription, String artifactId, ArtifactOperation operation, boolean shouldLock, boolean inTransaction) { + private Either createOrUpdateSingleNonMetaArtifact(Resource resource, User user, String csarUUID, Map csar, String artifactPath, String artifactFileName, String artifactType, + ArtifactGroupTypeEnum artifactGroupType, String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, ArtifactOperationInfo operation, List createdArtifacts, boolean shouldLock, + boolean inTransaction) { byte[] artifactFileBytes = null; - if (csar.containsKey(Constants.ARTIFACTS + artifactFileName)) { - artifactFileBytes = csar.get(Constants.ARTIFACTS + artifactFileName); + if (csar.containsKey(artifactPath)) { + artifactFileBytes = csar.get(artifactPath); } Either result = Either.left(true); - if (operation.equals(ArtifactOperation.Update)) { + if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete) { if (artifactId != null && !artifactId.isEmpty() && artifactFileBytes == null) { Either, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null, null, shouldLock, inTransaction); @@ -1426,31 +1877,40 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } if ((artifactId == null || artifactId.isEmpty()) && artifactFileBytes != null) { - operation = ArtifactOperation.Create; + operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create); } } if (artifactFileBytes != null) { - Map vendorLicenseModelJson = buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactLabel, artifactDisplayName, artifactDescription, artifactFileBytes, null); - Either, ResponseFormat> vfLicenceArtifactCreateEither = createOrUpdateCsarArtifactFromJson(resource, user, vendorLicenseModelJson, operation, shouldLock, inTransaction); - - if (vfLicenceArtifactCreateEither.isRight()) { + Map vendorLicenseModelJson = buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, artifactFileBytes, null); + Either, ResponseFormat> eitherNonMetaArtifacts = createOrUpdateCsarArtifactFromJson(resource, user, vendorLicenseModelJson, operation, shouldLock, inTransaction); + addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts); + if (eitherNonMetaArtifacts.isRight()) { BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarUUID, ErrorSeverity.WARNING); - return Either.right(vfLicenceArtifactCreateEither.right().value()); + return Either.right(eitherNonMetaArtifacts.right().value()); } } return result; } - private Either, ResponseFormat> createOrUpdateCsarArtifactFromJson(Resource resource, User user, Map json, ArtifactOperation operation, boolean shoudLock, boolean inTransaction) { + private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List createdArtifacts, Either, ResponseFormat> eitherNonMetaArtifacts) { + if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && createdArtifacts != null && eitherNonMetaArtifacts.isLeft()) { + Either eitherResult = eitherNonMetaArtifacts.left().value(); + if (eitherResult.isLeft()) { + createdArtifacts.add(eitherResult.left().value()); + } + } + } + + private Either, ResponseFormat> createOrUpdateCsarArtifactFromJson(Resource resource, User user, Map json, ArtifactOperationInfo operation, boolean shoudLock, boolean inTransaction) { String jsonStr = gson.toJson(json); String origMd5 = GeneralUtility.calculateMD5ByString(jsonStr); ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class); - - Either, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.handleArtifactRequest(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, operation, - artifactDefinitionFromJson.getUniqueId(), artifactDefinitionFromJson, origMd5, jsonStr, null, null, null, null, shoudLock, inTransaction); + String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId(); + Either, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.validateAndHandleArtifact(resource.getUniqueId(), ComponentTypeEnum.RESOURCE, operation, artifactUniqueId, + artifactDefinitionFromJson, origMd5, jsonStr, null, null, null, user, resource, false, true); if (uploadArtifactToService.isRight()) return Either.right(uploadArtifactToService.right().value()); @@ -1489,37 +1949,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } return createResourceArtifacts(csarUUID, csar, resource, user, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdNewArtifacts, shouldLock, inTransaction); } - // find artifacts to delete - Set artifactNotInGroupSet = findArtifactsNotInGroupToDelete(groups, createdDeplymentArtifactsAfterDelete); - - // delete all artifacts which not in groups - if (!artifactNotInGroupSet.isEmpty()) { - for (String artifactId : artifactNotInGroupSet) { - Either, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null, - null, shouldLock, inTransaction); - if (handleDelete.isRight()) { - return Either.right(handleDelete.right().value()); - } - - } - Either eitherGerResource = resourceOperation.getResource(resource.getUniqueId(), inTransaction); - if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); - - return Either.right(responseFormat); - - } - - resource = eitherGerResource.left().value(); - deplymentArtifact = resource.getDeploymentArtifacts(); - - createdDeplymentArtifactsAfterDelete.clear(); - if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) { - for (Entry entry : deplymentArtifact.entrySet()) { - createdDeplymentArtifactsAfterDelete.add(entry.getValue()); - } - } - } // find master in group Map>> groupArtifact = findMasterArtifactInGroup(groups, deplymentArtifact); @@ -1551,18 +1980,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Map> dissocArtifactFromGroup = new HashMap>(); Set jsonMasterArtifacts = parsedGroup.keySet(); - - Map mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, artifactsToDelete, groupToDelete, jsonMasterArtifacts); - - // find artifacts to delete - for (Entry> deleteGroup : groupToDelete.entrySet()) { - - List artifacts = deleteGroup.getValue(); - for (ArtifactDefinition artifact : artifacts) { - findArtifactToDelete(parsedGroup, artifactsToDelete, deleteGroup.getKey(), artifact); - } - - } + Map mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeplymentArtifactsAfterDelete); // Set deletedArtifactsName = new HashSet(); Either, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(resource, user, shouldLock, inTransaction, artifactsToDelete, groupToDelete); @@ -1602,24 +2020,25 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } resource = assDissotiateEither.left().value(); - groups = resource.getGroups(); - List groupToUpdate = new ArrayList<>(); - // update vfModule names - Set groupForAssociateWithMembers = mergedgroup.keySet(); + deplymentArtifact = resource.getDeploymentArtifacts(); + createdDeplymentArtifactsAfterDelete.clear(); + if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) { + for (Entry entry : deplymentArtifact.entrySet()) { + createdDeplymentArtifactsAfterDelete.add(entry.getValue()); + } + } + + groups = resource.getGroups(); + List groupToUpdate = new ArrayList<>(); + // update vfModule names + Set groupForAssociateWithMembers = mergedgroup.keySet(); if (groups != null && !groups.isEmpty()) { - Either, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNamesOnGraph(groups, resource.getSystemName(), inTransaction); + Either, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNamesOnGraph(groups, resource, inTransaction); if (validateUpdateVfGroupNamesRes.isRight()) { return Either.right(validateUpdateVfGroupNamesRes.right().value()); } List heatGroups = null; - // List collect = resources.stream().flatMap( e -> - // e.getArtifacts().stream()).filter(p -> - // relevantArtifactTypes.contains(p.getArtifactType() - // )).collect(Collectors.toList()); - // List heatGroups = createdGroups.stream().filter( - // e -> e.getProperties().stream().filter(p -> - // p.getName().contains(Constants.HEAT_FILE_PROPS))).collect(Collectors.toList()); heatGroups = groups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList()); ; @@ -1634,7 +2053,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Map members = new HashMap(); Set artifactsGroup = new HashSet(); artifactsGroup.addAll(group.getArtifacts()); - associateMembersTToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members); + associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members); if (!members.isEmpty()) { group.setMembers(members); @@ -1642,14 +2061,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } - if (!groupToUpdate.isEmpty()) { - Either, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateMembersToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupToUpdate, false, true); - if (assotiateGroupEither.isRight()) { - log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value()); - return Either.right(assotiateGroupEither.right().value()); - - } - } + /* + * if (!groupToUpdate.isEmpty()) { Either, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateMembersToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupToUpdate, false, + * true); if (assotiateGroupEither.isRight()) { log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value()); return Either.right(assotiateGroupEither.right().value()); + * + * } } + */ } @@ -1689,18 +2106,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { // updatedGroup if (!groupForAssociateWithMembers.isEmpty()) { - List groupsId = groupForAssociateWithMembers.stream().map(e -> e.getUniqueId()).collect(Collectors.toList()); + List groupsId = groupForAssociateWithMembers.stream().map(e -> e).collect(Collectors.toList()); - Either, StorageOperationStatus> updateVersionEither = groupBusinessLogic.updateGroupVersion(groupsId, true); + Either, ResponseFormat> updateVersionEither = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsId); if (updateVersionEither.isRight()) { log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updateVersionEither.right().value()), resource); - return Either.right(responseFormat); + + return Either.right(updateVersionEither.right().value()); } } - Either eitherGerResource = resourceOperation.getResource(resource.getUniqueId(), inTransaction); + Either eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); if (eitherGerResource.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); @@ -1714,30 +2131,50 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { private Either, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Resource resource, User user, boolean shouldLock, boolean inTransaction, Set artifactsToDelete, Map> groupToDelete) { List deletedArtifacts = new ArrayList(); - + String resourceId = resource.getUniqueId(); if (!artifactsToDelete.isEmpty()) { for (ArtifactDefinition artifact : artifactsToDelete) { + String artifactType = artifact.getArtifactType(); + ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.findType(artifactType); + if (artifactTypeEnum == ArtifactTypeEnum.HEAT_ENV) { + + /* + * Either removeArifactFromGraph = artifactOperation.removeArifactFromResource(resourceId, artifact.getUniqueId(), NodeTypeEnum.Resource, true, true); if + * (removeArifactFromGraph.isRight()) { StorageOperationStatus status = removeArifactFromGraph.right().value(); log.debug("Failed to delete heat env artifact {} . status is {}", artifact.getUniqueId(), status); ActionStatus + * actionStatus = componentsUtils.convertFromStorageResponse(status); return Either.right(componentsUtils.getResponseFormat(actionStatus)); } + * + * deletedArtifacts.add(removeArifactFromGraph.left().value()); + */ - Either, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, - resource, null, null, shouldLock, inTransaction); - if (handleDelete.isRight()) { - return Either.right(handleDelete.right().value()); } - deletedArtifacts.add(handleDelete.left().value().left().value()); + + else { + Either, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resourceId, artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, + null, null, shouldLock, inTransaction); + if (handleDelete.isRight()) { + return Either.right(handleDelete.right().value()); + } + + deletedArtifacts.add(handleDelete.left().value().left().value()); + } } } if (!groupToDelete.isEmpty()) { log.debug("try to delete group"); + List groupDefinitionstoDelete = new ArrayList<>(); + List groups = resource.getGroups(); for (Entry> deleteGroup : groupToDelete.entrySet()) { - Either deleteGroupEither = groupOperation.deleteGroup(deleteGroup.getKey(), inTransaction); - if (deleteGroupEither.isRight()) { - StorageOperationStatus storageOperationStatus = deleteGroupEither.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus); - log.debug("Failed to delete group {} under component {}, error: {}", deleteGroup.getKey(), resource.getNormalizedName(), actionStatus.name()); - - return Either.right(componentsUtils.getResponseFormat(actionStatus)); + Optional op = groups.stream().filter(gr -> gr.getUniqueId().equals(deleteGroup.getKey())).findAny(); + if (op.isPresent()) { + groupDefinitionstoDelete.add(op.get()); + } + } + if (!groupDefinitionstoDelete.isEmpty()) { + Either, ResponseFormat> prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupDefinitionstoDelete); + if (prepareGroups.isRight()) { + return Either.right(prepareGroups.right().value()); } } } @@ -1755,6 +2192,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { List dissList = new ArrayList(); for (ArtifactDefinition art : dissArtifactsInGroup) { dissList.add(art.getUniqueId()); + // String heatEnvId = checkAndGetHeatEnvId(art); + // if (!heatEnvId.isEmpty()) { + // dissList.add(heatEnvId); + // } } dissocArtifactFromGroup.put(entry.getKey().getUniqueId(), dissList); } @@ -1768,7 +2209,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { artifactsToUpdateMap.put(entry.getKey(), artifactsToUpdate); } - // Map> dissocArtifactFromGroup = new + // Map> dissocArtifactFromGroup = new HashMap>(); // HashMap>(); List dissotiateArtifactsgroups = new ArrayList(); for (Entry> dissotiateEntry : dissocArtifactFromGroup.entrySet()) { @@ -1779,15 +2220,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { dissotiateArtifactsgroups.add(dissotiateGroup); } if (!dissotiateArtifactsgroups.isEmpty()) { - log.debug("try to dissociate artifacts from groups "); - Either, ResponseFormat> dissotiateGroupEither = groupBusinessLogic.dissociateArtifactsFromGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, dissotiateArtifactsgroups, shouldLock, - inTransaction); - if (dissotiateGroupEither.isRight()) { - log.debug("Failed to dissociate artifacts from groups. Status is {} ", dissotiateGroupEither.right().value()); - resEither = Either.right(dissotiateGroupEither.right().value()); - return resEither; - - } + /* + * log.debug("try to dissociate artifacts from groups "); Either, ResponseFormat> dissotiateGroupEither = groupBusinessLogic.dissociateArtifactsFromGroup(resource.getUniqueId(), user.getUserId(), + * ComponentTypeEnum.RESOURCE, dissotiateArtifactsgroups, shouldLock, inTransaction); if (dissotiateGroupEither.isRight()) { log.debug("Failed to dissociate artifacts from groups. Status is {} ", dissotiateGroupEither.right().value()); + * resEither = Either.right(dissotiateGroupEither.right().value()); return resEither; + * + * } + */ } if (!artifactsToUpdateMap.isEmpty()) { @@ -1825,6 +2264,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) { arifactsUids.add(createdArtifact.getUniqueId()); isCreate = false; + String heatEnvId = checkAndGetHeatEnvId(createdArtifact); + if (!heatEnvId.isEmpty()) { + arifactsUids.add(heatEnvId); + Optional op = createdDeplymentArtifactsAfterDelete.stream().filter(p -> p.getUniqueId().equals(heatEnvId)).findAny(); + if (op.isPresent()) { + this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource.getUniqueId(), resource.getComponentType().getNodeType()); + + } + } + break; } @@ -1834,18 +2283,33 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) { arifactsUids.add(createdNewArtifact.getUniqueId()); isCreate = false; + String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact); + if (!heatEnvId.isEmpty()) { + arifactsUids.add(heatEnvId); + } break; } } } if (isCreate) { - Either createArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction); + Either createArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction); if (createArtifactEither.isRight()) { resEither = Either.right(createArtifactEither.right().value()); return resEither; } - arifactsUids.add(createArtifactEither.left().value().getUniqueId()); + ArtifactDefinition createdArtifact = createArtifactEither.left().value(); + arifactsUids.add(createdArtifact.getUniqueId()); + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType()); + if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) { + Either createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource, + resource.getName(), user, resource, null); + if (createHeatEnvPlaceHolder.isRight()) { + return Either.right(createHeatEnvPlaceHolder.right().value()); + } + String heatEnvId = createHeatEnvPlaceHolder.left().value().getUniqueId(); + arifactsUids.add(heatEnvId); + } } } @@ -1860,18 +2324,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } - if (!associateArtifactGroup.isEmpty()) { - - log.debug("Try to associate artifacts to groups."); - - Either, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateArtifactsToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, associateArtifactGroup, shouldLock, inTransaction); - if (assotiateGroupEither.isRight()) { - log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value()); - resEither = Either.right(assotiateGroupEither.right().value()); - return resEither; - - } - } + /* + * if (!associateArtifactGroup.isEmpty()) { + * + * log.debug("Try to associate artifacts to groups."); + * + * Either, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateArtifactsToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, associateArtifactGroup, shouldLock, inTransaction); if + * (assotiateGroupEither.isRight()) { log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value()); resEither = Either.right(assotiateGroupEither.right().value()); return resEither; + * + * } } + */ ComponentParametersView parametersView = new ComponentParametersView(); parametersView.disableAll(); @@ -1879,7 +2341,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { parametersView.setIgnoreUsers(false); parametersView.setIgnoreArtifacts(false); parametersView.setIgnoreGroups(false); - Either eitherGerResource = resourceOperation.getComponent(resource.getUniqueId(), parametersView, inTransaction); + + Either eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView); if (eitherGerResource.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); @@ -1893,7 +2356,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } private Map mergeGroupInUpdateFlow(Map>> groupArtifact, Map> parsedGroup, - Set artifactsToDelete, Map> groupToDelete, Set jsonMasterArtifacts) { + Set artifactsToDelete, Map> groupToDelete, Set jsonMasterArtifacts, List createdDeplymentArtifacts) { Map mergedgroup = new HashMap(); for (Entry>> groupListEntry : groupArtifact.entrySet()) { Map> createdArtifactMap = groupListEntry.getValue(); @@ -1902,7 +2365,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) { listToDelete = createdArtifactMap.get(maserArtifact); for (ArtifactDefinition artToDelete : listToDelete) { - findArtifactToDelete(parsedGroup, artifactsToDelete, groupListEntry.getKey().getUniqueId(), artToDelete); + findArtifactToDelete(parsedGroup, artifactsToDelete, groupListEntry.getKey().getUniqueId(), artToDelete, createdDeplymentArtifacts); } for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) { if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) { @@ -1950,19 +2413,37 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return artifactNotInGroupSet; } - private void findArtifactToDelete(Map> parsedGroup, Set artifactsToDelete, String deleteGroupId, ArtifactDefinition artifact) { + private void findArtifactToDelete(Map> parsedGroup, Set artifactsToDelete, String deleteGroupId, ArtifactDefinition artifact, + List createdDeplymentArtifacts) { boolean isNeedToDeleteArtifact = true; + String artifactType = artifact.getArtifactType(); + ArtifactDefinition generatedFromArt = null; + if (artifact.getGeneratedFromId() != null && !artifact.getGeneratedFromId().isEmpty()) { + Optional op = createdDeplymentArtifacts.stream().filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())).findAny(); + if (op.isPresent()) + generatedFromArt = op.get(); + + } + for (Entry> parsedGroupSetEntry : parsedGroup.entrySet()) { Set artifactsNames = parsedGroupSetEntry.getValue(); for (ArtifactTemplateInfo template : artifactsNames) { - if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) && artifact.getArtifactType().equalsIgnoreCase(template.getType())) { + if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) && artifactType.equalsIgnoreCase(template.getType())) { isNeedToDeleteArtifact = false; + break; + } else { + if (generatedFromArt != null) { + if (generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName()) && generatedFromArt.getArtifactType().equalsIgnoreCase(template.getType())) { + isNeedToDeleteArtifact = false; + break; + } + } } } + } if (isNeedToDeleteArtifact) { - artifactsToDelete.add(artifact); } @@ -2017,7 +2498,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } log.debug("createResourceArtifacts end"); log.debug("getResource start"); - Either eitherGerResource = resourceOperation.getResource(resource.getUniqueId(), inTransaction); + Either eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); log.debug("getResource end"); if (eitherGerResource.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); @@ -2035,35 +2516,31 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { List createdGroups = resource.getGroups(); List heatGroups = null; if (createdGroups != null && !createdGroups.isEmpty()) { - - // List collect = resources.stream().flatMap( e -> - // e.getArtifacts().stream()).filter(p -> - // relevantArtifactTypes.contains(p.getArtifactType() - // )).collect(Collectors.toList()); - // List heatGroups = createdGroups.stream().filter( - // e -> e.getProperties().stream().filter(p -> - // p.getName().contains(Constants.HEAT_FILE_PROPS))).collect(Collectors.toList()); heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList()); - ; } + List needToAdd = new ArrayList<>(); for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) { String groupName = groupTemplateInfo.getGroupName(); Set artifactsGroup = new HashSet(); + Set artifactsUUIDGroup = new HashSet(); - resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction); + resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction); if (resStatus.isRight()) return resStatus; Map members = new HashMap(); - associateMembersTToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, members); + associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, members); List artifactsList = new ArrayList(artifactsGroup); + List artifactsUUIDList = new ArrayList(artifactsUUIDGroup); GroupDefinition groupDefinition = new GroupDefinition(); groupDefinition.setName(groupName); groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE); groupDefinition.setArtifacts(artifactsList); + groupDefinition.setArtifactsUuid(artifactsUUIDList); + if (!members.isEmpty()) groupDefinition.setMembers(members); @@ -2072,21 +2549,49 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { prop.setName(Constants.IS_BASE); prop.setValue(Boolean.toString(groupTemplateInfo.isBase())); - properties.add(prop); - groupDefinition.setProperties(properties); - Either createGroup = groupBusinessLogic.createGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction); - if (createGroup.isRight()) - return Either.right(createGroup.right().value()); + List createdArtifacts = new ArrayList<>(); + createdArtifacts.addAll(createdNewArtifacts); + createdArtifacts.addAll(artifactsFromResource); + Either getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true); + if (getLatestGroupTypeRes.isRight()) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value()))); + } + properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value()); + groupDefinition.convertFromGroupProperties(properties); + properties.add(prop); + groupDefinition.convertFromGroupProperties(properties); + // Either createGroup = groupBusinessLogic.createGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction); + // if (createGroup.isRight()) + // return Either.right(createGroup.right().value()); + needToAdd.add(groupDefinition); + } + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreArtifacts(false); + componentParametersView.setIgnoreGroups(false); + componentParametersView.setIgnoreComponentInstances(false); + + Either component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView); + if (component.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } + resource = component.left().value(); + + Either, ResponseFormat> addGroups = groupBusinessLogic.addGroups(resource, user, ComponentTypeEnum.RESOURCE, needToAdd); + if (addGroups.isRight()) + return Either.right(addGroups.right().value()); + return resStatus; } - private Either createDeploymentArtifactsFromCsar(String csarUUID, Map csar, Resource resource, User user, Set artifactsGroup, ArtifactTemplateInfo artifactTemplateInfo, - List createdArtifacts, List artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) { + private Either createDeploymentArtifactsFromCsar(String csarUUID, Map csar, Resource resource, User user, Set artifactsGroup, Set artifactsUUIDGroup, + ArtifactTemplateInfo artifactTemplateInfo, List createdArtifacts, List artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) { Either resStatus = Either.left(resource); String artifactFileName = artifactTemplateInfo.getFileName(); String artifactUid = ""; + String artifactUUID = ""; + String artifactEnvUid = ""; boolean alreadyExist = false; // check if artifacts already exist @@ -2094,12 +2599,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { for (ArtifactDefinition artifactFromResource : artifactsFromResource) { if (artifactFromResource.getArtifactName().equals(artifactFileName)) { artifactUid = artifactFromResource.getUniqueId(); + artifactUUID = artifactFromResource.getArtifactUUID(); if (!artifactFromResource.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType()); BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType())); } alreadyExist = true; + artifactEnvUid = checkAndGetHeatEnvId(artifactFromResource); break; } @@ -2110,12 +2617,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { for (ArtifactDefinition createdArtifact : createdArtifacts) { if (createdArtifact.getArtifactName().equals(artifactFileName)) { artifactUid = createdArtifact.getUniqueId(); + artifactUUID = createdArtifact.getArtifactUUID(); + if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()); BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType())); } alreadyExist = true; + artifactEnvUid = checkAndGetHeatEnvId(createdArtifact); break; } @@ -2124,21 +2634,35 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { // if not exist need to create if (!alreadyExist) { - Either newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction); + Either newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction); if (newArtifactEither.isRight()) { resStatus = Either.right(newArtifactEither.right().value()); return resStatus; } - artifactUid = newArtifactEither.left().value().getUniqueId(); - + ArtifactDefinition newArtifact = newArtifactEither.left().value(); + artifactUid = newArtifact.getUniqueId(); + artifactUUID = newArtifact.getArtifactUUID(); + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType()); + if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) { + Either createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource, + resource.getName(), user, resource, null); + if (createHeatEnvPlaceHolder.isRight()) { + return Either.right(createHeatEnvPlaceHolder.right().value()); + } + artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId(); + } } artifactsGroup.add(artifactUid); + artifactsUUIDGroup.add(artifactUUID); + if (!artifactEnvUid.isEmpty()) { + artifactsGroup.add(artifactEnvUid); + } List relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); if (relatedArtifacts != null) { for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) { - resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction); + resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction); if (resStatus.isRight()) return resStatus; } @@ -2165,6 +2689,121 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } + private Either createOrUpdateNonMetaArtifacts(String csarUUID, Map csar, Resource resource, User user, List createdArtifacts, boolean shouldLock, boolean inTransaction, + ArtifactOperationInfo artifactOperation) { + + Either resStatus = null; + Map>> collectedWarningMessages = new HashMap<>(); + + try { + List artifactPathAndNameList = + // Stream of file paths contained in csar + csar.entrySet().stream() + // Filter in only VF artifact path location + .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches()) + // Validate and add warnings + .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages)) + // Filter in Non Warnings + .filter(e -> e.isLeft()) + // Convert from Either to NonMetaArtifactInfo + .map(e -> e.left().value()) + // collect to List + .collect(Collectors.toList()); + + EnumMap> vfCsarArtifactsToHandle = null; + + if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) { + vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); + vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList); + } else { + Either>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(resource, artifactPathAndNameList, user); + + if (findVfCsarArtifactsToHandleRes.isRight()) { + resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value()); + } + if (resStatus == null) { + vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value(); + } + } + if (resStatus == null && vfCsarArtifactsToHandle != null) { + for (Entry> currArtifactOperationPair : vfCsarArtifactsToHandle.entrySet()) { + + Optional optionalCreateInDBError = + // Stream of artifacts to be created + currArtifactOperationPair.getValue().stream() + // create each artifact + .map(e -> createOrUpdateSingleNonMetaArtifact(resource, user, csarUUID, csar, e.getPath(), e.getArtifactName(), e.getArtifactType().getType(), e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), + CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), artifactsBusinessLogic.new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, shouldLock, + inTransaction)) + // filter in only error + .filter(e -> e.isRight()). + // Convert the error from either to ResponseFormat + map(e -> e.right().value()). + // Check if an error occurred + findAny(); + // Error found on artifact Creation + if (optionalCreateInDBError.isPresent()) { + resStatus = Either.right(optionalCreateInDBError.get()); + break; + } + } + } + if (resStatus == null) { + resStatus = Either.left(resource); + } + } catch (Exception e) { + resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e); + } finally { + CsarUtils.handleWarningMessages(collectedWarningMessages); + } + return resStatus; + } + + private Either>, ResponseFormat> findVfCsarArtifactsToHandle(Resource resource, List artifactPathAndNameList, User user) { + + List existingArtifacts = new ArrayList<>(); + // collect all Deployment and Informational artifacts of VF + if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) { + existingArtifacts.addAll(resource.getDeploymentArtifacts().values()); + } + if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) { + existingArtifacts.addAll(resource.getArtifacts().values()); + } + existingArtifacts = existingArtifacts.stream() + // filter MANDATORY artifacts, LICENSE artifacts and artifacts was created from HEAT.meta + .filter(this::isNonMetaArtifact).collect(Collectors.toList()); + + List artifactsToIgnore = new ArrayList<>(); + // collect IDs of Artifacts of VF which belongs to any group + if (resource.getGroups() != null) { + resource.getGroups().stream().forEach(g -> { + if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) + artifactsToIgnore.addAll(g.getArtifacts()); + }); + } + existingArtifacts = existingArtifacts.stream() + // filter artifacts which belongs to any group + .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(Collectors.toList()); + return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user); + } + + private boolean isNonMetaArtifact(ArtifactDefinition artifact) { + boolean result = true; + if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) { + result = false; + } + return result; + } + + private boolean isValidArtifactType(ArtifactDefinition artifact) { + boolean result = true; + if (artifact.getArtifactType() == null || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) { + result = false; + } + return result; + } + private Either createGroupDeploymentArtifactsFromCsar(String csarUUID, Map csar, Resource resource, User user, List artifactsTemplateList, List createdArtifacts, int labelCounter, boolean shouldLock, boolean inTransaction) { Either resStatus = Either.left(resource); @@ -2182,67 +2821,146 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList()); ; } + List needToCreate = new ArrayList<>(); for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) { String groupName = groupTemplateInfo.getGroupName(); Set artifactsGroup = new HashSet(); + Set artifactsUUIDGroup = new HashSet(); log.debug("createDeploymentArtifactsFromCsar start"); - resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction); + resStatus = createDeploymentArtifactFromCsar(csarUUID, ARTIFACTS_PATH, csar, resource, user, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction); log.debug("createDeploymentArtifactsFromCsar end"); if (resStatus.isRight()) return resStatus; Map members = new HashMap(); - associateMembersTToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members); + associateMembersToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members); List artifactsList = new ArrayList(artifactsGroup); + List artifactsUUIDList = new ArrayList(artifactsUUIDGroup); GroupDefinition groupDefinition = new GroupDefinition(); groupDefinition.setName(groupName); groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE); groupDefinition.setArtifacts(artifactsList); + groupDefinition.setArtifactsUuid(artifactsUUIDList); + if (!members.isEmpty()) groupDefinition.setMembers(members); List properties = new ArrayList(); GroupProperty prop = new GroupProperty(); prop.setName(Constants.IS_BASE); prop.setValue(Boolean.toString(groupTemplateInfo.isBase())); - properties.add(prop); - groupDefinition.setProperties(properties); + Either getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true); + if (getLatestGroupTypeRes.isRight()) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value()))); + } + properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value()); + groupDefinition.convertFromGroupProperties(properties); log.debug("createGroup start"); - // Either createGroup = - // groupBusinessLogic.createGroup(resource.getUniqueId(), - // user.getUserId(), ComponentTypeEnum.RESOURCE, groupDefinition, - // inTransaction); - // Ignore validations and get component // Since in these groups we handle only artifacts, then no need to // fetch component instances - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreUsers(false); - componentParametersView.setIgnoreArtifacts(false); - componentParametersView.setIgnoreGroups(false); - componentParametersView.setIgnoreComponentInstances(false); - Either component = resourceOperation.getComponent(resource.getUniqueId(), componentParametersView, inTransaction); - if (component.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - Either createGroup = groupBusinessLogic.createGroup(component.left().value(), user, ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction); - log.debug("createGroup end"); - if (createGroup.isRight()) - return Either.right(createGroup.right().value()); + // Either createGroup = groupBusinessLogic.createGroup(comp, user, ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction); + // log.debug("createGroup end"); + // if (createGroup.isRight()) + // return Either.right(createGroup.right().value()); + needToCreate.add(groupDefinition); + } + + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreUsers(false); + componentParametersView.setIgnoreArtifacts(false); + componentParametersView.setIgnoreGroups(false); + componentParametersView.setIgnoreComponentInstances(false); + + Either component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView); + if (component.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } + + Either, ResponseFormat> createGroups = groupBusinessLogic.addGroups(component.left().value(), user, ComponentTypeEnum.RESOURCE, needToCreate); + if (createGroups.isRight()) { + return Either.right(createGroups.right().value()); + } + return resStatus; } - private void associateMembersTToArtifacts(List createdArtifacts, List artifactsFromResource, List heatGroups, Set artifactsGroup, Map members) { + public List createVfModuleAdditionalProperties(boolean isBase, String moduleName, List properties, List deploymentArtifacts, List artifactsInGroup, GroupTypeDefinition groupType) { + Map vfModuleProperties = ConfigurationManager.getConfigurationManager().getConfiguration().getVfModuleProperties(); + vfModuleProperties.entrySet().forEach(p -> { + GroupProperty prop = new GroupProperty(); + prop.setName(p.getKey()); + if (isBase) { + prop.setValue(p.getValue().getForBaseModule()); + prop.setDefaultValue(p.getValue().getForBaseModule()); + } else { + prop.setValue(p.getValue().getForNonBaseModule()); + prop.setDefaultValue(p.getValue().getForNonBaseModule()); + } + properties.add(prop); + + }); + GroupProperty proplabel = new GroupProperty(); + proplabel.setName("vf_module_label"); + + Matcher matcher = pattern.matcher(moduleName); + + if (matcher.find()) { + proplabel.setValue(matcher.group(1)); + proplabel.setDefaultValue(matcher.group(1)); + } else { + proplabel.setValue(moduleName); + proplabel.setDefaultValue(moduleName); + } + properties.add(proplabel); + + GroupProperty propvolume = new GroupProperty(); + propvolume.setName("volume_group"); + boolean isVolume = false; + for (String artifactId : artifactsInGroup) { + ArtifactDefinition artifactDef = null; + artifactDef = findArtifactInList(deploymentArtifacts, artifactId); + if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) { + isVolume = true; + break; + } + } + propvolume.setValue(String.valueOf(isVolume)); + propvolume.setDefaultValue(String.valueOf(isVolume)); + properties.add(propvolume); + mergeWithGroupTypeProperties(properties, groupType.getProperties()); + return properties; + } + + private void mergeWithGroupTypeProperties(List properties, List groupTypeProperties) { + + Map propertiesMap = properties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); + for (PropertyDefinition groupTypeProperty : groupTypeProperties) { + if (!propertiesMap.containsKey(groupTypeProperty.getName())) { + properties.add(new GroupProperty(groupTypeProperty)); + } + } + } + + private ArtifactDefinition findArtifactInList(List createdArtifacts, String artifactId) { + for (ArtifactDefinition artifact : createdArtifacts) { + if (artifact.getUniqueId().equals(artifactId)) { + return artifact; + } + } + return null; + } + + private void associateMembersToArtifacts(List createdArtifacts, List artifactsFromResource, List heatGroups, Set artifactsGroup, Map members) { if (heatGroups != null && !heatGroups.isEmpty()) { for (GroupDefinition heatGroup : heatGroups) { - List grpoupProps = heatGroup.getProperties(); + List grpoupProps = heatGroup.convertToGroupProperties(); if (grpoupProps != null) { Optional op = grpoupProps.stream().filter(p -> p.getName().equals(Constants.HEAT_FILE_PROPS)).findAny(); if (op.isPresent()) { @@ -2274,45 +2992,63 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } - private Either createDeploymentArtifactsFromCsar(String csarUUID, Map csar, Resource resource, User user, Set artifactsGroup, ArtifactTemplateInfo artifactTemplateInfo, - List createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) { + private Either createDeploymentArtifactFromCsar(String csarUUID, String artifactPath, Map csar, Resource resource, User user, Set artifactsGroup, Set artifactsUUIDGroup, + ArtifactTemplateInfo artifactTemplateInfo, List createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) { Either resStatus = Either.left(resource); String artifactFileName = artifactTemplateInfo.getFileName(); String artifactUid = ""; + String artifactEnvUid = ""; + String artifactUUID = ""; boolean alreadyExist = false; // check if artifacts already exist for (ArtifactDefinition createdArtifact : createdArtifacts) { if (createdArtifact.getArtifactName().equals(artifactFileName)) { artifactUid = createdArtifact.getUniqueId(); + artifactUUID = createdArtifact.getArtifactUUID(); if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()); BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType())); } alreadyExist = true; + artifactEnvUid = checkAndGetHeatEnvId(createdArtifact); break; } - } // if not exist need to create if (!alreadyExist) { - Either newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction); + Either newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction); if (newArtifactEither.isRight()) { resStatus = Either.right(newArtifactEither.right().value()); return resStatus; } - artifactUid = newArtifactEither.left().value().getUniqueId(); + ArtifactDefinition newArtifact = newArtifactEither.left().value(); + artifactUid = newArtifact.getUniqueId(); + artifactUUID = newArtifact.getArtifactUUID(); + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType()); + if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) { + Either createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource, + resource.getName(), user, resource, null); + if (createHeatEnvPlaceHolder.isRight()) { + return Either.right(createHeatEnvPlaceHolder.right().value()); + } + artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId(); + } } artifactsGroup.add(artifactUid); + artifactsUUIDGroup.add(artifactUUID); + if (!artifactEnvUid.isEmpty()) { + artifactsGroup.add(artifactEnvUid); + } List relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); if (relatedArtifacts != null) { for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) { - resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction); + resStatus = createDeploymentArtifactFromCsar(csarUUID, artifactPath, csar, resource, user, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction); if (resStatus.isRight()) return resStatus; } @@ -2320,17 +3056,28 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return resStatus; } - private Either createDeploymentArtifact(String csarUUID, Map csar, Resource resource, User user, ArtifactTemplateInfo artifactTemplateInfo, List createdArtifacts, - int labelCounter, boolean shoudLock, boolean inTransaction) { - String artifactUid; - Either, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactTemplateInfo.getFileName(), componentsUtils); - if (artifactContententStatus.isRight()) + private String checkAndGetHeatEnvId(ArtifactDefinition createdArtifact) { + String artifactEnvUid = ""; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType()); + if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) { + artifactEnvUid = createdArtifact.getUniqueId() + ArtifactsBusinessLogic.HEAT_ENV_SUFFIX; + } + return artifactEnvUid; + } + + private Either createDeploymentArtifact(String csarUUID, Map csar, Resource resource, User user, String artifactPath, ArtifactTemplateInfo artifactTemplateInfo, + List createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) { + final String artifactFileName = artifactTemplateInfo.getFileName(); + Either, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactPath + artifactFileName, artifactFileName, componentsUtils); + if (artifactContententStatus.isRight()) { return Either.right(artifactContententStatus.right().value()); + } labelCounter += createdArtifacts.size(); Map json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter); - Either, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, ArtifactOperation.Create, shoudLock, inTransaction); + Either, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), + shoudLock, inTransaction); if (uploadArtifactToService.isRight()) return Either.right(uploadArtifactToService.right().value()); @@ -2338,21 +3085,40 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value(); if (currentInfo.getHeatParameters() != null) { - Either updateEnvEither = updateHeatParamsFromCsar(csarUUID, csar, artifactTemplateInfo, currentInfo); + Either updateEnvEither = updateHeatParamsFromCsar(resource, csarUUID, csar, artifactTemplateInfo, currentInfo, false); if (updateEnvEither.isRight()) { - log.debug("failed to update parameters to artifact {}", artifactTemplateInfo.getFileName()); + log.debug("failed to update parameters to artifact {}", artifactFileName); return Either.right(updateEnvEither.right().value()); } - artifactUid = updateEnvEither.left().value().getUniqueId(); - createdArtifacts.add(updateEnvEither.left().value()); currentInfo = updateEnvEither.left().value(); - } else { - - artifactUid = currentInfo.getUniqueId(); - createdArtifacts.add(currentInfo); } + + createdArtifacts.add(currentInfo); + + return Either.left(currentInfo); + + } + + private Either createInformationalArtifact(String csarUUID, Map csar, Resource resource, User user, ArtifactTemplateInfo artifactTemplateInfo, int labelCounter, boolean shoudLock, + boolean inTransaction) { + final String artifactFileName = artifactTemplateInfo.getFileName(); + String artifactPath = CsarUtils.ARTIFACTS_PATH + CsarUtils.INFORMATIONAL_ARTIFACTS + artifactFileName; + Either, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactPath, artifactFileName, componentsUtils); + if (artifactContententStatus.isRight()) + return Either.right(artifactContententStatus.right().value()); + + Map json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter); + + Either, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), + shoudLock, inTransaction); + + if (uploadArtifactToService.isRight()) + return Either.right(uploadArtifactToService.right().value()); + + ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value(); + return Either.left(currentInfo); } @@ -2380,15 +3146,17 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } - Either, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactTemplateInfo.getFileName(), componentsUtils); + Either, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils); if (artifactContententStatus.isRight()) { resStatus = Either.right(artifactContententStatus.right().value()); return resStatus; } - Map json = buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, oldArtifact.getArtifactType(), oldArtifact.getArtifactLabel(), oldArtifact.getArtifactDisplayName(), oldArtifact.getDescription(), - artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts); - Either, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, ArtifactOperation.Update, shouldLock, inTransaction); + Map json = buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(), oldArtifact.getArtifactDisplayName(), + oldArtifact.getDescription(), artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts); + + Either, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), + shouldLock, inTransaction); if (uploadArtifactToService.isRight()) { resStatus = Either.right(uploadArtifactToService.right().value()); @@ -2396,12 +3164,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value(); - Either updateEnvEither = updateHeatParamsFromCsar(csarUUID, csar, artifactTemplateInfo, currentInfo); + Either updateEnvEither = updateHeatParamsFromCsar(resource, csarUUID, csar, artifactTemplateInfo, currentInfo, true); if (updateEnvEither.isRight()) { log.debug("failed to update parameters to artifact {}", artifactFileName); resStatus = Either.right(updateEnvEither.right().value()); return resStatus; } + // TODO evg update env time ( must be separate US for this!!!!) artifactUid = updateEnvEither.left().value().getUniqueId(); updatedArtifacts.add(updateEnvEither.left().value()); @@ -2411,70 +3180,79 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } - private Either updateHeatParamsFromCsar(String csarUUID, Map csar, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo) { + private Either updateHeatParamsFromCsar(Resource resource, String csarUUID, Map csar, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) { Either resStatus = Either.left(currentInfo); if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) { - Either, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactTemplateInfo.getEnv(), componentsUtils); + Either, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(), + componentsUtils); if (artifactparamsStatus.isRight()) { resStatus = Either.right(artifactparamsStatus.right().value()); return resStatus; } - Either, ResponseFormat> propsStatus = extractHeatParameters(ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(), artifactparamsStatus.left().value().getValue()); - if (propsStatus.isRight()) { - - resStatus = Either.right(propsStatus.right().value()); - return resStatus; - } - List updatedHeatEnvParams = propsStatus.left().value(); - List currentHeatEnvParams = currentInfo.getHeatParameters(); - List newHeatEnvParams = new ArrayList(); - - if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) { - - String paramName; - for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { - - paramName = heatEnvParam.getName(); - for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { - if (paramName.equalsIgnoreCase(currHeatParam.getName())) { - - String updatedParamValue = heatEnvParam.getCurrentValue(); - if (updatedParamValue == null) - updatedParamValue = heatEnvParam.getDefaultValue(); - HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType()); - if (!paramType.getValidator().isValid(updatedParamValue, null)) { - ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE; - ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName); - resStatus = Either.right(responseFormat); - return resStatus; + Either, ResponseFormat> propsStatus = extractHeatParameters(ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(), artifactparamsStatus.left().value().getValue(), false); + /* + * if (propsStatus.isRight()) { + * + * resStatus = Either.right(propsStatus.right().value()); return resStatus; } + */ + if (propsStatus.isLeft()) { + List updatedHeatEnvParams = propsStatus.left().value(); + List currentHeatEnvParams = currentInfo.getListHeatParameters(); + // List newHeatEnvParams = new ArrayList(); + + if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) { + + String paramName; + for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { + + paramName = heatEnvParam.getName(); + for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { + if (paramName.equalsIgnoreCase(currHeatParam.getName())) { + + String updatedParamValue = heatEnvParam.getCurrentValue(); + if (updatedParamValue == null) + updatedParamValue = heatEnvParam.getDefaultValue(); + HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType()); + if (!paramType.getValidator().isValid(updatedParamValue, null)) { + ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE; + ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName); + resStatus = Either.right(responseFormat); + return resStatus; + } + currHeatParam.setCurrentValue(HeatParameterType.isValidType(currHeatParam.getType()).getConverter().convert(updatedParamValue, null, null)); + // newHeatEnvParams.add(currHeatParam); + break; } - currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null)); - newHeatEnvParams.add(currHeatParam); - break; } } - } - if (!newHeatEnvParams.isEmpty()) { - StorageOperationStatus operationStatus = heatParametersOperation.updateHeatParameters(currentHeatEnvParams); - - if (operationStatus != StorageOperationStatus.OK) { - log.debug("Failed to update artifact on graph - {}", currentInfo.getUniqueId()); - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus)); - resStatus = Either.right(responseFormat); - return resStatus; + currentInfo.setListHeatParameters(currentHeatEnvParams); + Either updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(currentInfo, resource.getUniqueId(), currentInfo.getUniqueId(), null, null); + if (updateArifactOnResource.isRight()) { + log.debug("Failed to update heat paratemers of heat on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), currentInfo.getUniqueId(), currentInfo.getArtifactLabel()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value()))); } } } - + } + if (isUpdateEnv) { + Map artifacts = resource.getDeploymentArtifacts(); + Optional op = artifacts.values().stream().filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId())).findAny(); + if (op.isPresent()) { + ArtifactDefinition artifactInfoHeatEnv = op.get(); + Either updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(artifactInfoHeatEnv, resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), null, null); + if (updateArifactOnResource.isRight()) { + log.debug("Failed to update heat env on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), artifactInfoHeatEnv.getArtifactLabel()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value()))); + } + } } return resStatus; } - private Either, ResponseFormat> extractHeatParameters(String artifactType, String fileName, byte[] content) { + private Either, ResponseFormat> extractHeatParameters(String artifactType, String fileName, byte[] content, boolean is64Encoded) { // extract heat parameters - String heatDecodedPayload = GeneralUtility.isBase64Encoded(content) ? new String(Base64.decodeBase64(content)) : new String(content); + String heatDecodedPayload = is64Encoded ? new String(Base64.decodeBase64(content)) : new String(content); Either, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactType); if (heatParameters.isRight()) { log.debug("File {} is not in expected key-value form in csar ", fileName); @@ -2495,15 +3273,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { json.put(Constants.ARTIFACT_TYPE, artifactTemplateInfo.getType()); json.put(Constants.ARTIFACT_DESCRIPTION, "created from csar"); - /* - * DE250204 - * There is no need to check if base64 encoding. All files that are inside the CSAR are not encoded and need to encoded. The check for isBase64 is not in cases we get files with extension .cert or .key these files are base64 but if do not - * encode them again, when the user download them, the decoded file will return not the encoded file that was upload. - */ + // DE250204: There is no need to check if base64 encoding. + // String encodedPayload = new String(artifactContentent); // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent); // if (!isEncoded) { - // log.debug("payload is encoded. perform decode"); String encodedPayload = Base64.encodeBase64String(artifactContentent); // } json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload); @@ -2520,7 +3294,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return json; } - private Map buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, String label, String displayName, String description, byte[] artifactContentent, + private Map buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContentent, List updatedRequiredArtifacts) { Map json = new HashMap(); @@ -2532,17 +3306,17 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { json.put(Constants.ARTIFACT_DESCRIPTION, description); String encodedPayload = new String(artifactContentent); - // DE250204 - need to encode all. - //boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent); - //if (!isEncoded) { - log.debug("payload is encoded. perform decode"); - encodedPayload = Base64.encodeBase64String(artifactContentent); - //} + + // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent); + // if (!isEncoded) { + log.debug("payload is encoded. perform decode"); + encodedPayload = Base64.encodeBase64String(artifactContentent); + // } json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload); json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName); json.put(Constants.ARTIFACT_LABEL, label); - json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType()); + json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType()); json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>() : updatedRequiredArtifacts.stream().filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())).map(e -> e.getFileName()).collect(Collectors.toList())); return json; @@ -2642,23 +3416,34 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.right(responseFormat); } - Map> propertiesListPerResource = new HashMap<>(); + log.debug("Before validateAndUpdatePropertyValue"); + Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName); - long totalCreateRel = 0; - long totalCreatePropVal = 0; - Iterator> nodesInfoValue = uploadResInstancesMap.entrySet().iterator(); - while (nodesInfoValue.hasNext()) { - Entry uploadComponentInstanceInfoEntry = nodesInfoValue.next(); - UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue(); + } + + Map> instProperties = new HashMap<>(); + Map>> instCapabilties = new HashMap<>(); + Map>> instRequirements = new HashMap<>(); + Map> instArtifacts = new HashMap<>(); + Map> instAttributes = new HashMap<>(); + Map originCompMap = new HashMap<>(); + List relations = new ArrayList<>(); + for (Entry entry : uploadResInstancesMap.entrySet()) { + UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue(); ComponentInstance currentCompInstance = null; for (ComponentInstance compInstance : componentInstancesList) { + if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) { currentCompInstance = compInstance; break; } - } + } if (currentCompInstance == null) { log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId()); BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR); @@ -2666,107 +3451,115 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.right(responseFormat); } String resourceInstanceId = currentCompInstance.getUniqueId(); - - log.debug("************* addPropertyValuesToRi start"); - long startAddProperty = System.currentTimeMillis(); - - ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, resourceInstanceId, currentCompInstance, yamlName, propertiesListPerResource); - log.debug("************* addPropertyValuesToRi end"); - totalCreatePropVal += (System.currentTimeMillis() - startAddProperty); - + Resource originResource = null; + if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) { + Either getPropertyRes = toscaOperationFacade.getToscaFullElement(currentCompInstance.getComponentUid()); + if (getPropertyRes.isRight()) { + log.debug("failed to find properties of resource {} status is {}", currentCompInstance.getComponentUid(), getPropertyRes); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getPropertyRes.right().value()), yamlName); + return Either.right(responseFormat); + } + originResource = getPropertyRes.left().value(); + originCompMap.put(originResource.getUniqueId(), originResource); + } else { + originResource = originCompMap.get(currentCompInstance.getComponentUid()); + } + if (originResource.getCapabilities() != null && !originResource.getCapabilities().isEmpty()) + instCapabilties.put(currentCompInstance, originResource.getCapabilities()); + if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty()) + instRequirements.put(currentCompInstance, originResource.getRequirements()); + if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) + instArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts()); + if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) + instAttributes.put(resourceInstanceId, originResource.getAttributes()); + + ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value()); if (addPropertiesValueToRiRes.getStatus() != 200) { return Either.right(addPropertiesValueToRiRes); } - Map> regMap = uploadComponentInstanceInfo.getRequirements(); - if (regMap == null) - continue; - Iterator>> nodesRegValue = regMap.entrySet().iterator(); - - long startAddRelation = System.currentTimeMillis(); - - while (nodesRegValue.hasNext()) { - Entry> nodesRegInfoEntry = nodesRegValue.next(); - - List uploadRegInfoList = nodesRegInfoEntry.getValue(); - for (UploadReqInfo uploadRegInfo : uploadRegInfoList) { - log.debug("Going to create relation {}", uploadRegInfo.getName()); - String regName = uploadRegInfo.getName(); - String nodeCapName = uploadRegInfo.getNode(); - RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef(); - regCapRelDef.setFromNode(resourceInstanceId); - log.debug("try to find available requirement {} ", regName); - Either eitherReqStatus = findAviableRequiremen(regName, yamlName, uploadComponentInstanceInfo, currentCompInstance); - if (eitherReqStatus.isRight()) { - log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value()); - return Either.right(eitherReqStatus.right().value()); - } - RequirementDefinition validReq = eitherReqStatus.left().value(); - List reqAndRelationshipPairList = regCapRelDef.getRelationships(); - if (reqAndRelationshipPairList == null) - reqAndRelationshipPairList = new ArrayList(); - RequirementAndRelationshipPair reqAndRelationshipPair = new RequirementAndRelationshipPair(); - reqAndRelationshipPair.setRequirement(regName); - reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId()); - reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId()); - - ComponentInstance currentCapCompInstance = null; - for (ComponentInstance compInstance : componentInstancesList) { - if (compInstance.getName().equals(uploadRegInfo.getNode())) { - currentCapCompInstance = compInstance; - break; - } - } + } - if (currentCapCompInstance == null) { - log.debug("component instance with name {} in resource {} ", uploadRegInfo.getNode(), resource.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadRegInfo.getNode() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - return Either.right(responseFormat); - } - regCapRelDef.setToNode(currentCapCompInstance.getUniqueId()); - log.debug("try to find aviable Capability req name is {} ", validReq.getName()); - CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo); - if (aviableCapForRel == null) { - log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(), currentCapCompInstance.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError("aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance.getUniqueId(), resource.getUniqueId(), - ErrorSeverity.ERROR); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - return Either.right(responseFormat); - } - reqAndRelationshipPair.setCapability(aviableCapForRel.getName()); - reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId()); - reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId()); - reqAndRelationshipPairList.add(reqAndRelationshipPair); - regCapRelDef.setRelationships(reqAndRelationshipPairList); - ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(); - Either eitherRelationRes = componentInstanceBL.associateRIToRIOnGraph(resource.getUniqueId(), regCapRelDef, ComponentTypeEnum.RESOURCE, inTransaction); - log.debug("************* finished to create relation {}", uploadRegInfo.getName()); - if (eitherRelationRes.isRight()) { - log.debug("failed to associate ri {} to ri {}", regCapRelDef.getFromNode(), regCapRelDef.getToNode()); - return Either.right(eitherRelationRes.right().value()); - } + Either>, StorageOperationStatus> addPropToInst = toscaOperationFacade.associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId()); + if (addPropToInst.isRight()) { + log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName); + return Either.right(responseFormat); + } - } + StorageOperationStatus addArtToInst = toscaOperationFacade.associateArtifactToInstances(instArtifacts, resource.getUniqueId(), user); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + return Either.right(responseFormat); + } - } - totalCreateRel += (System.currentTimeMillis() - startAddRelation); + addArtToInst = toscaOperationFacade.associateCalculatedCapReq(instCapabilties, instRequirements, resource.getUniqueId()); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + return Either.right(responseFormat); + } + + addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource.getUniqueId()); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + return Either.right(responseFormat); } - /* - * List inputs = resource.getInputs(); for(InputDefinition input: inputs){ if(input.getProperties() != null){ this.inputOperation.associatePropertiesToInputOnGraph(input. getUniqueId(), input.getProperties()); } } - */ - // Either eitherGerResource = - // resourceOperation.getResource(resource.getUniqueId(), inTransaction); - log.debug("************* create relations took : create {}, add property value {}", totalCreateRel, totalCreatePropVal); - log.debug("************* in create relations, getResource start"); ComponentParametersView parametersView = new ComponentParametersView(); parametersView.disableAll(); parametersView.setIgnoreComponentInstances(false); - parametersView.setIgnoreUsers(false); - parametersView.setIgnoreArtifacts(false); - parametersView.setIgnoreGroups(false); - Either eitherGerResource = resourceOperation.getComponent(resource.getUniqueId(), parametersView, inTransaction); + parametersView.setIgnoreComponentInstancesProperties(false); + parametersView.setIgnoreCapabilities(false); + parametersView.setIgnoreRequirements(false); + + Either eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView); + + if (eitherGerResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); + + return Either.right(responseFormat); + + } + + resource = eitherGerResource.left().value(); + + for (Entry entry : uploadResInstancesMap.entrySet()) { + UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue(); + ComponentInstance currentCompInstance = null; + for (ComponentInstance compInstance : componentInstancesList) { + + if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) { + currentCompInstance = compInstance; + break; + } + + } + if (currentCompInstance == null) { + log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId()); + BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + return Either.right(responseFormat); + } + + ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations); + if (addRelationToRiRes.getStatus() != 200) { + return Either.right(addRelationToRiRes); + } + } + + addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), addArtToInst); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + return Either.right(responseFormat); + } + + log.debug("************* in create relations, getResource start"); + + eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); log.debug("************* in create relations, getResource end"); if (eitherGerResource.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); @@ -2777,117 +3570,216 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.left(eitherGerResource.left().value()); } - private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, String resourceInstanceId, ComponentInstance currentCompInstance, String yamlName, - Map> propertiesListPerResource) { + private ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue, List relations) { + List componentInstancesList = resource.getComponentInstances(); + long totalCreateRel = 0; + long totalCreatePropVal = 0; + + UploadComponentInstanceInfo uploadComponentInstanceInfo = nodesInfoValue; + + ComponentInstance currentCompInstance = null; + + for (ComponentInstance compInstance : componentInstancesList) { + + if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) { + currentCompInstance = compInstance; + break; + } + + } + + if (currentCompInstance == null) { + log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId()); + BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + return responseFormat; + } + String resourceInstanceId = currentCompInstance.getUniqueId(); + + log.debug("************* addPropertyValuesToRi start"); + long startAddProperty = System.currentTimeMillis(); + log.debug("************* addPropertyValuesToRi end"); + totalCreatePropVal += (System.currentTimeMillis() - startAddProperty); + Map> regMap = uploadComponentInstanceInfo.getRequirements(); + if (regMap == null) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName); + return responseFormat; + } + Iterator>> nodesRegValue = regMap.entrySet().iterator(); + + long startAddRelation = System.currentTimeMillis(); + + while (nodesRegValue.hasNext()) { + Entry> nodesRegInfoEntry = nodesRegValue.next(); + + List uploadRegInfoList = nodesRegInfoEntry.getValue(); + for (UploadReqInfo uploadRegInfo : uploadRegInfoList) { + log.debug("Going to create relation {}", uploadRegInfo.getName()); + String regName = uploadRegInfo.getName(); + String nodeCapName = uploadRegInfo.getNode(); + RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef(); + regCapRelDef.setFromNode(resourceInstanceId); + log.debug("try to find available requirement {} ", regName); + Either eitherReqStatus = findAviableRequiremen(regName, yamlName, uploadComponentInstanceInfo, currentCompInstance, uploadRegInfo.getCapabilityName()); + if (eitherReqStatus.isRight()) { + log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value()); + return eitherReqStatus.right().value(); + } + + RequirementDefinition validReq = eitherReqStatus.left().value(); + List reqAndRelationshipPairList = regCapRelDef.getRelationships(); + if (reqAndRelationshipPairList == null) + reqAndRelationshipPairList = new ArrayList(); + RequirementAndRelationshipPair reqAndRelationshipPair = new RequirementAndRelationshipPair(); + reqAndRelationshipPair.setRequirement(regName); + reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId()); + reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId()); + RelationshipImpl relationship = new RelationshipImpl(); + relationship.setType(validReq.getCapability()); + reqAndRelationshipPair.setRelationships(relationship); + + ComponentInstance currentCapCompInstance = null; + for (ComponentInstance compInstance : componentInstancesList) { + if (compInstance.getName().equals(uploadRegInfo.getNode())) { + currentCapCompInstance = compInstance; + break; + } + } + + if (currentCapCompInstance == null) { + log.debug("component instance with name {} in resource {} ", uploadRegInfo.getNode(), resource.getUniqueId()); + BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadRegInfo.getNode() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + return responseFormat; + } + regCapRelDef.setToNode(currentCapCompInstance.getUniqueId()); + log.debug("try to find aviable Capability req name is {} ", validReq.getName()); + CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo); + if (aviableCapForRel == null) { + log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(), currentCapCompInstance.getUniqueId()); + BeEcompErrorManager.getInstance().logInternalDataError("aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance.getUniqueId(), resource.getUniqueId(), + ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + return responseFormat; + } + reqAndRelationshipPair.setCapability(aviableCapForRel.getName()); + reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId()); + reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId()); + reqAndRelationshipPairList.add(reqAndRelationshipPair); + regCapRelDef.setRelationships(reqAndRelationshipPairList); + relations.add(regCapRelDef); + + } + + } + totalCreateRel += (System.currentTimeMillis() - startAddRelation); + + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + + private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName, + Map> instProperties, Map allDataTypes) { Map> propMap = uploadComponentInstanceInfo.getProperties(); if (propMap != null && propMap.size() > 0) { Map currPropertiesMap = new HashMap(); - List propertiesList = new ArrayList(); - Integer index = currentCompInstance.getPropertyValueCounter(); - Integer indexInput = currentCompInstance.getInputValueCounter(); - List listFromMap = propertiesListPerResource.get(currentCompInstance.getComponentUid()); - if (listFromMap != null) { - propertiesList = listFromMap; - } else { - TitanOperationStatus getPropertyRes = ((PropertyOperation) propertyOperation).findAllResourcePropertiesRecursively(currentCompInstance.getComponentUid(), propertiesList); - if (!getPropertyRes.equals(TitanOperationStatus.OK)) { - log.debug("failed to find properties of resource {} status is {}", currentCompInstance.getComponentUid(), getPropertyRes); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(getPropertyRes)), yamlName); - return responseFormat; + + int index = 0; + List listFromMap = originResource.getProperties(); + if (listFromMap == null || listFromMap.isEmpty()) { + log.debug("failed to find properties "); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND); + return responseFormat; + } + for (PropertyDefinition prop : listFromMap) { + String propName = prop.getName(); + if (!currPropertiesMap.containsKey(propName)) { + currPropertiesMap.put(propName, prop); } - propertiesListPerResource.put(currentCompInstance.getComponentUid(), propertiesList); } - if (propertiesList.size() > 0) { - for (PropertyDefinition prop : propertiesList) { - String propName = prop.getName(); - if (!currPropertiesMap.containsKey(propName)) { - currPropertiesMap.put(propName, prop); - } + List instPropList = new ArrayList<>(); + for (List propertyList : propMap.values()) { + + UploadPropInfo propertyInfo = propertyList.get(0); + String propName = propertyInfo.getName(); + if (!currPropertiesMap.containsKey(propName)) { + log.debug("failed to find property {} ", propName); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName); + return responseFormat; } - for (List propertyList : propMap.values()) { - UploadPropInfo propertyInfo = propertyList.get(0); - String propName = propertyInfo.getName(); - if (!currPropertiesMap.containsKey(propName)) { - log.debug("failed to find property {} ", propName); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName); - return responseFormat; - } - PropertyDefinition curPropertyDef = currPropertiesMap.get(propName); - ComponentInstanceProperty property = null; - ComponentInstanceInput inputValue = null; - // TODO - String value = null; - List getInputs = null; - boolean isValidate = true; - if (propertyInfo.getValue() != null) { - getInputs = propertyInfo.getGet_input(); - isValidate = getInputs == null || getInputs.isEmpty(); - if (isValidate) { - value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType()); - } else - value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName()); - } + PropertyDefinition curPropertyDef = currPropertiesMap.get(propName); + ComponentInstanceProperty property = null; + + String value = null; + List getInputs = null; + boolean isValidate = true; + if (propertyInfo.getValue() != null) { + getInputs = propertyInfo.getGet_input(); + isValidate = getInputs == null || getInputs.isEmpty(); + if (isValidate) { + value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType()); + } else + value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName()); + } + String innerType = null; + property = new ComponentInstanceProperty(curPropertyDef, value, null); - property = new ComponentInstanceProperty(curPropertyDef, value, null); + Either validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes); + if (validatevalueEiter.isRight()) { + return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value())); + } - Either result = componentInstanceOperation.addPropertyValueToResourceInstance(property, resourceInstanceId, isValidate, index, true); - if (result.isRight()) { - log.debug("Failed to add property value {} to resource instance {}", property, resourceInstanceId); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); - return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, currentCompInstance.getName()); - } - Either increaseCounterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.PROPERTY_COUNTER, true); - if (increaseCounterRes.isRight()) { - log.debug("Failed to increase resource property counter {} to resource instance {}", property, resourceInstanceId); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(increaseCounterRes.right().value()); - return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, currentCompInstance.getName()); - } - index = increaseCounterRes.left().value(); - if (getInputs != null && !getInputs.isEmpty()) { - for (GetInputValueInfo getInput : getInputs) { - List inputs = resource.getInputs(); - if (inputs == null || inputs.isEmpty()) { - log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, resourceInstanceId); - return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - } + // String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(currentCompInstance.getComponentUid(), index++); + // property.setUniqueId(uniqueId); + property.setValue(validatevalueEiter.left().value()); + + if (getInputs != null && !getInputs.isEmpty()) { + List getInputValues = new ArrayList<>(); + for (GetInputValueDataDefinition getInput : getInputs) { + List inputs = resource.getInputs(); + if (inputs == null || inputs.isEmpty()) { + log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId()); + return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + } + + Optional optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny(); + if (!optional.isPresent()) { + log.debug("Failed to find input {} ", getInput.getInputName()); + // @@TODO error message + return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + } + InputDefinition input = optional.get(); + getInput.setInputId(input.getUniqueId()); + getInputValues.add(getInput); - Optional optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny(); + GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); + if (getInputIndex != null) { + optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny(); if (!optional.isPresent()) { - log.debug("Failed to find input {} ", getInput.getInputName()); + log.debug("Failed to find input {} ", getInputIndex.getInputName()); // @@TODO error message return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); } - InputDefinition input = optional.get(); - TitanOperationStatus status = inputOperation.associatePropertyToInput(resourceInstanceId, input.getUniqueId(), result.left().value(), getInput); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to associate input {} tp property value{} ", getInput.getInputName(), result.left().value().getValueUniqueUid()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName); - return responseFormat; - } - GetInputValueInfo getInputIndex = getInput.getGetInputIndex(); - if (getInputIndex != null) { - optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny(); - if (!optional.isPresent()) { - log.debug("Failed to find input {} ", getInputIndex.getInputName()); - // @@TODO error message - return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - } - InputDefinition inputIndex = optional.get(); - status = inputOperation.associatePropertyToInput(resourceInstanceId, inputIndex.getUniqueId(), result.left().value(), getInputIndex); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to associate input {} tp property value{} ", getInput.getInputName(), result.left().value().getValueUniqueUid()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName); - return responseFormat; - } - - } + InputDefinition inputIndex = optional.get(); + getInputIndex.setInputId(inputIndex.getUniqueId()); + getInputValues.add(getInputIndex); } - } + } + property.setGetInputValues(getInputValues); + } + instPropList.add(property); + // delete overriden property + currPropertiesMap.remove(property.getName()); + } + // add rest of properties + if (!currPropertiesMap.isEmpty()) { + for (PropertyDefinition value : currPropertiesMap.values()) { + instPropList.add(new ComponentInstanceProperty(value)); } } + instProperties.put(currentCompInstance.getUniqueId(), instPropList); } return componentsUtils.getResponseFormat(ActionStatus.OK); } @@ -2904,6 +3796,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) { + CapabilityDefinition cap = null; Map> capMap = currentCapCompInstance.getCapabilities(); if (!capMap.containsKey(validReq.getCapability())) { return null; @@ -2912,18 +3805,30 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (!capByName.isPresent()) { return null; } - CapabilityDefinition cap = capByName.get(); + cap = capByName.get(); + + if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { + String leftOccurrences = cap.getLeftOccurrences(); + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + cap.setLeftOccurrences(String.valueOf(left)); + + } + + } + // TODO temporary fix - remove specific capability node validation - // String reqNode = validReq.getNode(); // if (reqNode != null && !reqNode.isEmpty() && // !cap.getCapabilitySources().contains(reqNode)) { // return null; // } - RequirementAndRelationshipPair relationPair = getReqRelPair(cap); - Either eitherStatus = componentInstanceOperation.isAvailableCapabilty(currentCapCompInstance, relationPair); - if (eitherStatus.isRight() || eitherStatus.left().value() == false) { - return null; - } + // RequirementAndRelationshipPair relationPair = getReqRelPair(cap); + // Either eitherStatus = componentInstanceOperation.isAvailableCapabilty(currentCapCompInstance, relationPair); + // if (eitherStatus.isRight() || eitherStatus.left().value() == false) { + // return null; + // } return cap; } @@ -2949,12 +3854,21 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { // continue; // } // } - - RequirementAndRelationshipPair relationPair = getReqRelPair(cap); - Either eitherStatus = componentInstanceOperation.isAvailableCapabilty(currentCapCompInstance, relationPair); - if (eitherStatus.isRight() || eitherStatus.left().value() == false) - continue; - else { + if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { + String leftOccurrences = cap.getLeftOccurrences(); + if (leftOccurrences == null) { + leftOccurrences = cap.getMaxOccurrences(); + } + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + cap.setLeftOccurrences(String.valueOf(left)); + aviableCapForRel = cap; + break; + } else { + continue; + } + } else { aviableCapForRel = cap; break; } @@ -2963,33 +3877,63 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return aviableCapForRel; } - private Either findAviableRequiremen(String regName, String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance) { + private Either findAviableRequiremen(String regName, String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, String capName) { Map> comInstRegDefMap = currentCompInstance.getRequirements(); - - Iterator>> regListValue = comInstRegDefMap.entrySet().iterator(); + List list = comInstRegDefMap.get(capName); RequirementDefinition validRegDef = null; - while (regListValue.hasNext()) { - Entry> regInfoEntry = regListValue.next(); - - List comInstRegDefList = regInfoEntry.getValue(); + if (list == null) { + for (Entry> entry : comInstRegDefMap.entrySet()) { + for (RequirementDefinition reqDef : entry.getValue()) { + if (reqDef.getName().equals(regName)) { + if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + String leftOccurrences = reqDef.getLeftOccurrences(); + if (leftOccurrences == null) { + leftOccurrences = reqDef.getMaxOccurrences(); + } + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + reqDef.setLeftOccurrences(String.valueOf(left)); + validRegDef = reqDef; + break; + } else { + continue; + } + } else { + validRegDef = reqDef; + break; + } - for (RequirementDefinition comInstRegDef : comInstRegDefList) { - if (!regName.equals(comInstRegDef.getName())) - continue; - RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair(); - relationPair.setRequirementUid(comInstRegDef.getUniqueId()); - relationPair.setCapability(comInstRegDef.getCapability()); - relationPair.setRequirementOwnerId(comInstRegDef.getOwnerId()); - Either eitherStatus = componentInstanceOperation.isAvailableRequirement(currentCompInstance, relationPair); - if (eitherStatus.isLeft() && eitherStatus.left().value() == true) { - validRegDef = comInstRegDef; + } + } + if (validRegDef != null) { break; } } - if (validRegDef != null) - break; + } else { + for (RequirementDefinition reqDef : list) { + if (reqDef.getName().equals(regName)) { + if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + String leftOccurrences = reqDef.getLeftOccurrences(); + if (leftOccurrences == null) { + leftOccurrences = reqDef.getMaxOccurrences(); + } + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + reqDef.setLeftOccurrences(String.valueOf(left)); + validRegDef = reqDef; + break; + } else { + continue; + } + } else { + validRegDef = reqDef; + break; + } + } + } } - if (validRegDef == null) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); return Either.right(responseFormat); @@ -2997,6 +3941,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.left(validRegDef); } + @SuppressWarnings("unchecked") public Either parseResourceInfoFromYaml(String yamlFileName, Resource resource, String resourceYml, User user) { Map mappedToscaTemplate = (Map) new Yaml().load(resourceYml); @@ -3034,6 +3979,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { private Either createResourceInstances(User user, String yamlName, Resource resource, Map uploadResInstancesMap, boolean inTransaction, boolean needLock, Map nodeTypeNamespaceMap) { + + Either eitherResource = null; log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName); if (uploadResInstancesMap == null || uploadResInstancesMap.isEmpty()) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE); @@ -3041,25 +3988,26 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.right(responseFormat); } - Map existingnodeTypeMap = new HashMap(); + Map existingnodeTypeMap = new HashMap<>(); if (nodeTypeNamespaceMap != null && !nodeTypeNamespaceMap.isEmpty()) { nodeTypeNamespaceMap.entrySet().stream().forEach(x -> existingnodeTypeMap.put(x.getValue().getToscaResourceName(), x.getValue())); } Iterator> nodesInfoValue = uploadResInstancesMap.entrySet().iterator(); + Map resourcesInstancesMap = new HashMap<>(); while (nodesInfoValue.hasNext()) { - log.debug("*************Going to create resource instances {}", yamlName); + log.debug("*************Going to create resource instances {}", yamlName); Entry uploadComponentInstanceInfoEntry = nodesInfoValue.next(); UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue(); // updating type if the type is node type name - we need to take the // updated name - log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName()); + log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName()); if (nodeTypeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { uploadComponentInstanceInfo.setType(nodeTypeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName()); } - Either eitherResource = validateResourceInstanceBeforeCreate(yamlName, inTransaction, uploadComponentInstanceInfo, existingnodeTypeMap); + eitherResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap); if (eitherResource.isRight()) { return eitherResource; } @@ -3067,7 +4015,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { ComponentInstance componentInstance = new ComponentInstance(); - componentInstance.setName(uploadComponentInstanceInfo.getName()); componentInstance.setComponentUid(refResource.getUniqueId()); ComponentTypeEnum containerComponentType = resource.getComponentType(); @@ -3087,26 +4034,24 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.right(responseFormat); } Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType()); - ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(); - Either eitherCreateCI = componentInstanceBL.createComponentInstanceOnGraph(ComponentTypeEnum.RESOURCE_PARAM_NAME, resource, origResource, componentInstance, user.getUserId(), needLock, inTransaction); - if (eitherCreateCI.isRight()) { - log.debug("createResourceInstances - failed to create resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - return Either.right(eitherCreateCI.right().value()); - } + componentInstance.setName(uploadComponentInstanceInfo.getName()); + componentInstance.setIcon(origResource.getIcon()); - ComponentInstance createdCI = eitherCreateCI.left().value(); - createdCI.setName(uploadComponentInstanceInfo.getName()); - /* - * updateComponentInstance(String containerComponentParam, org.openecomp.sdc.be.model.Component containerComponent, String componentInstanceId, ComponentInstance componentInstance, boolean inTransaction, boolean needLock) - */ - eitherCreateCI = componentInstanceBL.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, resource, origResource, createdCI.getUniqueId(), createdCI, needLock, inTransaction); - if (eitherCreateCI.isRight()) { - log.debug("createResourceInstances - failed to update resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - return Either.right(eitherCreateCI.right().value()); + resourcesInstancesMap.put(componentInstance, origResource); + + } + if (MapUtils.isNotEmpty(resourcesInstancesMap)) { + + StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false); + if (status != null && status != StorageOperationStatus.OK) { + log.debug("Failed to add component instances to container component {}", resource.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)); + eitherResource = Either.right(responseFormat); + return eitherResource; } - log.debug("*************finished to create and update resource instances {}", uploadComponentInstanceInfo.getName()); } + log.debug("*************Going to get resource {}", resource.getUniqueId()); ComponentParametersView parametersView = new ComponentParametersView(); parametersView.disableAll(); @@ -3114,7 +4059,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { parametersView.setIgnoreUsers(false); parametersView.setIgnoreInputs(false); // inputs are read when creating // property values on instances - Either eitherGerResource = resourceOperation.getComponent(resource.getUniqueId(), parametersView, inTransaction); + Either eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView); log.debug("*************finished to get resource {}", resource.getUniqueId()); if (eitherGerResource.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); @@ -3135,20 +4080,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.left(eitherGerResource.left().value()); } - private Either validateResourceInstanceBeforeCreate(String yamlName, boolean inTransaction, UploadComponentInstanceInfo uploadComponentInstanceInfo, Map nodeTypeNamespaceMap) { + private Either validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, Map nodeTypeNamespaceMap) { log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); Resource refResource = null; if (nodeTypeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { refResource = nodeTypeNamespaceMap.get(uploadComponentInstanceInfo.getType()); } else { - - Either eithervalidateResource = resourceOperation.validateToscaResourceNameExists(uploadComponentInstanceInfo.getType()); - if ((eithervalidateResource.isRight() && eithervalidateResource.right().value() == StorageOperationStatus.NOT_FOUND) || eithervalidateResource.left().value() == true) { - log.debug("validateResourceInstanceBeforeCreate - resource instance with name {} and type not valid", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - return Either.right(responseFormat); - } - Either findResourceEither = resourceOperation.getLatestCertifiedByToscaResourceName(uploadComponentInstanceInfo.getType(), inTransaction); + Either findResourceEither = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType()); if (findResourceEither.isRight()) { log.debug("validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value())); @@ -3291,6 +4229,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { UploadPropInfo propertyDef = new UploadPropInfo(); propertyDef.setValue(propValue); + propertyDef.setName(propName); if (propValue instanceof Map) { if (((Map) propValue).containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { propertyDef.setType(((Map) propValue).get(ToscaTagNamesEnum.TYPE.getElementName()).toString()); @@ -3319,7 +4258,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { propertyDef.setValue(propValue); } - propertyDef.setName(propName); if (moduleProp.containsKey(propName)) { moduleProp.get(propName).add(propertyDef); } else { @@ -3337,18 +4275,22 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (objValue instanceof Map) { Map objMap = (Map) objValue; - Set keys = objMap.keySet(); - for (String key : keys) { - Object value = objMap.get(key); - if (value instanceof Map) { - createGetInputModuleFromMap(key, (Map) value, propertyDef); + if (objMap.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) + createGetInputModuleFromMap(propertyDef.getName(), objMap, propertyDef); + else { + Set keys = objMap.keySet(); + for (String key : keys) { + Object value = objMap.get(key); + if (value instanceof Map) { + createGetInputModuleFromMap(key, (Map) value, propertyDef); - } else if (value instanceof List) { - List propSubValueList = (List) value; + } else if (value instanceof List) { + List propSubValueList = (List) value; - createInputPropList(propertyDef, propSubValueList); - } + createInputPropList(propertyDef, propSubValueList); + } + } } } else if (objValue instanceof List) { @@ -3365,10 +4307,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (propValue.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) { Object getInput = propValue.get(ToscaTagNamesEnum.GET_INPUT.getElementName()); - GetInputValueInfo getInputInfo = new GetInputValueInfo(); - List getInputs = propertyDef.getGet_input(); + GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition(); + List getInputs = propertyDef.getGet_input(); if (getInputs == null) { - getInputs = new ArrayList(); + getInputs = new ArrayList(); } if (getInput instanceof String) { @@ -3388,7 +4330,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { getInputInfo.setIndexValue(index); } else if (indexObj instanceof Map && ((Map) indexObj).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) { Object index = ((Map) indexObj).get(ToscaTagNamesEnum.GET_INPUT.getElementName()); - GetInputValueInfo getInputInfoIndex = new GetInputValueInfo(); + GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition(); getInputInfoIndex.setInputName((String) index); getInputInfoIndex.setPropName(propName); getInputInfo.setGetInputIndex(getInputInfoIndex); @@ -3607,32 +4549,35 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify"); if (inTransaction == false) { log.debug("operation failed. do rollback"); - titanGenericDao.rollback(); + titanDao.rollback(); } } else if (inTransaction == false) { log.debug("operation success. do commit"); - titanGenericDao.commit(); + titanDao.commit(); } } } - /** + /* + * /** + * * @deprecated Use {@link #createOrUpdateResourceByImport(Resource,User,boolean, boolean,boolean)} instead */ - public Either, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { - return createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); - } + /* + * public Either, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { return + * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); } + */ public Either, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock) { // check if resource already exist - Either latestByName = resourceOperation.getLatestByName(resource.getName(), true); + Either latestByName = toscaOperationFacade.getLatestByName(resource.getName()); Either, ResponseFormat> result = null; // create if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - Either latestByToscaName = resourceOperation.getLatestByToscaResourceName(resource.getToscaResourceName(), true); + Either latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName()); if (latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)) result = createResourceByImport(resource, user, isNormative, isInTransaction); @@ -3672,7 +4617,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (response.isRight()) { return Either.right(response.right().value()); } - Either createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction); + Either createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null); if (createResponse.isRight()) { return Either.right(createResponse.right().value()); } else { @@ -3684,7 +4629,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } public boolean isResourceExist(String resourceName) { - Either latestByName = resourceOperation.getLatestByName(resourceName, false); + Either latestByName = toscaOperationFacade.getLatestByName(resourceName); return latestByName.isLeft(); } @@ -3750,7 +4695,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) { setToscaArtifactsPlaceHolders(newResource, user); } - Either overrideResource = resourceOperation.overrideResource(newResource, oldResource, true); + Either overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource); if (overrideResource.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource); @@ -3771,10 +4716,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Change LifecycleState - Certify"); BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify"); log.debug("operation failed. do rollback"); - titanGenericDao.rollback(); + titanDao.rollback(); } else if (inTransaction == false) { log.debug("operation success. do commit"); - titanGenericDao.commit(); + titanDao.commit(); } if (needLock == true) { log.debug("unlock resource {}", lockedResourceId); @@ -3829,7 +4774,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { public Either validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction) { - Either eitherValidation = validateResourceFieldsBeforeCreate(user, getResourceOperation(), resource, actionEnum, inTransaction); + Either eitherValidation = validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction); if (eitherValidation.isRight()) { return Either.right(eitherValidation.right().value()); } @@ -3908,9 +4853,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) { log.debug("validate capability Types Exist - capabilities section"); - for (String type : resource.getCapabilities().keySet()) { + for (Entry> typeEntry : resource.getCapabilities().entrySet()) { - eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, type, inTransaction); + eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry, inTransaction); if (eitherResult.isRight()) { return Either.right(eitherResult.right().value()); } @@ -3951,11 +4896,54 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return eitherResult; } - public Either createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative) { - return createResourceByDao(resource, user, actionEnum, isNormative, false); + private Either validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, Either eitherResult, + Entry> typeEntry, boolean inTransaction) { + Either eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(typeEntry.getKey(), inTransaction); + if (eitherCapTypeFound.isRight()) { + if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeCapabilityTypeMissingError, "Create Resource - validateCapabilityTypesCreate", typeEntry.getKey()); + BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey()); + log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName()); + BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate"); + } + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateCapabilityTypesCreate"); + log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey()); + eitherResult = Either.right(errorResponse); + componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); + } + CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value(); + if (capabilityTypeDefinition.getProperties() != null) { + for (CapabilityDefinition capDef : typeEntry.getValue()) { + List properties = capDef.getProperties(); + if (properties == null || properties.isEmpty()) { + properties = new ArrayList(); + for (Entry prop : capabilityTypeDefinition.getProperties().entrySet()) { + ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue()); + properties.add(newProp); + } + } else { + for (Entry prop : capabilityTypeDefinition.getProperties().entrySet()) { + PropertyDefinition porpFromDef = prop.getValue(); + List propsToAdd = new ArrayList<>(); + for (ComponentInstanceProperty cip : properties) { + if (!cip.getName().equals(porpFromDef.getName())) { + ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef); + propsToAdd.add(newProp); + } + } + if (!propsToAdd.isEmpty()) { + properties.addAll(propsToAdd); + } + } + } + capDef.setProperties(properties); + } + } + return eitherResult; } - public Either createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) { + public Either createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction, EnumMap additionalParams) { // create resource // lock new resource name in order to avoid creation resource with same @@ -3964,37 +4952,50 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Either lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource"); if (lockResult.isRight()) { ResponseFormat responseFormat = lockResult.right().value(); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); + componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams); return Either.right(responseFormat); } - log.debug("name is locked {}. status = {}", resource.getSystemName(), lockResult); + log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult); } try { - Either respStatus = createResourceTransaction(resource, user, actionEnum, isNormative, inTransaction); + if (resource.deriveFromGeneric()) { + Either genericResourceEither = fetchAndSetDerivedFromGenericType(resource); + if (genericResourceEither.isRight()) + return genericResourceEither; + if (resource.shouldGenerateInputs()) + generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value()); + } + + Either respStatus = createResourceTransaction(resource, user, isNormative, inTransaction); if (respStatus.isLeft()) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); + componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams); ASDCKpiApi.countCreatedResourcesKPI(); } else - componentsUtils.auditResource(respStatus.right().value(), user, resource, "", "", actionEnum, null); + componentsUtils.auditResource(respStatus.right().value(), user, resource, "", "", actionEnum, additionalParams); return respStatus; } finally { if (inTransaction == false) { - // graphLockOperation.unlockComponent(resource.getSystemName(), - // NodeTypeEnum.Resource); graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource); } } } - private Either createResourceTransaction(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) { + private Either createResourceTransaction(Resource resource, User user, boolean isNormative, boolean inTransaction) { // validate resource name uniqueness log.debug("validate resource name"); - Either eitherValidation = validateResourceNameExists(user, resource, actionEnum); + Either eitherValidation = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType()); if (eitherValidation.isRight()) { - return Either.right(eitherValidation.right().value()); + log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), eitherValidation.right().value()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value())); + return Either.right(errorResponse); + } + if (eitherValidation.left().value()) { + log.debug("resource with name: {}, already exists", resource.getName()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); + return Either.right(errorResponse); } log.debug("send resource {} to dao for create", resource.getName()); @@ -4002,8 +5003,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { createArtifactsPlaceHolderData(resource, user); // + + // enrich object if (!isNormative) { - // enrich object log.debug("enrich resource with creator, version and state"); resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); resource.setVersion(INITIAL_VERSION); @@ -4011,16 +5013,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { resource.setAbstract(false); } - Either dataModelResponse = resourceOperation.createResource(resource, inTransaction); - - // Resource created successfully!!! - if (dataModelResponse.isLeft()) { - log.debug("Resource created successfully!!!"); - - return Either.left(dataModelResponse.left().value()); + Either createToscaElement = toscaOperationFacade.createToscaComponent(resource); + if (createToscaElement.isLeft()) { + return Either.left(createToscaElement.left().value()); } - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), resource); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(createToscaElement.right().value()), resource); return Either.right(responseFormat); } @@ -4123,7 +5121,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return eitherCreator.right().value(); } - Either resourceStatus = resourceOperation.getResource(resourceId); + Either resourceStatus = toscaOperationFacade.getToscaElement(resourceId); if (resourceStatus.isRight()) { log.debug("failed to get resource {}", resourceId); return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), ""); @@ -4152,10 +5150,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } finally { if (result == null || !result.equals(StorageOperationStatus.OK)) { log.warn("operation failed. do rollback"); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("operation success. do commit"); - titanGenericDao.commit(); + titanDao.commit(); } graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); } @@ -4170,30 +5168,30 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } // Resource resource = null; - List resourcesList = null; + Resource resource = null; StorageOperationStatus result = StorageOperationStatus.OK; try { - Either, StorageOperationStatus> resourceStatus = resourceOperation.getResourceByNameAndVersion(resourceName, version, true); + Either resourceStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version); if (resourceStatus.isRight()) { log.debug("failed to get resource {} version {}", resourceName, version); return componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName); } - resourcesList = resourceStatus.left().value(); + resource = resourceStatus.left().value(); } finally { if (result == null || !result.equals(StorageOperationStatus.OK)) { log.warn("operation failed. do rollback"); - titanGenericDao.rollback(); + titanDao.rollback(); ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName); } else { log.debug("operation success. do commit"); - titanGenericDao.commit(); + titanDao.commit(); } } - for (Resource resource : resourcesList) { + if (resource != null) { Either lockResult = lockComponent(resource.getUniqueId(), resource, "Delete Resource"); if (lockResult.isRight()) { result = StorageOperationStatus.GENERAL_ERROR; @@ -4210,10 +5208,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } finally { if (result == null || !result.equals(StorageOperationStatus.OK)) { log.warn("operation failed. do rollback"); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("operation success. do commit"); - titanGenericDao.commit(); + titanDao.commit(); } graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource); } @@ -4230,8 +5228,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } - IResourceOperation dataModel = getResourceOperation(); - Either storageStatus = dataModel.getResource(resourceId); + // IResourceOperation dataModel = getResourceOperation(); + Either storageStatus = toscaOperationFacade.getToscaElement(resourceId); if (storageStatus.isRight()) { log.debug("failed to get resource by id {}", resourceId); @@ -4241,14 +5239,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } - public Either, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, String userId) { + public Either getResourceByNameAndVersion(String resourceName, String resourceVersion, String userId) { Either resp = validateUserExists(userId, "get Resource By Name And Version", false); if (resp.isRight()) { return Either.right(resp.right().value()); } - Either, StorageOperationStatus> getResource = resourceOperation.getResourceByNameAndVersion(resourceName, resourceVersion, false); + Either getResource = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion); if (getResource.isRight()) { log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion); return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName)); @@ -4276,7 +5274,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.right(resp.right().value()); } - IResourceOperation dataModel = getResourceOperation(); + // IResourceOperation dataModel = getResourceOperation(); log.debug("Get resource with id {}", resourceIdToUpdate); boolean needToUnlock = false; boolean rollbackNeeded = true; @@ -4285,7 +5283,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { // Either storageStatus = // dataModel.getResource_tx(resourceIdToUpdate, false); if (currentResource == null) { - Either storageStatus = dataModel.getResource(resourceIdToUpdate, false); + Either storageStatus = toscaOperationFacade.getToscaElement(resourceIdToUpdate); if (storageStatus.isRight()) { return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), "")); } @@ -4303,7 +5301,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (!lockResult.equals(StorageOperationStatus.OK)) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, "Upload Artifact - lock " + resourceIdToUpdate + ": " + NodeTypeEnum.Resource); BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), resourceIdToUpdate); - log.debug("Failed to lock resource {} error - {}", resourceIdToUpdate, lockResult); + log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult); ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult)); return Either.right(responseFormat); } @@ -4347,9 +5345,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } finally { if (!inTransaction) { if (rollbackNeeded) { - titanGenericDao.rollback(); + titanDao.rollback(); } else { - titanGenericDao.commit(); + titanDao.commit(); } } @@ -4361,7 +5359,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { private Either updateResourceMetadata(String resourceIdToUpdate, Resource newResource, User user, Resource currentResource, boolean shouldLock, boolean inTransaction) { - IResourceOperation dataModel = getResourceOperation(); Either validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction); if (validateResourceFields.isRight()) { return Either.right(validateResourceFields.right().value()); @@ -4371,7 +5368,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { newResource.setLastUpdaterUserId(user.getUserId()); newResource.setUniqueId(resourceIdToUpdate); // Cannot set highest version through UI - newResource.setHighestVersion(null); + newResource.setHighestVersion(currentResource.isHighestVersion()); newResource.setCreationDate(currentResource.getCreationDate()); Either processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, newResource, user.getUserId(), shouldLock, inTransaction); @@ -4382,7 +5379,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } log.debug("send resource {} to dao for update", newResource.getUniqueId()); - Either dataModelResponse = dataModel.updateResource(newResource, inTransaction); + Either dataModelResponse = toscaOperationFacade.updateToscaElement(newResource); if (dataModelResponse.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource); @@ -4405,7 +5402,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { * - Resource object to validate * @return Either */ - private Either validateResourceFieldsBeforeCreate(User user, IResourceOperation dataModel, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { + private Either validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { Either componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, resource, actionEnum); if (componentsFieldsValidation.isRight()) { return componentsFieldsValidation; @@ -4449,6 +5446,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return eitherValidation; } + // validate contact info + /* + * log.debug("validate contact info"); eitherValidation = validateContactIdContactId(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; } + */ + // validate cost log.debug("validate cost"); eitherValidation = validateCost(user, resource, actionEnum); @@ -4577,7 +5579,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { String updatedCreatorUserId = updateInfoResource.getCreatorUserId(); if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) { - log.warn("Resource Creator User id is automatically set and cannot be updated"); + log.warn("Resource Creator UserId is automatically set and cannot be updated"); } String currentCreatorFullName = currentResource.getCreatorFullName(); @@ -4689,7 +5691,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { ResponseFormat errorResponse = validateResourceNameResponse.right().value(); return Either.right(errorResponse); } - validateResourceNameResponse = validateResourceNameExists(null, updateInfoResource, null); + validateResourceNameResponse = validateResourceNameExists(updateInfoResource); if (validateResourceNameResponse.isRight()) { ResponseFormat errorResponse = validateResourceNameResponse.right().value(); return Either.right(errorResponse); @@ -4699,7 +5701,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated)); } else { - log.info("Resource name {} cannot be updated once the resource has been certified once.", resourceNameUpdated); + log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); return Either.right(errorResponse); } @@ -4784,9 +5786,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return validateDerivedFromExistsEither; } } else { - log.debug("Derived from cannot be updated once the resource has been certified once."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_DERIVED_FROM_CANNOT_BE_CHANGED); - return Either.right(errorResponse); + Either validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource, null); + + if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) { + log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance"); + return validateDerivedFromExtending; + } } } else { // For derived from, we must know whether it was actually changed, @@ -4806,11 +5811,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.left(true); } - IResourceOperation resourceOperation = getResourceOperation(); + // IResourceOperation resourceOperation = getResourceOperation(); String templateName = resource.getDerivedFrom().get(0); - Either dataModelResponse = resourceOperation.validateToscaResourceNameExists(templateName); + Either dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName); if (dataModelResponse.isRight()) { StorageOperationStatus storageStatus = dataModelResponse.right().value(); BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateDerivedFromExist"); @@ -4822,8 +5827,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.right(responseFormat); } - if (dataModelResponse.left().value()) { - log.info("resource template with name {} does not exists", templateName); + else if (!dataModelResponse.left().value()) { + log.info("resource template with name: {}, does not exists", templateName); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); @@ -4833,6 +5838,41 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.left(true); } + // Tal G for extending inheritance US815447 + private Either validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource, AuditingActionEnum actionEnum) { + // If updated resource is not deriving, should fail validation + /* + * if (currentResource.getDerivedFrom() == null || currentResource.getDerivedFrom().isEmpty()) { return Either.left(false); } + */ + // If current resource is deriving from certain type and it is updated to not deriving, should fail validation + /* + * if (updateInfoResource.getDerivedFrom() == null || updateInfoResource.getDerivedFrom().isEmpty()) { return Either.left(false); } + */ + String currentTemplateName = currentResource.getDerivedFrom().get(0); + String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0); + + Either dataModelResponse = toscaOperationFacade.validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName); + if (dataModelResponse.isRight()) { + StorageOperationStatus storageStatus = dataModelResponse.right().value(); + BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType"); + log.debug("request to data model failed with error: {}", storageStatus.name()); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource); + log.trace("audit before sending response"); + componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null); + return Either.right(responseFormat); + } + + if (!dataModelResponse.left().value()) { + log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND); + componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null); + + return Either.right(responseFormat); + + } + return Either.left(true); + } + public Either validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) { log.debug("validate resource derivedFrom field"); if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) { @@ -4845,23 +5885,20 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.left(true); } - private Either validateResourceNameExists(User user, Resource resource, AuditingActionEnum actionEnum) { + private Either validateResourceNameExists(Resource resource) { - IResourceOperation resourceOperation = getResourceOperation(); - Either resourceOperationResponse = resourceOperation.validateResourceNameExists(resource.getName(), resource.getResourceType()); + Either resourceOperationResponse = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType()); if (resourceOperationResponse.isLeft()) { - if (resourceOperationResponse.left().value()) { - return Either.left(true); + if (!resourceOperationResponse.left().value()) { + return Either.left(false); } else { - log.debug("resource with name {} already exists", resource.getName()); + log.debug("resource with name: {}, already exists", resource.getName()); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); - componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); } } log.debug("error while validateResourceNameExists for resource: {}", resource.getName()); ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceOperationResponse.right().value())); - componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); } @@ -5037,7 +6074,57 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.left(false); } - + + /* + * private Either validateDescriptionAndCleanup(User user, Resource resource, AuditingActionEnum actionEnum) { String description = resource.getDescription(); if (!ValidationUtils.validateStringNotEmpty(description)) { + * log.debug("Resource description is empty"); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(errorResponse, + * user, resource, "", "", actionEnum, null); return Either.right(errorResponse); } + * + * description = ValidationUtils.removeNoneUtf8Chars(description); description = ValidationUtils.removeHtmlTags(description); description = ValidationUtils.normaliseWhitespace(description); description = ValidationUtils.stripOctets(description); + * + * Either validatDescription = validateResourceDescription(description); if (validatDescription.isRight()) { ResponseFormat responseFormat = validatDescription.right().value(); + * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setDescription(description); return Either.left(true); } + * + * private Either validateResourceDescription(String description) { if (description != null) { if (!ValidationUtils.validateDescriptionLength(description)) { return + * Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)); } + * + * if (!ValidationUtils.validateIsEnglish(description)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue())); } return Either.left(true); } return + * Either.left(false); } + */ + + /* + * private Either validateContactId(User user, Resource resource, AuditingActionEnum actionEnum) { String contactId = resource.getContactId(); + * + * if (!ValidationUtils.validateStringNotEmpty(contactId)) { log.info("contact info is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); } + * + * Either validateContactIdResponse = validateContactId(contactId); if (validateContactIdResponse.isRight()) { ResponseFormat responseFormat = validateContactIdResponse.right().value(); + * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); } return validateContactIdResponse; } + * + * private Either validateContactId(String contactId) { if (contactId != null) { if (!ValidationUtils.validateContactId(contactId)) { log.debug("contact {} is invalid.", contactId); ResponseFormat errorResponse = + * componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false); + * + * } + */ + + /* + * private Either validateIcon(User user, Resource resource, AuditingActionEnum actionEnum) { String icon = resource.getIcon(); + * + * if (!ValidationUtils.validateStringNotEmpty(icon)) { log.debug("icon is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue()); + * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); } + * + * Either validateIcon = validateIcon(icon); if (validateIcon.isRight()) { ResponseFormat responseFormat = validateIcon.right().value(); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, + * null); } return validateIcon; + * + * } + * + * public Either validateIcon(String icon) { if (icon != null) { if (!ValidationUtils.validateIconLength(icon)) { log.debug("icon exceeds max length"); return Either.right(componentsUtils.getResponseFormat(ActionStatus. + * COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH)); } if (!ValidationUtils.validateIcon(icon)) { log.debug("icon is invalid." ); ResponseFormat errorResponse = + * componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false); + * + * } + */ + private Either validateCost(User user, Resource resource, AuditingActionEnum actionEnum) { String cost = resource.getCost(); if (cost != null) { @@ -5084,11 +6171,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition); log.trace("Starting interface artifacts removal for interface type {}", interfaceType); - Map operations = interfaceDefinition.getOperations(); + Map operations = interfaceDefinition.getOperationsMap(); if (operations != null) { for (Entry operationEntry : operations.entrySet()) { Operation operation = operationEntry.getValue(); - ArtifactDefinition implementation = operation.getImplementation(); + ArtifactDefinition implementation = operation.getImplementationArtifact(); if (implementation != null) { String uniqueId = implementation.getUniqueId(); log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", uniqueId, operationEntry.getKey(), interfaceType); @@ -5097,7 +6184,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (deleteArtifactByInterface.isRight()) { log.debug("Couldn't remove artifact definition with id {}", uniqueId); if (!inTransaction) { - titanGenericDao.rollback(); + titanDao.rollback(); } return Either.right(deleteArtifactByInterface.right().value()); } @@ -5116,7 +6203,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (findPropertiesOfNode.isRight() && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) { log.debug("Failed to remove all properties of resource"); if (!inTransaction) - titanGenericDao.rollback(); + titanDao.rollback(); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value()))); } @@ -5125,7 +6212,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } if (!inTransaction) - titanGenericDao.commit(); + titanDao.commit(); return Either.left(true); } @@ -5309,7 +6396,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (regResponse.isRight()) return Either.right(regResponse.right().value()); if (regResponse.left().value().size() > 0) { - groupInfo.setProperties(regResponse.left().value()); + groupInfo.convertFromGroupProperties(regResponse.left().value()); } } @@ -5378,7 +6465,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { groupProperty.setValue(convertedValue); groupProperty.setName(propName); - log.debug("After building group property {}", groupProperty); + log.trace("After building group property {}", groupProperty); result.add(groupProperty); } @@ -5401,7 +6488,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } // get resource from csar uuid - Either either = resourceOperation.getLatestResourceByCsarOrName(csarUuid, ""); + Either either = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, ""); if (either.isRight()) { ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUuid); return Either.right(resp); @@ -5464,6 +6551,94 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.left(true); } + private Either>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(List artifactPathAndNameList, List existingArtifactsToHandle, + Resource resource, User user) { + + EnumMap> nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); + Wrapper responseWrapper = new Wrapper<>(); + Either>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle); + ; + try { + // add all found Csar artifacts to list to upload + List artifactsToUpload = new ArrayList<>(artifactPathAndNameList); + List artifactsToUpdate = new ArrayList<>(); + List artifactsToDelete = new ArrayList<>(); + for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) { + ArtifactDefinition foundArtifact; + + if (!existingArtifactsToHandle.isEmpty()) { + foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null); + if (foundArtifact != null) { + if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact.getArtifactType()) { + if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) { + currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId()); + // if current artifact already exists, but has different content, add him to the list to update + artifactsToUpdate.add(currNewArtifact); + } + // remove found artifact from the list of existing artifacts to handle, because it was already handled + existingArtifactsToHandle.remove(foundArtifact); + // and remove found artifact from the list to upload, because it should either be updated or be ignored + artifactsToUpload.remove(currNewArtifact); + } else { + log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName()); + ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(), + currNewArtifact.getArtifactType().name(), foundArtifact.getArtifactType()); + AuditingActionEnum auditingAction = artifactsBusinessLogic.detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), foundArtifact.getArtifactChecksum()); + artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(), user, null, null, foundArtifact.getUniqueId(), responseFormat, resource.getComponentType(), null); + responseWrapper.setInnerElement(responseFormat); + break; + } + } + } + } + if (responseWrapper.isEmpty()) { + existingArtifactsToHandle.stream() + // add all artifacts which was not detected as artifact to update or to ignore to the list to delete + .forEach(a -> artifactsToDelete.add(new NonMetaArtifactInfo(a.getArtifactName(), null, ArtifactTypeEnum.findType(a.getArtifactType()), a.getArtifactGroupType(), null, a.getUniqueId()))); + } + if (responseWrapper.isEmpty()) { + if (!artifactsToUpload.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload); + if (!artifactsToUpdate.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate); + if (!artifactsToDelete.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete); + } + if (!responseWrapper.isEmpty()) { + nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement()); + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + responseWrapper.setInnerElement(responseFormat); + log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); + } + return nodeTypeArtifactsToHandleRes; + } + + private String buildNestedVfcToscaNamespace(String nodeTypeFullName) { + + String actualName = this.getNodeTypeActualName(nodeTypeFullName); + return ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + actualName; + + } + + private String buildNestedVfcToscaResourceName(String vfResourceName, String nodeTypeFullName) { + String toscaResourceName; + String nameWithouNamespacePrefix = getNodeTypeActualName(nodeTypeFullName); + if (nameWithouNamespacePrefix.startsWith(Constants.ABSTRACT)) { + toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + '.' + vfResourceName + '.' + nameWithouNamespacePrefix; + } else { + toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + '.' + vfResourceName + '.' + Constants.ABSTRACT + nameWithouNamespacePrefix; + } + return toscaResourceName; + } + + private String buildNestedSubstituteYamlName(String nodeTypeFullName) { + String[] nodeTypeFullNameParsed = nodeTypeFullName.split("\\."); + String nodeTypeActualName = nodeTypeFullNameParsed[nodeTypeFullNameParsed.length - 1]; + return CsarUtils.DEFINITIONS_PATH + nodeTypeActualName + Constants.SERVICE_TEMPLATE_FILE_POSTFIX; + } + public ICacheMangerOperation getCacheManagerOperation() { return cacheManagerOperation; } @@ -5472,4 +6647,92 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { this.cacheManagerOperation = cacheManagerOperation; } + ///////////////////////////////////////// DataModel refactoring///////////////////////////////////////////// + + /* + * /** + * + * @deprecated Use {@link #createOrUpdateResourceByImport(Resource,User,boolean, boolean,boolean)} instead + */ + /* + * public Either, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { return + * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); } + */ + + public Either, ResponseFormat> createOrUpdateNodeTypeByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock) { + + // check if resource already exist + Either latestByName = toscaOperationFacade.getLatestByName(resource.getName()); + Either, ResponseFormat> result = null; + + // create + if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + + Either latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName()); + if (latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)) + result = createNodeTypeByImport(resource, user, isNormative, isInTransaction); + + else { + StorageOperationStatus status = latestByName.right().value(); + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName()); + BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); + log.debug("resource already exist {}. status={}", resource.getName(), status); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS); + componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); + result = Either.right(responseFormat); + } + + } + + // update + else if (latestByName.isLeft()) { + // result = updateExistingNodeTypeByImport(resource, latestByName.left().value(), user, isNormative, needLock); + } + + // error + else { + StorageOperationStatus status = latestByName.right().value(); + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName()); + log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource); + componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); + result = Either.right(responseFormat); + } + return result; + + } + + private Either, ResponseFormat> createNodeTypeByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction) { + log.debug("resource with name {} does not exist. create new resource", resource.getName()); + Either response = validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction); + if (response.isRight()) { + return Either.right(response.right().value()); + } + + Either createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null); + if (createResponse.isRight()) { + return Either.right(createResponse.right().value()); + } else { + ImmutablePair resourcePair = new ImmutablePair<>(createResponse.left().value(), ActionStatus.CREATED); + ASDCKpiApi.countImportResourcesKPI(); + return Either.left(resourcePair); + + } + } + + public Either getUiComponentDataTransferByComponentId(String resourceId, List dataParamsToReturn) { + + ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn); + Either resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen); + + if (resourceResultEither.isRight()) { + log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn.toString()); + return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), "")); + } + + Resource resource = resourceResultEither.left().value(); + UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resource, dataParamsToReturn); + return Either.left(dataTransfer); + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java index 329481a546..f35515f8fe 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java @@ -37,6 +37,7 @@ import javax.servlet.ServletContext; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.Constants; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; @@ -49,6 +50,7 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.ComponentInstanceProperty; @@ -61,6 +63,7 @@ import org.openecomp.sdc.be.model.UploadResourceInfo; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; @@ -101,29 +104,45 @@ public class ResourceImportManager { @Autowired protected CapabilityTypeOperation capabilityTypeOperation; + @Autowired + protected ToscaOperationFacade toscaOperationFacade; private ResponseFormatManager responseFormatManager; private static Logger log = LoggerFactory.getLogger(ResourceImportManager.class.getName()); + public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { + this.toscaOperationFacade = toscaOperationFacade; + } + public Either, ResponseFormat> importNormativeResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) { LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(); lifecycleChangeInfo.setUserRemarks("certification on import"); Function> validator = (resource) -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); - return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock); + return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null); + } + + public Either, ResponseFormat> importNormativeResourceFromCsar(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) { + + LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(); + lifecycleChangeInfo.setUserRemarks("certification on import"); + Function> validator = (resource) -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); + + return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null); } public Either, ResponseFormat> importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, Function> validationFunction, - LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock) { + LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map> nodeTypeArtifactsToHandle, List nodeTypesNewCreatedArtifacts) { Resource resource = new Resource(); - ImmutablePair responsePair = new ImmutablePair(resource, ActionStatus.CREATED); + ImmutablePair responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED); Either, ResponseFormat> response = Either.left(responsePair); String latestCertifiedResourceId = null; try { - setConstantMetaData(resource); + boolean shouldBeCertified = nodeTypeArtifactsToHandle == null || nodeTypeArtifactsToHandle.isEmpty() ? true : false; + setConstantMetaData(resource, shouldBeCertified); setMetaDataFromJson(resourceMetaData, resource); Either validateResourceFromYaml = populateResourceFromYaml(resourceYml, resource, isInTransaction); @@ -138,21 +157,30 @@ public class ResourceImportManager { if (isValidResource.isLeft()) { // The flag createNewVersion if false doesn't create new version if (!createNewVersion) { - Either latestByName = resourceOperation.getLatestByName(resource.getName(), isInTransaction); + Either latestByName = toscaOperationFacade.getLatestByName(resource.getName()); if (latestByName.isLeft()) { return Either.right(componentsUtils.getResponseFormatByResource(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, resource)); } } response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock); + Either changeStateResponse; if (response.isLeft()) { resource = response.left().value().left; + + if(nodeTypeArtifactsToHandle !=null && !nodeTypeArtifactsToHandle.isEmpty()){ + Either, ResponseFormat> handleNodeTypeArtifactsRes = + resourceBusinessLogic.handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, creator, isInTransaction); + if(handleNodeTypeArtifactsRes.isRight()){ + return Either.right(handleNodeTypeArtifactsRes.right().value()); + } + } latestCertifiedResourceId = getLatestCertifiedResourceId(resource); - Either certificationResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock); - if (certificationResponse.isRight()) { - response = Either.right(certificationResponse.right().value()); + changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock); + if (changeStateResponse.isRight()) { + response = Either.right(changeStateResponse.right().value()); } else { - responsePair = new ImmutablePair(certificationResponse.left().value(), response.left().value().right); + responsePair = new ImmutablePair<>(changeStateResponse.left().value(), response.left().value().right); response = Either.left(responsePair); } } @@ -490,7 +518,8 @@ public class ResourceImportManager { String derivedFrom = toscaDerivedFromElement.left().value(); log.debug("Derived from TOSCA name is {}", derivedFrom); resource.setDerivedFrom(Arrays.asList(new String[] { derivedFrom })); - Either latestByToscaResourceName = resourceOperation.getLatestByToscaResourceName(derivedFrom, inTransaction); + Either latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom); + if (latestByToscaResourceName.isRight()) { StorageOperationStatus operationStatus = latestByToscaResourceName.right().value(); if (operationStatus.equals(StorageOperationStatus.NOT_FOUND)) { @@ -775,10 +804,18 @@ public class ResourceImportManager { } - private void setConstantMetaData(Resource resource) { - resource.setVersion(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION); - ; - resource.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE); + private void setConstantMetaData(Resource resource, boolean shouldBeCertified) { + String version; + LifecycleStateEnum state; + if(shouldBeCertified){ + version = ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION; + state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE; + }else{ + version = ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION; + state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT; + } + resource.setVersion(version); + resource.setLifecycleState(state); resource.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); resource.setVendorName(ImportUtils.Constants.VENDOR_NAME); resource.setVendorRelease(ImportUtils.Constants.VENDOR_RELEASE); @@ -833,7 +870,7 @@ public class ResourceImportManager { } if (maxOccurrences <= 0 || maxOccurrences < minOccurrences) { - log.debug("Invalid occurrenses format. min occurrence is {}. Max occurrence is {}", minOccurrences, maxOccurrences); + log.debug("Invalid occurrenses format. min occurrence is {}, Max occurrence is {}", minOccurrences, maxOccurrences); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); return Either.right(responseFormat); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java index 6bbe88f30c..1f481a7b5a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java @@ -32,10 +32,6 @@ import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Collectors; @@ -44,6 +40,7 @@ import javax.servlet.http.HttpServletRequest; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine; import org.openecomp.sdc.be.components.distribution.engine.INotificationData; import org.openecomp.sdc.be.components.distribution.engine.VfModuleArtifactPayload; @@ -52,17 +49,20 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.GroupTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DistributionStatusEnum; import org.openecomp.sdc.be.model.DistributionTransitionEnum; -import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupInstance; +import org.openecomp.sdc.be.model.GroupInstanceProperty; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; @@ -70,25 +70,25 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; -import org.openecomp.sdc.be.model.operations.api.IServiceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.ComponentOperation; -import org.openecomp.sdc.be.model.operations.impl.ServiceOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; +import org.openecomp.sdc.be.resources.data.ComponentInstanceData; +import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent; import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent; import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; +import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.kpi.api.ASDCKpiApi; +import org.openecomp.sdc.common.util.GeneralUtility; import org.openecomp.sdc.common.util.ThreadLocalsHolder; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; @@ -124,6 +124,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { @Autowired private ServiceComponentInstanceBusinessLogic serviceComponentInstanceBusinessLogic; + @Autowired + private GroupBusinessLogic groupBusinessLogic; + @Autowired private ICacheMangerOperation cacheManagerOperation; @@ -190,17 +193,16 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } else { newState = DistributionStatusEnum.DISTRIBUTION_REJECTED; } - Either result = serviceOperation.updateDestributionStatus(service, user, newState); + Either result = toscaOperationFacade.updateDistributionStatus(service, user, newState); if (result.isRight()) { - titanGenericDao.rollback(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "ChangeServiceDistributionState"); + titanDao.rollback(); BeEcompErrorManager.getInstance().logBeSystemError("ChangeServiceDistributionState"); log.debug("service {} is change destribuation status failed", service.getUniqueId()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, service.getVersion(), service.getName()); createAudit(user, auditAction, comment, service, responseFormat); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } - titanGenericDao.commit(); + titanDao.commit(); Service updatedService = result.left().value(); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); @@ -319,13 +321,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { log.debug("enrich service with version and state"); service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); service.setVersion(INITIAL_VERSION); + service.setConformanceLevel(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel()); service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); Either createServiceResponse = validateServiceBeforeCreate(service, user, AuditingActionEnum.CREATE_RESOURCE); if (createServiceResponse.isRight()) { return createServiceResponse; } - return createServiceByDao(service, AuditingActionEnum.CREATE_RESOURCE, serviceOperation, user); + return createServiceByDao(service, AuditingActionEnum.CREATE_RESOURCE, user); } private void checkFieldsForOverideAttampt(Service service) { @@ -335,7 +338,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } } - private Either createServiceByDao(Service service, AuditingActionEnum actionEnum, IServiceOperation dataModel, User user) { + private Either createServiceByDao(Service service, AuditingActionEnum actionEnum, User user) { log.debug("send service {} to dao for create", service.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); Either lockResult = lockComponentByName(service.getSystemName(), service, "Create Service"); @@ -352,8 +355,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { createMandatoryArtifactsData(service, user); createServiceApiArtifactsData(service, user); setToscaArtifactsPlaceHolders(service, user); + Either genericServiceEither = fetchAndSetDerivedFromGenericType(service); + if (genericServiceEither.isRight()) + return Either.right(genericServiceEither.right().value()); - Either dataModelResponse = dataModel.createService(service); + generateInputsFromGenericTypeProperties(service, genericServiceEither.left().value()); + + Either dataModelResponse = toscaOperationFacade.createToscaComponent(service); // service created successfully!!! if (dataModelResponse.isLeft()) { @@ -361,12 +369,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE); ASDCKpiApi.countCreatedServicesKPI(); - - Service createdService = dataModelResponse.left().value(); - // //add service to cache - // cacheManagerOperation.updateComponentInCache(createdService.getUniqueId(), - // createdService.getLastUpdateDate(), NodeTypeEnum.Service); - return Either.left(dataModelResponse.left().value()); } @@ -380,6 +382,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } } + @SuppressWarnings("unchecked") private void createServiceApiArtifactsData(Service service, User user) { // create mandatory artifacts @@ -389,7 +392,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { // UniqueIdBuilder.buildServiceUniqueId(service.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), // service.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion()); String serviceUniqueId = service.getUniqueId(); - Map artifactMap = service.getArtifacts(); + Map artifactMap = service.getServiceApiArtifacts(); if (artifactMap == null) artifactMap = new HashMap(); @@ -417,7 +420,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); } - service.setArtifacts(artifactMap); + service.setServiceApiArtifacts(artifactMap); } } @@ -458,6 +461,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return categoryValidation; } + // validate project name (ProjectCode) - mandatory in service + log.debug("validate projectName"); Either projectCodeValidation = validateProjectCode(user, service, actionEnum); if (projectCodeValidation.isRight()) { @@ -494,7 +499,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.right(resp.right().value()); } - Either dataModelResponse = serviceOperation.validateServiceNameExists(serviceName); + Either dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE); + + // DE242223 + titanDao.commit(); if (dataModelResponse.isLeft()) { Map result = new HashMap<>(); @@ -512,10 +520,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { this.elementDao = elementDao; } - public void setServiceOperation(ServiceOperation serviceOperation) { - this.serviceOperation = serviceOperation; - } - public void setCassandraAuditingDao(AuditCassandraDao auditingDao) { this.auditCassandraDao = auditingDao; } @@ -549,15 +553,15 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.right(validateRes.right().value()); } - Either storageStatus = serviceOperation.getService(serviceId); + Either storageStatus = toscaOperationFacade.getToscaElement(serviceId); if (storageStatus.isRight()) { return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); } Service currentService = storageStatus.left().value(); - if (!ComponentValidationUtils.canWorkOnService(currentService.getUniqueId(), serviceOperation, user.getUserId())) { - log.info("Restricted operation for user {} on service {}", user.getUserId(), currentService.getCreatorUserId()); + if (!ComponentValidationUtils.canWorkOnComponent(currentService, user.getUserId())) { + log.info("Restricted operation for user: {}, on service: {}", user.getUserId(), currentService.getCreatorUserId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } @@ -574,15 +578,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.right(lockResult.right().value()); } try { - Either updateResponse = serviceOperation.updateService(serviceToUpdate, true); + Either updateResponse = toscaOperationFacade.updateToscaElement(serviceToUpdate); if (updateResponse.isRight()) { - titanGenericDao.rollback(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Update Service Metadata"); + titanDao.rollback(); BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata"); log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } - titanGenericDao.commit(); + titanDao.commit(); return Either.left(updateResponse.left().value()); } finally { graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); @@ -619,7 +622,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { String lastUpdaterFullNameUpdated = serviceUpdate.getLastUpdaterFullName(); String lastUpdaterFullNameCurrent = currentService.getLastUpdaterFullName(); if (lastUpdaterFullNameUpdated != null && !lastUpdaterFullNameCurrent.equals(lastUpdaterFullNameUpdated)) { - log.info("update srvice: recived request to update lastUpdaterFullName to {} the field is not updatable ignoring.", lastUpdaterFullNameUpdated ); + log.info("update srvice: recived request to update lastUpdaterFullName to {} the field is not updatable ignoring.", lastUpdaterFullNameUpdated); } response = validateAndUpdateServiceName(user, currentService, serviceUpdate, hasBeenCertified, null); @@ -709,10 +712,31 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { log.warn("Product invariant UUID is automatically set and cannot be updated"); serviceUpdate.setInvariantUUID(currentInvariantUuid); } + validateAndUpdateEcompNaming(currentService, serviceUpdate); + return Either.left(currentService); } + private void validateAndUpdateEcompNaming(Service currentService, Service serviceUpdate) { + Boolean isEcompoGeneratedCurr = currentService.isEcompGeneratedNaming(); + Boolean isEcompoGeneratedUpdate = serviceUpdate.isEcompGeneratedNaming(); + if (isEcompoGeneratedUpdate != null && isEcompoGeneratedCurr != isEcompoGeneratedUpdate) { + currentService.setEcompGeneratedNaming(isEcompoGeneratedUpdate); + } + String namingPolicyUpd = serviceUpdate.getNamingPolicy(); + if (!currentService.isEcompGeneratedNaming()) { + if (ValidationUtils.validateStringNotEmpty(namingPolicyUpd)) { + log.warn("NamingPolicy must be empty for EcompGeneratedNaming=false"); + currentService.setNamingPolicy(""); + } else { + currentService.setNamingPolicy(namingPolicyUpd); + } + }else{ + currentService.setNamingPolicy(namingPolicyUpd); + } + } + private Either validateAndUpdateContactId(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) { String contactIdUpdated = serviceUpdate.getContactId(); String contactIdCurrent = currentService.getContactId(); @@ -765,12 +789,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { String projectCodeUpdated = serviceUpdate.getProjectCode(); String projectCodeCurrent = currentService.getProjectCode(); if (!projectCodeCurrent.equals(projectCodeUpdated)) { + Either validatProjectCodeResponse = validateProjectCode(user, serviceUpdate, audatingAction); if (validatProjectCodeResponse.isRight()) { ResponseFormat errorRespons = validatProjectCodeResponse.right().value(); return Either.right(errorRespons); } currentService.setProjectCode(projectCodeUpdated); + } return Either.left(true); } @@ -892,7 +918,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } user = eitherCreator.left().value(); - Either serviceStatus = serviceOperation.getService(serviceId); + Either serviceStatus = toscaOperationFacade.getToscaElement(serviceId); if (serviceStatus.isRight()) { log.debug("failed to get service {}", serviceId); return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceStatus.right().value()), ""); @@ -922,10 +948,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (result == null || !result.equals(StorageOperationStatus.OK)) { log.warn("operation failed. do rollback"); BeEcompErrorManager.getInstance().logBeSystemError("Delete Service"); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("operation success. do commit"); - titanGenericDao.commit(); + titanDao.commit(); } graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); } @@ -972,10 +998,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (result == null || !result.equals(StorageOperationStatus.OK)) { log.warn("operation failed. do rollback"); BeEcompErrorManager.getInstance().logBeSystemError("Delete Service"); - titanGenericDao.rollback(); + titanDao.rollback(); } else { log.debug("operation success. do commit"); - titanGenericDao.commit(); + titanDao.commit(); } graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); } @@ -994,7 +1020,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } user = eitherCreator.left().value(); - Either storageStatus = serviceOperation.getService(serviceId); + Either storageStatus = toscaOperationFacade.getToscaElement(serviceId); if (storageStatus.isRight()) { log.debug("failed to get service by id {}", serviceId); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceId)); @@ -1010,7 +1036,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (resp.isRight()) { return Either.right(resp.right().value()); } - Either storageStatus = serviceOperation.getServiceByNameAndVersion(serviceName, serviceVersion, null, false); + Either storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.SERVICE, serviceName, serviceVersion); if (storageStatus.isRight()) { log.debug("failed to get service by name {} and version {}", serviceName, serviceVersion); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceName)); @@ -1019,6 +1045,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.left(service); } + @SuppressWarnings("unchecked") private void createMandatoryArtifactsData(Service service, User user) { // create mandatory artifacts @@ -1076,7 +1103,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { transitionEnum = DistributionTransitionEnum.getFromDisplayName(distributionTransition); if (transitionEnum == null) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Change Service Distribution"); BeEcompErrorManager.getInstance().logBeSystemError("Change Service Distribution"); log.info("state operation is not valid. operations allowed are: {}", DistributionTransitionEnum.valuesAsString()); ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); @@ -1090,7 +1116,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { String data = comment.getUserRemarks(); if (data == null || data.trim().isEmpty()) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "Change Service Distribution"); BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution"); log.debug("user comment cannot be empty or null."); return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); @@ -1101,7 +1126,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { data = ValidationUtils.stripOctets(data); if (!ValidationUtils.validateLength(data, ValidationUtils.COMMENT_MAX_LENGTH)) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "Change Service Distribution"); BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution"); log.debug("user comment exceeds limit."); return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, "comment", String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH))); @@ -1113,7 +1137,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } private Either validateServiceDistributionChange(User user, String serviceId, AuditingActionEnum auditAction, String comment) { - Either storageStatus = serviceOperation.getService(serviceId); + Either storageStatus = toscaOperationFacade.getToscaElement(serviceId); if (storageStatus.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId); createAudit(user, auditAction, comment, responseFormat); @@ -1132,13 +1156,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { private Either validateUserDistributionChange(User user, Service service, AuditingActionEnum auditAction, String comment) { log.debug("get user from DB"); - /* - * Either eitherCreator = userAdmin.getUser(user.getUserId());s if (eitherCreator.isRight() || eitherCreator.left().value() == null) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeUserMissingError, - * "Activate Distribution", user.getUserId()); log. debug("changeServiceDistributionState method - user is not listed. userId=" + user.getUserId()); ResponseFormat responseFormat = - * componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND); createAudit(user, auditAction, comment, responseFormat); return Either.right(responseFormat); } user = eitherCreator.left().value(); log.debug("validate user role"); if - * (!validateUserTemp(user, Role.ADMIN, Role.GOVERNOR)) { log.info("role {} is not allowed to perform this action", user.getRole()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - * createAudit(user, auditAction, comment, service, responseFormat); return Either.right(responseFormat); } - */ + // get user details Either eitherCreator = validateUser(user, "Activate Distribution", service, auditAction, false); if (eitherCreator.isRight()) { @@ -1150,6 +1168,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { List roles = new ArrayList<>(); roles.add(Role.ADMIN); roles.add(Role.GOVERNOR); + roles.add(Role.OPS); Either validateRes = validateUserRole(user, service, roles, auditAction, comment); if (validateRes.isRight()) { return Either.right(validateRes.right().value()); @@ -1208,14 +1227,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { ServletContext servletContext = request.getSession().getServletContext(); boolean isDistributionEngineUp = getHealthCheckBL(servletContext).isDistributionEngineUp(request.getSession().getServletContext()); // DE if (!isDistributionEngineUp) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Distribution Engine is DOWN"); BeEcompErrorManager.getInstance().logBeSystemError("Distribution Engine is DOWN"); log.debug("Distribution Engine is DOWN"); response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); return Either.right(response); } - Either serviceRes = serviceOperation.getService(serviceId); + Either serviceRes = toscaOperationFacade.getToscaElement(serviceId); if (serviceRes.isRight()) { log.debug("failed retrieving service"); response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceRes.right().value(), ComponentTypeEnum.SERVICE), serviceId); @@ -1243,7 +1261,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { response = componentsUtils.getResponseFormat(ActionStatus.OK); result = Either.left(updatedService); } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Activate Distribution - send notification"); BeEcompErrorManager.getInstance().logBeSystemError("Activate Distribution - send notification"); log.debug("distributionEngine.notifyService response is: {}", notifyServiceResponse); response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); @@ -1273,15 +1290,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.right(lockResult.right().value()); } try { - Either result = serviceOperation.updateDestributionStatus(service, user, state); + Either result = toscaOperationFacade.updateDistributionStatus(service, user, state); if (result.isRight()) { - titanGenericDao.rollback(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "updateDistributionStatusForActivation"); + titanDao.rollback(); BeEcompErrorManager.getInstance().logBeSystemError("updateDistributionStatusForActivation"); log.debug("service {} change distribution status failed", serviceId); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } - titanGenericDao.commit(); + titanDao.commit(); return Either.left(result.left().value()); } finally { graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); @@ -1298,9 +1314,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { log.debug("mark distribution deployed"); AuditingActionEnum auditAction = AuditingActionEnum.DISTRIBUTION_DEPLOY; - Either getServiceResponse = serviceOperation.getService(serviceId); + Either getServiceResponse = toscaOperationFacade.getToscaElement(serviceId); if (getServiceResponse.isRight()) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeServiceMissingError, "markDistributionAsDeployed", serviceId); BeEcompErrorManager.getInstance().logBeComponentMissingError("markDistributionAsDeployed", ComponentTypeEnum.SERVICE.getValue(), serviceId); log.debug("service {} not found", serviceId); ResponseFormat responseFormat = auditDeployError(did, user, auditAction, null, componentsUtils.convertFromStorageResponse(getServiceResponse.right().value(), ComponentTypeEnum.SERVICE), ""); @@ -1323,36 +1338,35 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { public Either generateVfModuleArtifacts(Service service, User modifier, boolean shouldLock) { Function>> artifactTaskGeneratorCreator = ri -> // Only one VF Module Artifact per instance - add it to a list of one - Arrays.asList(new VfModuleArtifacGenerator(modifier, ri, service, shouldLock)); + buildArtifactGenList(service, modifier, shouldLock, ri); return generateDeploymentArtifacts(service, modifier, artifactTaskGeneratorCreator); } - private List collectGroupsForCompInstance(ComponentInstance currVF, Wrapper responseWrapper) { - List relevantGroups = new ArrayList<>(); - Either, StorageOperationStatus> eitherGroups = groupOperation.getAllGroups(currVF.getComponentUid(), NodeTypeEnum.Resource); - - if (eitherGroups.isRight()) { - final StorageOperationStatus storageStatus = eitherGroups.right().value(); - if (storageStatus != StorageOperationStatus.NOT_FOUND && storageStatus != StorageOperationStatus.OK) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageStatus); - responseWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus)); - } + private List> buildArtifactGenList(Service service, User modifier, boolean shouldLock, ComponentInstance ri) { + List> asList = new ArrayList>(); - } else { - relevantGroups = eitherGroups.left().value().stream().filter(p -> GroupTypeEnum.VF_MODULE.getGroupTypeName().equals(p.getType())).collect(Collectors.toList()); + if (ri.getOriginType() == OriginTypeEnum.VF) { + asList = Arrays.asList(new VfModuleArtifacGenerator(modifier, ri, service, shouldLock)); } - return relevantGroups; + return asList; } - private ArtifactDefinition getVfModuleArtifactForCompInstance(ComponentInstance currVF, Service service, User modifier, List groupsForCurrVF, Wrapper payloadWrapper, Wrapper responseWrapper) { - ArtifactDefinition vfModuleAertifact = null; + private List collectGroupsInstanceForCompInstance(ComponentInstance currVF, Wrapper responseWrapper) { - Optional optionalVfModuleArtifact = currVF.getDeploymentArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())).findAny(); - if (optionalVfModuleArtifact.isPresent()) { - vfModuleAertifact = optionalVfModuleArtifact.get(); - } else { + return currVF.getGroupInstances(); + } + + private ArtifactDefinition getVfModuleInstArtifactForCompInstance(ComponentInstance currVF, Service service, User modifier, List groupsForCurrVF, Wrapper payloadWrapper, Wrapper responseWrapper) { + ArtifactDefinition vfModuleAertifact = null; + if (MapUtils.isNotEmpty(currVF.getDeploymentArtifacts())) { + Optional optionalVfModuleArtifact = currVF.getDeploymentArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())).findAny(); + if (optionalVfModuleArtifact.isPresent()) { + vfModuleAertifact = optionalVfModuleArtifact.get(); + } + } + if (vfModuleAertifact == null) { Either createVfModuleArtifact = createVfModuleArtifact(modifier, currVF, service, payloadWrapper.getInnerElement()); if (createVfModuleArtifact.isLeft()) { vfModuleAertifact = createVfModuleArtifact.left().value(); @@ -1363,19 +1377,26 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return vfModuleAertifact; } - private void fillVfModuleHeatEnvPayload(List groupsForCurrVF, ComponentInstance currVFInstance, Wrapper payloadWrapper) { + private void fillVfModuleInstHeatEnvPayload(List groupsForCurrVF, ComponentInstance currVFInstance, Wrapper payloadWrapper) { // Converts GroupDefinition to VfModuleArtifactPayload which is the // format used in the payload - List vfModulePayloadForCurrVF = groupsForCurrVF.stream().map(group -> new VfModuleArtifactPayload(group)).collect(Collectors.toList()); - Collections.sort(vfModulePayloadForCurrVF, (art1, art2) -> VfModuleArtifactPayload.compareByGroupName(art1, art2)); - // Update Payload With Heat Env - vfModulePayloadForCurrVF.stream().forEach(e -> addHeatEnvArtifactsToVFModulePayload(e, currVFInstance)); + // List vfModulePayloadForCurrVF = groupsForCurrVF.stream().map(group -> new VfModuleArtifactPayload(group)).collect(Collectors.toList()); + List vfModulePayloadForCurrVF = new ArrayList(); + if (groupsForCurrVF != null) { + for (GroupInstance groupInstance : groupsForCurrVF) { + VfModuleArtifactPayload modulePayload = new VfModuleArtifactPayload(groupInstance); + vfModulePayloadForCurrVF.add(modulePayload); + } + Collections.sort(vfModulePayloadForCurrVF, (art1, art2) -> VfModuleArtifactPayload.compareByGroupName(art1, art2)); + // Update Payload With Heat Env + vfModulePayloadForCurrVF.stream().forEach(e -> addHeatEnvArtifactsToVFModulePayload(e, currVFInstance)); - final Gson gson = new GsonBuilder().setPrettyPrinting().create(); + final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - String vfModulePayloadString = gson.toJson(vfModulePayloadForCurrVF); - payloadWrapper.setInnerElement(vfModulePayloadString); + String vfModulePayloadString = gson.toJson(vfModulePayloadForCurrVF); + payloadWrapper.setInnerElement(vfModulePayloadString); + } } @@ -1383,6 +1404,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { List originalModuleArtifacts = vfModulePayload.getArtifacts(); if (!MapUtils.isEmpty(currVFInstance.getDeploymentArtifacts()) && !CollectionUtils.isEmpty(originalModuleArtifacts)) { + // EVG : fix now for patch. remove null from list. Need to be fixed later : remove VF HEAT ENV uuid from the list?? + List filteredUUIDFromModule = originalModuleArtifacts.stream().filter(uuid -> uuid != null).collect(Collectors.toList()); + final Collection depInsArtifacts = currVFInstance.getDeploymentArtifacts().values(); // All Heat_ENV List heatEnvArtifacts = depInsArtifacts.stream().filter(art -> art.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())).collect(Collectors.toList()); @@ -1393,23 +1417,23 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { List relevantHeatEnvUUID = heatEnvArtifacts.stream().filter(heatEnv -> moduleArtUniqueId.contains(heatEnv.getGeneratedFromId())).map(heatEnv -> heatEnv.getArtifactUUID()).collect(Collectors.toList()); List fullArtifactList = new ArrayList<>(); - fullArtifactList.addAll(originalModuleArtifacts); + fullArtifactList.addAll(filteredUUIDFromModule); fullArtifactList.addAll(relevantHeatEnvUUID); vfModulePayload.setArtifacts(fullArtifactList); } } - private Either generateVfModuleArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock) { + private Either generateVfModuleInstanceArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock) { ArtifactDefinition vfModuleAertifact = null; Wrapper responseWrapper = new Wrapper<>(); Wrapper payloadWrapper = new Wrapper<>(); - List groupsForCurrVF = collectGroupsForCompInstance(currVFInstance, responseWrapper); + List groupsForCurrVF = collectGroupsInstanceForCompInstance(currVFInstance, responseWrapper); if (responseWrapper.isEmpty()) { - fillVfModuleHeatEnvPayload(groupsForCurrVF, currVFInstance, payloadWrapper); + fillVfModuleInstHeatEnvPayload(groupsForCurrVF, currVFInstance, payloadWrapper); } - if (responseWrapper.isEmpty()) { - vfModuleAertifact = getVfModuleArtifactForCompInstance(currVFInstance, service, modifier, groupsForCurrVF, payloadWrapper, responseWrapper); + if (responseWrapper.isEmpty() && payloadWrapper.getInnerElement() != null) { + vfModuleAertifact = getVfModuleInstArtifactForCompInstance(currVFInstance, service, modifier, groupsForCurrVF, payloadWrapper, responseWrapper); } if (responseWrapper.isEmpty() && vfModuleAertifact != null) { vfModuleAertifact = fillVfModulePayload(modifier, currVFInstance, vfModuleAertifact, shouldLock, payloadWrapper, responseWrapper); @@ -1425,21 +1449,24 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return result; } - private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleAertifact, boolean shouldLock, Wrapper payloadWrapper, Wrapper responseWrapper) { + private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock, Wrapper payloadWrapper, Wrapper responseWrapper) { ArtifactDefinition result = null; - final Either eitherResource = resourceOperation.getResource(currVF.getComponentUid()); + final Either eitherResource = toscaOperationFacade.getToscaElement(currVF.getComponentUid()); if (eitherResource.isRight()) { responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherResource.right().value()))); - } else { + } else if (!payloadWrapper.isEmpty()) { Resource resource = eitherResource.left().value(); - Either eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleAertifact, resource, currVF.getName(), modifier, shouldLock, () -> System.currentTimeMillis(), - () -> Either.left(artifactsBusinessLogic.createEsArtifactData(vfModuleAertifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8)))); + Either eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleArtifact, resource.getComponentType(), resource, currVF.getName(), modifier, shouldLock, () -> System.currentTimeMillis(), + () -> Either.left(artifactsBusinessLogic.createEsArtifactData(vfModuleArtifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8))), currVF.getUniqueId()); if (eitherPayload.isLeft()) { result = eitherPayload.left().value(); } else { responseWrapper.setInnerElement(eitherPayload.right().value()); } } + if (result == null) { + result = vfModuleArtifact; + } return result; } @@ -1447,6 +1474,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { private Either createVfModuleArtifact(User modifier, ComponentInstance currVF, Service service, String vfModulePayloadString) { ArtifactDefinition vfModuleArtifactDefinition = new ArtifactDefinition(); + String newCheckSum = null; vfModuleArtifactDefinition.setDescription("Auto-generated VF Modules information artifact"); vfModuleArtifactDefinition.setArtifactDisplayName("Vf Modules Metadata"); @@ -1456,8 +1484,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { vfModuleArtifactDefinition.setTimeout(0); vfModuleArtifactDefinition.setArtifactName(currVF.getNormalizedName() + "_modules.json"); vfModuleArtifactDefinition.setPayloadData(vfModulePayloadString); + if (vfModulePayloadString != null) { + newCheckSum = GeneralUtility.calculateMD5ByByteArray(vfModulePayloadString.getBytes()); + } + vfModuleArtifactDefinition.setArtifactChecksum(newCheckSum); - Either addArifactToComponent = artifactOperation.addArifactToComponent(vfModuleArtifactDefinition, currVF.getUniqueId(), NodeTypeEnum.ResourceInstance, true, true); + Either addArifactToComponent = artifactToscaOperation.addArifactToComponent(vfModuleArtifactDefinition, service.getUniqueId(), NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId()); Either result; if (addArifactToComponent.isLeft()) { @@ -1477,7 +1509,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { // Filter in Only Heat Env filter(depArtifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(depArtifact.getArtifactType())). // Create ArtifactGenerator from those Artifacts - map(depArtifact -> new HeatEnvArtifactGenerator(depArtifact, service, resourceInstance.getName(), modifier, shouldLock)).collect(Collectors.toList()); + map(depArtifact -> new HeatEnvArtifactGenerator(depArtifact, service, resourceInstance.getName(), modifier, shouldLock, resourceInstance.getUniqueId())).collect(Collectors.toList()); return generateDeploymentArtifacts(service, modifier, artifactTaskGeneratorCreator); @@ -1485,41 +1517,25 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { private Either generateDeploymentArtifacts(Service service, User modifier, Function>> artifactTaskGeneratorCreator) { - List>> allFutures = new ArrayList<>(); - // Get Flat List of (Callable) ArtifactGenerator for all the RI in the // service if (service.getComponentInstances() != null) { List> artifactGenList = service.getComponentInstances().stream().flatMap(ri -> artifactTaskGeneratorCreator.apply(ri).stream()).collect(Collectors.toList()); if (artifactGenList != null && !artifactGenList.isEmpty()) { - ExecutorService executor = Executors.newFixedThreadPool(artifactGenList.size()); - - artifactGenList.stream().forEach(e -> allFutures.add(executor.submit(e))); - - boolean isSuccess = true; - ResponseFormat firstError = null; - for (Future> entry : allFutures) { + for (ArtifactGenerator entry : artifactGenList) { + Either callRes; try { - Either actionStatus = entry.get(20, TimeUnit.SECONDS); - if (actionStatus.isRight()) { - isSuccess = false; - if (firstError == null) { - firstError = actionStatus.right().value(); - } - log.debug("Failed to generate artifact error : {}", actionStatus.right().value()); + callRes = entry.call(); + if (callRes.isRight()) { + log.debug("Failed to generate artifact error : {}", callRes.right().value()); + return Either.right(callRes.right().value()); } } catch (Exception e) { - log.debug("Failed to collect result from artifact generator ", e); - isSuccess = false; - firstError = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + log.debug("Failed to generate artifact exception : {}", e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } } - executor.shutdown(); - if (!isSuccess) { - return Either.right(firstError); - } } - } return Either.left(service); } @@ -1533,19 +1549,21 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { Service service; String resourceInstanceName; User modifier; + String instanceId; boolean shouldLock; - HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier, boolean shouldLock) { + HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier, boolean shouldLock, String instanceId) { this.artifactDefinition = artifactDefinition; this.service = service; this.resourceInstanceName = resourceInstanceName; this.modifier = modifier; this.shouldLock = shouldLock; + this.instanceId = instanceId; } @Override public Either call() throws Exception { - return artifactsBusinessLogic.generateHeatEnvArtifact(artifactDefinition, service, resourceInstanceName, modifier, shouldLock); + return artifactsBusinessLogic.generateHeatEnvArtifact(artifactDefinition, ComponentTypeEnum.RESOURCE_INSTANCE, service, resourceInstanceName, modifier, shouldLock, instanceId); } public ArtifactDefinition getArtifactDefinition() { @@ -1562,7 +1580,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { @Override public Either call() throws Exception { - return generateVfModuleArtifact(user, componentInstance, service, shouldLock); + return generateVfModuleInstanceArtifact(user, componentInstance, service, shouldLock);// generateVfModuleArtifact(user, componentInstance, service, shouldLock); } private VfModuleArtifacGenerator(User user, ComponentInstance componentInstance, Service service, boolean shouldLock) { @@ -1618,7 +1636,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { List distributionRequests = distRequestsResponse.left().value(); if (distributionRequests.isEmpty()) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionMissingError, "markDistributionAsDeployed", did); BeEcompErrorManager.getInstance().logBeDistributionMissingError("markDistributionAsDeployed", did); log.info("distribution {} is not found", did); ResponseFormat error = auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_NOT_FOUND); @@ -1686,9 +1703,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { private Either validateRoleForDeploy(String did, User user, AuditingActionEnum auditAction, Service service) { Either eitherCreator = userAdmin.getUser(user.getUserId(), false); if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUserMissingError, "Deploy Service", user.getUserId()); BeEcompErrorManager.getInstance().logBeUserMissingError("Deploy Service", user.getUserId()); - log.debug("validateRoleForDeploy method - user is not listed. userId={}", user.getUserId()); + log.debug("validateRoleForDeploy method - user is not listed. userId= {}", user.getUserId()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, user.getUserId()); auditDeployError(did, user, auditAction, service, ActionStatus.USER_NOT_FOUND); return Either.right(responseFormat); @@ -1711,7 +1727,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { @Override public void setDeploymentArtifactsPlaceHolder(Component component, User user) { - // TODO Auto-generated method stub } @@ -1739,21 +1754,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (resp.isRight()) { return Either.right(resp.right().value()); } - - ComponentOperation componentOperation = getComponentOperation(componentTypeEnum); - - Either, StorageOperationStatus> componentInstancesResponse = componentOperation.getAllComponentInstncesMetadata(componentId, componentTypeEnum.getNodeType()); - if (componentInstancesResponse.isRight()) { - - if (componentInstancesResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - return Either.left(new ArrayList()); - } - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentInstancesResponse.right().value())); + Either getComponentRes = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll); + if (getComponentRes.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentRes.right().value())); return Either.right(responseFormat); } - List componentInstances = componentInstancesResponse.left().value(); - componentInstances = componentInstances.stream().filter(instance -> instance.getOriginType().equals(OriginTypeEnum.VF)).collect(Collectors.toList()); + List componentInstances = getComponentRes.left().value().getComponentInstances(); + // componentInstances = componentInstances.stream().filter(instance -> instance.getOriginType().equals(OriginTypeEnum.VF)).collect(Collectors.toList()); return Either.left(componentInstances); } @@ -1765,4 +1773,207 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) { this.cacheManagerOperation = cacheManagerOperation; } + + /** + * updates group instance with new property values in case of successful update of group instance related component instance will be updated with new modification time and related service will be updated with new last update date + * + * @param modifier + * @param serviceId + * @param componentInstanceId + * @param groupInstanceId + * @param newProperties + * @return + */ + public Either, ResponseFormat> updateGroupInstancePropertyValues(User modifier, String serviceId, String componentInstanceId, String groupInstanceId, List newProperties) { + + Either, ResponseFormat> actionResult = null; + Either, ResponseFormat> validateUserAndComponentRes; + Component component = null; + Either lockResult = null; + log.debug("Going to update group instance {} of service {} with new property values. ", groupInstanceId, serviceId); + try { + validateUserAndComponentRes = validateUserAndComponent(serviceId, modifier); + if (validateUserAndComponentRes.isRight()) { + log.debug("Cannot update group instance {} of service {} with new property values. Validation failed. ", groupInstanceId, serviceId); + actionResult = Either.right(validateUserAndComponentRes.right().value()); + } + if (actionResult == null) { + component = validateUserAndComponentRes.left().value().getKey(); + lockResult = lockComponentByName(component.getSystemName(), component, "Update Group Instance on Service"); + if (lockResult.isRight()) { + log.debug("Failed to lock service {}. Response is {}. ", component.getName(), lockResult.right().value().getFormattedMessage()); + actionResult = Either.right(lockResult.right().value()); + } else { + log.debug("The service with system name {} locked. ", component.getSystemName()); + } + } + if (actionResult == null) { + actionResult = validateAndUpdateGroupInstancePropertyValuesAndContainingParents(component, componentInstanceId, groupInstanceId, newProperties); + if (actionResult.isRight()) { + log.debug("Failed to validate and update group instance {} property values and containing parents. The message is {}. ", groupInstanceId, actionResult.right().value().getFormattedMessage()); + } + } + } catch (Exception e) { + log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e); + actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + if (lockResult != null && lockResult.isLeft() && lockResult.left().value()) { + graphLockOperation.unlockComponentByName(component.getSystemName(), component.getUniqueId(), NodeTypeEnum.Service); + } + } + return actionResult; + } + + private Either, ResponseFormat> validateAndUpdateGroupInstancePropertyValuesAndContainingParents(Component component, String componentInstanceId, String groupInstanceId, List newProperties) { + + Either, ResponseFormat> actionResult = null; + Either, ResponseFormat> findGroupInstanceRes; + Either, ResponseFormat> updateParentsModificationTimeRes; + ComponentInstance relatedComponentInstance = null; + GroupInstance oldGroupInstance = null; + Either updateGroupInstanceResult = null; + GroupInstance updatedGroupInstance = null; + boolean inTransaction = true; + boolean shouldCloseTransaction = true; + findGroupInstanceRes = findGroupInstanceOnRelatedComponentInstance(component, componentInstanceId, groupInstanceId); + if (findGroupInstanceRes.isRight()) { + log.debug("Group instance {} not found. ", groupInstanceId); + actionResult = Either.right(findGroupInstanceRes.right().value()); + } + if (actionResult == null) { + oldGroupInstance = findGroupInstanceRes.left().value().getValue(); + relatedComponentInstance = findGroupInstanceRes.left().value().getKey(); + updateGroupInstanceResult = groupBusinessLogic.validateAndUpdateGroupInstancePropertyValues(component.getUniqueId(), componentInstanceId, oldGroupInstance, newProperties, inTransaction); + if (updateGroupInstanceResult.isRight()) { + log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName()); + actionResult = Either.right(updateGroupInstanceResult.right().value()); + } + } + if (actionResult == null) { + updatedGroupInstance = updateGroupInstanceResult.left().value(); + if (!oldGroupInstance.getModificationTime().equals(updatedGroupInstance.getModificationTime())) { + updateParentsModificationTimeRes = updateParentsModificationTimeAndCustomizationUuid(component, relatedComponentInstance, updatedGroupInstance, inTransaction, shouldCloseTransaction); + if (updateParentsModificationTimeRes.isRight()) { + log.debug("Failed to update modification time. ", oldGroupInstance.getName()); + actionResult = Either.right(updateParentsModificationTimeRes.right().value()); + } + } + } + if (actionResult == null) { + actionResult = Either.left(updatedGroupInstance.convertToGroupInstancesProperties()); + } + return actionResult; + } + + private Either, ResponseFormat> updateParentsModificationTimeAndCustomizationUuid(Component component, ComponentInstance relatedComponentInstance, GroupInstance updatedGroupInstance, + boolean inTranscation, boolean shouldCloseTransaction) { + + Either, ResponseFormat> actionResult; + Either serviceMetadataUpdateResult; + Either updateComponentInstanceRes = serviceComponentInstanceBusinessLogic.updateComponentInstanceModificationTimeAndCustomizationUuid(relatedComponentInstance, NodeTypeEnum.ResourceInstance, + updatedGroupInstance.getModificationTime(), inTranscation); + if (updateComponentInstanceRes.isRight()) { + log.debug("Failed to update component instance {} after update of group instance {}. ", relatedComponentInstance.getName(), updatedGroupInstance.getName()); + actionResult = Either.right(updateComponentInstanceRes.right().value()); + } else { + serviceMetadataUpdateResult = toscaOperationFacade.updateComponentLastUpdateDateOnGraph(component, updatedGroupInstance.getModificationTime()); + if (serviceMetadataUpdateResult.isRight()) { + log.debug("Failed to update service {} after update of component instance {} with new property values of group instance {}. ", component.getName(), relatedComponentInstance.getName(), updatedGroupInstance.getName()); + actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceMetadataUpdateResult.right().value()))); + } else { + actionResult = Either.left(new ImmutablePair<>(serviceMetadataUpdateResult.left().value(), updateComponentInstanceRes.left().value())); + } + } + return actionResult; + } + + private Either, ResponseFormat> validateUserAndComponent(String serviceId, User modifier) { + + Either, ResponseFormat> result = null; + Either validateComponentExistsRes = null; + User currUser = null; + Component component = null; + Either validationUserResult = validateUserIgnoreAudit(modifier, "updateGroupInstancePropertyValues"); + if (validationUserResult.isRight()) { + log.debug("Failed to validate user with userId for update service {}. ", modifier.getUserId(), serviceId); + result = Either.right(validationUserResult.right().value()); + } + if (result == null) { + currUser = validationUserResult.left().value(); + validateComponentExistsRes = validateComponentExists(serviceId, ComponentTypeEnum.SERVICE, null); + if (validateComponentExistsRes.isRight()) { + log.debug("Failed to validate service existing {}. ", serviceId); + result = Either.right(validateComponentExistsRes.right().value()); + } + } + if (result == null) { + component = validateComponentExistsRes.left().value(); + if (!ComponentValidationUtils.canWorkOnComponent(component, currUser.getUserId())) { + log.info("Restricted operation for user: {}, on service: {}", currUser.getUserId(), component.getCreatorUserId()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + } + if (result == null) { + result = Either.left(new ImmutablePair<>(component, currUser)); + } + return result; + } + + private Either, ResponseFormat> findGroupInstanceOnRelatedComponentInstance(Component component, String componentInstanceId, String groupInstanceId) { + + Either, ResponseFormat> actionResult = null; + GroupInstance groupInstance = null; + ComponentInstance foundComponentInstance = findRelatedComponentInstance(component, componentInstanceId); + if (foundComponentInstance == null) { + log.debug("Component instance {} not found on service {}. ", componentInstanceId, component.getName()); + actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstanceId, "resource instance", "service", component.getName())); + } else if (!CollectionUtils.isEmpty(foundComponentInstance.getGroupInstances())) { + groupInstance = foundComponentInstance.getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstanceId)).findFirst().orElse(null); + if (groupInstance == null) { + log.debug("Group instance {} not found on component instance {}. ", groupInstanceId, foundComponentInstance.getName()); + actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE, groupInstanceId, foundComponentInstance.getName())); + } + } + if (actionResult == null) { + actionResult = Either.left(new ImmutablePair<>(foundComponentInstance, groupInstance)); + } + return actionResult; + } + + private ComponentInstance findRelatedComponentInstance(Component component, String componentInstanceId) { + ComponentInstance componentInstance = null; + if (!CollectionUtils.isEmpty(component.getComponentInstances())) { + componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null); + } + return componentInstance; + } + + private Either validateUserIgnoreAudit(User modifier, String ecompErrorContext) { + Either result = validateUser(modifier, ecompErrorContext, null, null, false); + if (result.isLeft()) { + List roles = new ArrayList<>(); + roles.add(Role.ADMIN); + roles.add(Role.DESIGNER); + Either validationRoleRes = validateUserRole(result.left().value(), roles); + if (validationRoleRes.isRight()) { + result = Either.right(validationRoleRes.right().value()); + } + } + return result; + } + + public Either getUiComponentDataTransferByComponentId(String resourceId, List dataParamsToReturn) { + + ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn); + Either serviceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen); + + if (serviceResultEither.isRight()) { + log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn.toString()); + return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(serviceResultEither.right().value()), "")); + } + + Service service = serviceResultEither.left().value(); + UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromServiceByParams(service, dataParamsToReturn); + return Either.left(dataTransfer); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java index c42cf004ff..9586be81ea 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java @@ -41,16 +41,6 @@ public class ServiceComponentInstanceBusinessLogic extends ComponentInstanceBusi return NodeTypeEnum.Resource; } - @Override - protected ComponentOperation getContainerComponentOperation() { - return serviceOperation; - } - - @Override - protected ComponentOperation getCompInstOriginComponentOperation() { - return resourceOperation; - } - @Override protected ComponentTypeEnum getComponentTypeOfComponentInstance() { return ComponentTypeEnum.RESOURCE_INSTANCE; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java index 3e42897c79..61a5af5b74 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java @@ -25,7 +25,6 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.operations.impl.ComponentOperation; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -54,16 +53,6 @@ public class VFComponentInstanceBusinessLogic extends ComponentInstanceBusinessL return NodeTypeEnum.Resource; } - @Override - protected ComponentOperation getContainerComponentOperation() { - return resourceOperation; - } - - @Override - protected ComponentOperation getCompInstOriginComponentOperation() { - return resourceOperation; - } - @Override protected ComponentTypeEnum getComponentTypeOfComponentInstance() { return ComponentTypeEnum.RESOURCE_INSTANCE; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java index 445b3a9750..0e0f6f9464 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java @@ -21,27 +21,25 @@ package org.openecomp.sdc.be.components.lifecycle; import java.util.Arrays; -import java.util.List; - import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.user.Role; -import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -57,8 +55,8 @@ public class CertificationChangeTransition extends LifeCycleTransition { private AuditingActionEnum auditingAction; private ArtifactsBusinessLogic artifactsManager; - public CertificationChangeTransition(LifeCycleTransitionEnum name, ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation) { - super(componentUtils, lifecycleOperation); + public CertificationChangeTransition(LifeCycleTransitionEnum name, ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); this.name = name; @@ -67,7 +65,11 @@ public class CertificationChangeTransition extends LifeCycleTransition { addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(certificationChangeRoles)); addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(certificationChangeRoles)); // TODO to be later defined for product - + + //additional authorized roles for resource type + Role[] resourceRoles = { Role.DESIGNER}; + addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles)); + switch (this.name) { case CERTIFY: this.auditingAction = AuditingActionEnum.CERTIFICATION_SUCCESS_RESOURCE; @@ -106,7 +108,6 @@ public class CertificationChangeTransition extends LifeCycleTransition { } private ResponseFormat formatCertificationError(Component component, StorageOperationStatus response, ComponentTypeEnum componentType) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Change LifecycleState - Certify failed on graph"); BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Certify failed on graph"); log.debug("certification change failed on graph"); @@ -118,20 +119,24 @@ public class CertificationChangeTransition extends LifeCycleTransition { @Override public Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - log.debug("validate before certification change. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); + log.info("validate before certification change. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); // validate user - Either userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo); - if (userValidationResponse.isRight()) { + Either userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); + if (userValidationResponse.isRight()) { + log.error("userRoleValidation failed"); return userValidationResponse; } if (!oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) { + log.error("oldState={} should be={}",oldState,ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION); ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase()); - return Either.right(error); + return Either.right(error); } if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { + log.error("oldState={} should not be={}",oldState,ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE); + log.error("&& modifier({})!={} && modifier.role({})!={}",modifier,owner); ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); return Either.right(error); } @@ -144,14 +149,13 @@ public class CertificationChangeTransition extends LifeCycleTransition { log.info("start performing certification change for resource {}", component.getUniqueId()); Either result = null; - NodeTypeEnum nodeType = componentType.getNodeType(); try { - Either certificationChangeResult = Either.right(StorageOperationStatus.GENERAL_ERROR); + Either certificationChangeResult = Either.right(StorageOperationStatus.GENERAL_ERROR); if (nextState.equals(LifecycleStateEnum.CERTIFIED)) { - certificationChangeResult = lifeCycleOperation.certifyComponent(nodeType, component, modifier, owner, true); + certificationChangeResult = lifeCycleOperation.certifyToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); } else { - certificationChangeResult = lifeCycleOperation.cancelOrFailCertification(nodeType, component, modifier, owner, nextState, true); + certificationChangeResult = lifeCycleOperation.cancelOrFailCertification(component.getUniqueId(), modifier.getUserId(), owner.getUserId(), nextState); } if (certificationChangeResult.isRight()) { @@ -159,51 +163,32 @@ public class CertificationChangeTransition extends LifeCycleTransition { result = Either.right(responseFormat); return result; } - + if (nextState.equals(LifecycleStateEnum.CERTIFIED)) { - Either deleteOldComponentVersions = lifeCycleOperation.deleteOldComponentVersions(nodeType, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), - component.getComponentMetadataDefinition().getMetadataDataDefinition().getUUID(), true); + Either deleteOldComponentVersions = lifeCycleOperation.deleteOldToscaElementVersions(ModelConverter.getVertexType(component), componentType, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), + component.getComponentMetadataDefinition().getMetadataDataDefinition().getUUID()); if (deleteOldComponentVersions.isRight()) { ResponseFormat responseFormat = formatCertificationError(component, deleteOldComponentVersions.right().value(), componentType); result = Either.right(responseFormat); - return result; } } - result = Either.left(certificationChangeResult.left().value()); + result = Either.left(ModelConverter.convertFromToscaElement(certificationChangeResult.left().value())); return result; } finally { if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Change LifecycleState"); BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); if (inTransaction == false) { log.debug("operation failed. do rollback"); - lifeCycleOperation.getResourceOperation().getTitanGenericDao().rollback(); + titanDao.rollback(); } } else { if (inTransaction == false) { log.debug("operation success. do commit"); - lifeCycleOperation.getResourceOperation().getTitanGenericDao().commit(); + titanDao.commit(); } } } } - - public StorageOperationStatus deleteOldVersion(List artifactsToDelete, Resource resourceToDelete) { - ResourceOperation resourceOperation = lifeCycleOperation.getResourceOperation(); - - Either, StorageOperationStatus> artifactsRes = resourceOperation.getComponentArtifactsForDelete(resourceToDelete.getUniqueId(), NodeTypeEnum.Resource, true); - if (artifactsRes.isRight()) { - return artifactsRes.right().value(); - } - Either deleteResourceRes = resourceOperation.deleteResource(resourceToDelete.getUniqueId(), true); - if (deleteResourceRes.isRight()) { - return deleteResourceRes.right().value(); - } - artifactsToDelete.addAll(artifactsRes.left().value()); - - return StorageOperationStatus.OK; - } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java index 69a9cbdb24..042af54383 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java @@ -29,10 +29,14 @@ import java.util.Map.Entry; import java.util.Optional; import java.util.Set; +import org.apache.commons.codec.binary.Base64; import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; @@ -50,13 +54,20 @@ import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation; import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.tosca.ToscaError; import org.openecomp.sdc.be.tosca.ToscaExportHandler; +import org.openecomp.sdc.be.tosca.ToscaRepresentation; import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; @@ -68,15 +79,11 @@ public class CertificationRequestTransition extends LifeCycleTransition { private static Logger log = LoggerFactory.getLogger(CertificationRequestTransition.class.getName()); - private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder; - private ResourceOperation resourceOperation; private CapabilityOperation capabilityOperation; private ServiceBusinessLogic serviceBusinessLogic; - private ToscaExportHandler toscaExportUtils; - - public CertificationRequestTransition(ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation, ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder, ServiceBusinessLogic serviceBusinessLogic, - CapabilityOperation capabilityOperation, ToscaExportHandler toscaExportUtils) { - super(componentUtils, lifecycleOperation); + public CertificationRequestTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder, ServiceBusinessLogic serviceBusinessLogic, + CapabilityOperation capabilityOperation, ToscaExportHandler toscaExportUtils, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); // authorized roles Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; @@ -87,13 +94,13 @@ public class CertificationRequestTransition extends LifeCycleTransition { // TODO to be later defined for product // addAuthorizedRoles(ComponentTypeEnum.PRODUCT, // Arrays.asList(productCheckoutRoles)); + + //additional authorized roles for resource type + Role[] resourceRoles = { Role.TESTER}; + addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles)); - this.serviceDistributionArtifactsBuilder = serviceDistributionArtifactsBuilder; - if (lifeCycleOperation != null) - this.resourceOperation = lifeCycleOperation.getResourceOperation(); this.serviceBusinessLogic = serviceBusinessLogic; this.capabilityOperation = capabilityOperation; - this.toscaExportUtils = toscaExportUtils; } @Override @@ -125,7 +132,7 @@ public class CertificationRequestTransition extends LifeCycleTransition { private ResponseFormat getRelevantResponseFormatUncertifiedRI(ComponentInstance nonCertifiedRI, ComponentTypeEnum componentType) { ResponseFormat responseFormat; - Either eitherResource = resourceOperation.getResource(nonCertifiedRI.getComponentUid()); + Either eitherResource = toscaOperationFacade.getToscaElement(nonCertifiedRI.getComponentUid()); if (eitherResource.isRight()) { responseFormat = componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); @@ -133,16 +140,16 @@ public class CertificationRequestTransition extends LifeCycleTransition { } else { ActionStatus actionStatus; Resource resource = eitherResource.left().value(); - Either, StorageOperationStatus> status = resourceOperation.findLastCertifiedResourceByUUID(resource); + Either status = toscaOperationFacade.findLastCertifiedToscaElementByUUID(resource); if (ValidationUtils.validateMinorVersion(nonCertifiedRI.getComponentVersion())) { - if (status.isRight() || status.left().value() == null || status.left().value().isEmpty()) { + if (status.isRight() || status.left().value() == null) { actionStatus = ActionStatus.VALIDATED_RESOURCE_NOT_FOUND; } else { actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE; } } else { - if (status.isRight() || status.left().value() == null || status.left().value().isEmpty()) + if (status.isRight() || status.left().value() == null) actionStatus = ActionStatus.FOUND_LIST_VALIDATED_RESOURCES; else { actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE; @@ -157,23 +164,23 @@ public class CertificationRequestTransition extends LifeCycleTransition { private Either> validateMandatoryArtifactsSupplied(Map artifacts) { - if (artifacts == null || true == artifacts.isEmpty()) { + if (artifacts == null || artifacts.isEmpty()) { return Either.left(ActionStatus.OK); } - Map invalidArtifacts = new HashMap(); + Map invalidArtifacts = new HashMap<>(); for (Entry artifact : artifacts.entrySet()) { ArtifactDefinition artifactDefinition = artifact.getValue(); - if (true == artifactDefinition.getMandatory()) { + if (artifactDefinition.getMandatory()) { String artifactEsId = artifactDefinition.getEsId(); - if (artifactEsId == null || true == artifactEsId.isEmpty()) { + if (artifactEsId == null || artifactEsId.isEmpty()) { invalidArtifacts.put(artifact.getKey(), artifactDefinition); } } } - if (true == invalidArtifacts.isEmpty()) { + if (invalidArtifacts.isEmpty()) { return Either.left(ActionStatus.OK); } else { return Either.right(invalidArtifacts); @@ -185,81 +192,73 @@ public class CertificationRequestTransition extends LifeCycleTransition { log.debug("start performing certification request for resource {}", component.getUniqueId()); - // Either> - // validateMandatoryArtifacts = - // validateMandatoryArtifactsSupplied(component.getArtifacts()); - // log.debug("After checking mandatory artifacts were populated. Result - // is " + validateMandatoryArtifacts); - // if (validateMandatoryArtifacts.isRight()) { - // ResponseFormat responseFormat = componentUtils - // .getResponseFormatByMissingArtifacts( - // componentType, - // validateMandatoryArtifacts.right().value()); - // return Either.right(responseFormat); - // } - ActionStatus actionStatus = null; - ResponseFormat responseFormat = null; - - if (componentType == ComponentTypeEnum.SERVICE || (componentType == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() == ResourceTypeEnum.VF)) { - - Either statusCert = validateAllResourceInstanceCertified(component); - if (statusCert.isRight()) { - return Either.right(statusCert.right().value()); - } - - statusCert = validateConfiguredAtomicReqCapSatisfied(component); - if (statusCert.isRight()) { - return Either.right(statusCert.right().value()); + ActionStatus actionStatus; + ResponseFormat responseFormat; + Either result = null; + try{ + if (componentType == ComponentTypeEnum.SERVICE || (componentType == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() == ResourceTypeEnum.VF)) { + + Either statusCert = validateAllResourceInstanceCertified(component); + if (statusCert.isRight()) { + return Either.right(statusCert.right().value()); + } + + statusCert = validateConfiguredAtomicReqCapSatisfied(component); + if (statusCert.isRight()) { + return Either.right(statusCert.right().value()); + } } - } - if (componentType == ComponentTypeEnum.SERVICE) { - Either status = validateDeloymentArtifactSupplied((Service) component); - if (status.isRight()) { - StorageOperationStatus operationStatus = status.right().value(); - actionStatus = componentUtils.convertFromStorageResponse(operationStatus); - } else { - Boolean isDeploymentArtifactExists = status.left().value(); - if (isDeploymentArtifactExists == null || isDeploymentArtifactExists.booleanValue() == false) { - actionStatus = ActionStatus.SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND; - } else { - Either generateHeatEnvResult = serviceBusinessLogic.generateHeatEnvArtifacts((Service) component, modifier, shouldLock); - if (generateHeatEnvResult.isRight()) { + if (componentType == ComponentTypeEnum.SERVICE) { + + Either generateHeatEnvResult = serviceBusinessLogic.generateHeatEnvArtifacts((Service) component, modifier, shouldLock); + + if (generateHeatEnvResult.isRight()) { return Either.right(generateHeatEnvResult.right().value()); } - Either generateVfModuleResult = serviceBusinessLogic.generateVfModuleArtifacts((Service) component, modifier, shouldLock); - if (generateVfModuleResult.isRight()) { + Either generateVfModuleResult = serviceBusinessLogic.generateVfModuleArtifacts((Service) component, modifier, shouldLock); + if (generateVfModuleResult.isRight()) { return Either.right(generateVfModuleResult.right().value()); - } } } - - if (actionStatus != null) { + + Either, ResponseFormat> eitherPopulated = componentBl.populateToscaArtifacts(component, modifier, true, inTransaction, shouldLock); + if (eitherPopulated != null && eitherPopulated.isRight()) { + return Either.right(eitherPopulated.right().value()); + } + + NodeTypeEnum nodeType = componentType.equals(ComponentTypeEnum.SERVICE) ? NodeTypeEnum.Service : NodeTypeEnum.Resource; + + + Either certificationRequestResult = lifeCycleOperation.requestCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); + if (certificationRequestResult.isRight()) { + log.debug("checkout failed on graph"); + StorageOperationStatus response = certificationRequestResult.right().value(); + actionStatus = componentUtils.convertFromStorageResponse(response); + + if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { + actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; + } responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - return Either.right(responseFormat); + result = Either.right(responseFormat); } - - } - - Either, ResponseFormat> eitherPopulated = componentBl.populateToscaArtifacts(component, modifier, true, inTransaction, shouldLock); - if (eitherPopulated != null && eitherPopulated.isRight()) { - return Either.right(eitherPopulated.right().value()); - } - - NodeTypeEnum nodeType = (componentType.equals(ComponentTypeEnum.SERVICE)) ? NodeTypeEnum.Service : NodeTypeEnum.Resource; - Either certificationRequestResult = lifeCycleOperation.requestCertificationComponent(nodeType, component, modifier, owner, inTransaction); - if (certificationRequestResult.isRight()) { - log.debug("checkout failed on graph"); - StorageOperationStatus response = certificationRequestResult.right().value(); - actionStatus = componentUtils.convertFromStorageResponse(response); - - if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { - actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; + else { + result = Either.left(ModelConverter.convertFromToscaElement(certificationRequestResult.left().value())); + } + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); + if (inTransaction == false) { + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } + } else { + if (inTransaction == false) { + log.debug("operation success. do commit"); + titanDao.commit(); } - responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - return Either.right(responseFormat); } - - return Either.left(certificationRequestResult.left().value()); + } + return result; } private Either validateConfiguredAtomicReqCapSatisfied(Component component) { @@ -369,7 +368,7 @@ public class CertificationRequestTransition extends LifeCycleTransition { log.debug("validate before certification request. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); // validate user - Either userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo); + Either userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); if (userValidationResponse.isRight()) { return userValidationResponse; } @@ -397,13 +396,4 @@ public class CertificationRequestTransition extends LifeCycleTransition { return Either.left(true); } - - private Either validateDeloymentArtifactSupplied(Service service) { - - Either serviceContainsDeploymentArtifacts = this.serviceDistributionArtifactsBuilder.isServiceContainsDeploymentArtifacts(service); - - return serviceContainsDeploymentArtifacts; - - } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java index 28227285f1..bfe51ded48 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java @@ -23,15 +23,19 @@ package org.openecomp.sdc.be.components.lifecycle; import java.util.Arrays; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; +import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.user.Role; @@ -45,8 +49,8 @@ public class CheckinTransition extends LifeCycleTransition { private static Logger log = LoggerFactory.getLogger(CheckinTransition.class.getName()); - public CheckinTransition(ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation) { - super(componentUtils, lifecycleOperation); + public CheckinTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); // authorized roles Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; @@ -71,21 +75,40 @@ public class CheckinTransition extends LifeCycleTransition { public Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { log.debug("start performing checkin for {} {}", componentType.name(), component.getUniqueId()); - NodeTypeEnum nodeType = componentType.getNodeType(); - Either checkinResourceResult = lifeCycleOperation.checkinComponent(nodeType, component, modifier, owner, inTransaction); - if (checkinResourceResult.isRight()) { - log.debug("checkout failed on graph"); - StorageOperationStatus response = checkinResourceResult.right().value(); - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); - - if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { - actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; + Either result = null; + try{ + Either checkinResourceResult = lifeCycleOperation. + checkinToscaELement(component.getLifecycleState(), component.getUniqueId(), modifier.getUserId(), owner.getUserId()); + + if (checkinResourceResult.isRight()) { + log.debug("checkout failed on graph"); + StorageOperationStatus response = checkinResourceResult.right().value(); + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); + + if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { + actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; + } + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + result = Either.right(responseFormat); + } + else { + result = Either.left(ModelConverter.convertFromToscaElement(checkinResourceResult.left().value())); + } + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); + if (inTransaction == false) { + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } + } else { + if (inTransaction == false) { + log.debug("operation success. do commit"); + titanDao.commit(); + } } - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - return Either.right(responseFormat); } - - return Either.left(checkinResourceResult.left().value()); + return result; } @Override @@ -94,13 +117,19 @@ public class CheckinTransition extends LifeCycleTransition { log.debug("validate before checkin. component name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); // validate user - Either userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo); + Either userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); if (userValidationResponse.isRight()) { return userValidationResponse; } if (!oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION) && !oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CHECKED_IN, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + ActionStatus action = ActionStatus.COMPONENT_ALREADY_CHECKED_IN; + if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)){ + action = ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION; + } else if (oldState.equals(LifecycleStateEnum.CERTIFIED)){ + action = ActionStatus.COMPONENT_ALREADY_CERTIFIED; + } + ResponseFormat error = componentUtils.getResponseFormat(action, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); return Either.right(error); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java index a4e6bdb86c..d6cbd3663c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java @@ -21,17 +21,26 @@ package org.openecomp.sdc.be.components.lifecycle; import java.util.Arrays; +import java.util.List; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; +import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.user.Role; @@ -43,12 +52,10 @@ import fj.data.Either; public class CheckoutTransition extends LifeCycleTransition { - private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes"; - private static Logger log = LoggerFactory.getLogger(CheckoutTransition.class.getName()); - public CheckoutTransition(ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation) { - super(componentUtils, lifecycleOperation); + public CheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); // authorized roles Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; @@ -74,24 +81,66 @@ public class CheckoutTransition extends LifeCycleTransition { log.debug("start performing {} for resource {}", getName().name(), component.getUniqueId()); - if (componentBl != null) - componentBl.setDeploymentArtifactsPlaceHolder(component, modifier); - NodeTypeEnum nodeType = componentType.getNodeType(); - Either checkoutResourceResult = lifeCycleOperation.checkoutComponent(nodeType, component, modifier, owner, inTransaction); + Either result = null; + try { + + Either checkoutResourceResult = lifeCycleOperation.checkoutToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); + + if (checkoutResourceResult.isRight()) { + log.debug("checkout failed on graph"); + StorageOperationStatus response = checkoutResourceResult.right().value(); + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); + + if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { + actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; + } + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + result = Either.right(responseFormat); + } else { + Component clonedComponent = ModelConverter.convertFromToscaElement(checkoutResourceResult.left().value()); + result = Either.left(clonedComponent); + Either upgradeToLatestGeneric = componentBl.shouldUpgradeToLatestGeneric(clonedComponent); + if (upgradeToLatestGeneric.isRight()) + result = Either.right(upgradeToLatestGeneric.right().value()); + else if (upgradeToLatestGeneric.left().value()) { + StorageOperationStatus response = upgradeToLatestGenericData(clonedComponent); + if (StorageOperationStatus.OK != response) { + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + result = Either.right(responseFormat); + } + } - if (checkoutResourceResult.isRight()) { - log.debug("checkout failed on graph"); - StorageOperationStatus response = checkoutResourceResult.right().value(); - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); + } - if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { - actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); + if (inTransaction == false) { + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } + } else { + if (inTransaction == false) { + log.debug("operation success. do commit"); + titanDao.commit(); + } } - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - return Either.right(responseFormat); } + return result; + } - return Either.left(checkoutResourceResult.left().value()); + private StorageOperationStatus upgradeToLatestGenericData(Component clonedComponent) { + + StorageOperationStatus updateStatus = null; + Either updateEither = toscaOperationFacade.updateToscaElement(clonedComponent); + if (updateEither.isRight()) + updateStatus = updateEither.right().value(); + else if (clonedComponent.shouldGenerateInputs()) { + List newInputs = clonedComponent.getInputs(); + updateStatus = lifeCycleOperation.updateToscaDataOfToscaElement(clonedComponent.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputs, JsonPresentationFields.NAME); + } + return updateStatus; } @Override @@ -100,7 +149,7 @@ public class CheckoutTransition extends LifeCycleTransition { log.debug("validate before checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); // validate user - Either userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo); + Either userValidationResponse = userRoleValidation(modifier, component, componentType, lifecycleChangeInfo); if (userValidationResponse.isRight()) { return userValidationResponse; } @@ -131,11 +180,4 @@ public class CheckoutTransition extends LifeCycleTransition { return Either.left(true); } - /* - * private Either productContactsValidation(Product product, User modifier) { // validate user Either eitherResponse = Either.left(true); String role = modifier.getRole(); if - * (UserRoleEnum.PRODUCT_MANAGER.getName().equals(role) || UserRoleEnum.PRODUCT_STRATEGIST.getName().equals(role)){ String userId = modifier.getUserId(); if (!product.getContacts().contains(userId)){ log. - * debug("User with userId {} cannot checkout product. userId not found in product contacts list" , userId); ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); return Either.right(responseFormat); - * } else { log. trace("Found user userId {} in product contacts - checkout request validated" ); } } return eitherResponse; } - */ - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java index 49d94dc80b..0d0e06fe6d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java @@ -24,44 +24,53 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.beans.factory.annotation.Autowired; import fj.data.Either; public abstract class LifeCycleTransition { protected ConfigurationManager configurationManager; - protected ILifecycleOperation lifeCycleOperation; + @Autowired + protected ToscaElementLifecycleOperation lifeCycleOperation; + @Autowired + protected TitanDao titanDao; protected ComponentsUtils componentUtils; protected Map> authorizedRoles; + protected Map> resourceAuthorizedRoles; + + ToscaOperationFacade toscaOperationFacade; - protected LifeCycleTransition(ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation) { + protected LifeCycleTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation2, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - // configurationManager = (ConfigurationManager) - // context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR); - // lifeCycleOperation = LifecycleOperation.getInstance(); this.configurationManager = ConfigurationManager.getConfigurationManager(); - this.lifeCycleOperation = lifecycleOperation; + this.lifeCycleOperation = lifecycleOperation2; this.componentUtils = componentUtils; this.authorizedRoles = new HashMap<>(); - + this.resourceAuthorizedRoles = new HashMap<>(); + this.toscaOperationFacade = toscaOperationFacade; + this.titanDao = titanDao; } public abstract LifeCycleTransitionEnum getName(); @@ -76,11 +85,11 @@ public abstract class LifeCycleTransition { this.configurationManager = configurationManager; } - public ILifecycleOperation getLifeCycleOperation() { + public ToscaElementLifecycleOperation getLifeCycleOperation() { return lifeCycleOperation; } - public void setLifeCycleOperation(ILifecycleOperation lifeCycleOperation) { + public void setLifeCycleOperation(ToscaElementLifecycleOperation lifeCycleOperation) { this.lifeCycleOperation = lifeCycleOperation; } @@ -91,14 +100,14 @@ public abstract class LifeCycleTransition { public void addAuthorizedRoles(ComponentTypeEnum componentType, List authorizedRoles) { this.authorizedRoles.put(componentType, authorizedRoles); } + + public List getResourceAuthorizedRoles(ResourceTypeEnum resourceType) { + return resourceAuthorizedRoles.get(resourceType); + } - // - // public Either - // changeState(ComponentTypeEnum componentType, Component component, - // ComponentBusinessLogic componentBl, User modifier, User owner){ - // return changeState(componentType, component, componentBl, modifier, - // owner, false); - // } + public void addResouceAuthorizedRoles(ResourceTypeEnum resourceType, List authorizedRoles) { + this.resourceAuthorizedRoles.put(resourceType, authorizedRoles); + } public abstract Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean needLock, boolean inTransaction); @@ -122,8 +131,7 @@ public abstract class LifeCycleTransition { protected Either getComponentOwner(Component component, ComponentTypeEnum componentType, boolean inTransaction) { - NodeTypeEnum nodeType = componentType.getNodeType(); - Either resourceOwnerResult = getLifeCycleOperation().getComponentOwner(component.getUniqueId(), nodeType, inTransaction); + Either resourceOwnerResult = getLifeCycleOperation().getToscaElementOwner(component.getUniqueId()); if (resourceOwnerResult.isRight()) { ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(componentUtils.convertFromStorageResponse(resourceOwnerResult.right().value()), component, componentType); return Either.right(responseFormat); @@ -131,21 +139,13 @@ public abstract class LifeCycleTransition { return Either.left(resourceOwnerResult.left().value()); } - /** - * isUserValidForRequest - * - * @param modifier - * @param action - * TODO - * @return - */ - protected Either userRoleValidation(User modifier, ComponentTypeEnum componentType, LifecycleChangeInfoWithAction lifecycleChangeInfo) { + protected Either userRoleValidation(User modifier,Component component, ComponentTypeEnum componentType, LifecycleChangeInfoWithAction lifecycleChangeInfo) { // validate user - if (getAuthorizedRoles(componentType).contains(Role.valueOf(modifier.getRole()))) { + //first check the user for the component and then for the resource + if (getAuthorizedRoles(componentType).contains(Role.valueOf(modifier.getRole())) || userResourceRoleValidation(component,componentType,modifier)) { return Either.left(true); } - // this is only when creating vfc/cp when import vf from csar - when we // create resources from node type, we create need to change the state // to certified @@ -156,5 +156,18 @@ public abstract class LifeCycleTransition { ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); return Either.right(responseFormat); } + + protected boolean userResourceRoleValidation(Component component, ComponentTypeEnum componentType, User modifier) { + if (componentType.equals(ComponentTypeEnum.RESOURCE)){ + ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition)component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); + if (getResourceAuthorizedRoles(resourceType)!=null && getResourceAuthorizedRoles(resourceType).contains(Role.valueOf(modifier.getRole()))) { + return true; + } + } else { + return false; + } + + return false; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java index 27709bb332..8e89a6bf31 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java @@ -34,8 +34,11 @@ import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; @@ -43,14 +46,13 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; -import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation; -import org.openecomp.sdc.be.model.operations.impl.ProductOperation; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; -import org.openecomp.sdc.be.model.operations.impl.ServiceOperation; +import org.openecomp.sdc.be.model.operations.impl.ComponentOperation; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.tosca.ToscaExportHandler; import org.openecomp.sdc.common.api.Constants; @@ -76,13 +78,7 @@ public class LifecycleBusinessLogic { private ArtifactsBusinessLogic artifactsBusinessLogic; @Autowired - private ResourceOperation resourceOperation; - - @Autowired - private ServiceOperation serviceOperation; - - @Autowired - private ProductOperation productOperation; + private TitanDao titanDao; @Autowired private CapabilityOperation capabilityOperation; @@ -93,7 +89,7 @@ public class LifecycleBusinessLogic { private ComponentsUtils componentUtils; @javax.annotation.Resource - private ILifecycleOperation lifecycleOperation; + private ToscaElementLifecycleOperation lifecycleOperation; @javax.annotation.Resource ArtifactsBusinessLogic artifactsManager; @@ -114,6 +110,9 @@ public class LifecycleBusinessLogic { @Autowired ICacheMangerOperation cacheManagerOperation; + + @Autowired + ToscaOperationFacade toscaOperationFacade; private Map stateTransitions; private static volatile boolean isInitialized = false; @@ -134,29 +133,29 @@ public class LifecycleBusinessLogic { private void initStateOperations() { stateTransitions = new HashMap(); - LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation); + LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); stateTransitions.put(checkoutOp.getName().name(), checkoutOp); - UndoCheckoutTransition undoCheckoutOp = new UndoCheckoutTransition(componentUtils, lifecycleOperation); + UndoCheckoutTransition undoCheckoutOp = new UndoCheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); undoCheckoutOp.setArtifactsBusinessLogic(artifactsBusinessLogic); stateTransitions.put(undoCheckoutOp.getName().name(), undoCheckoutOp); - LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation); + LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); stateTransitions.put(checkinOp.getName().name(), checkinOp); - LifeCycleTransition certificationRequest = new CertificationRequestTransition(componentUtils, lifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils); + LifeCycleTransition certificationRequest = new CertificationRequestTransition(componentUtils, lifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao); stateTransitions.put(certificationRequest.getName().name(), certificationRequest); - LifeCycleTransition startCertification = new StartCertificationTransition(componentUtils, lifecycleOperation); + LifeCycleTransition startCertification = new StartCertificationTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); stateTransitions.put(startCertification.getName().name(), startCertification); - LifeCycleTransition failCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.FAIL_CERTIFICATION, componentUtils, lifecycleOperation); + LifeCycleTransition failCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.FAIL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); stateTransitions.put(failCertification.getName().name(), failCertification); - LifeCycleTransition cancelCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CANCEL_CERTIFICATION, componentUtils, lifecycleOperation); + LifeCycleTransition cancelCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CANCEL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); stateTransitions.put(cancelCertification.getName().name(), cancelCertification); - CertificationChangeTransition successCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentUtils, lifecycleOperation); + CertificationChangeTransition successCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); successCertification.setArtifactsManager(artifactsBusinessLogic); stateTransitions.put(successCertification.getName().name(), successCertification); } @@ -172,132 +171,16 @@ public class LifecycleBusinessLogic { // TODO: rhalili - should use changeComponentState when possible public Either changeState(String resourceId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) { return (Either) changeComponentState(ComponentTypeEnum.RESOURCE, resourceId, modifier, transitionEnum, changeInfo, inTransaction, needLock); - - // LifeCycleTransition lifeCycleTransition = - // stateTransitions.get(transitionEnum.name()); - // if (lifeCycleTransition == null) { - // log.debug("state operation is not valid. operations allowed are: {}", - // LifeCycleTransitionEnum.valuesAsString()); - // ResponseFormat error = - // componentUtils.getInvalidContentErrorAndAudit(modifier, - // AuditingActionEnum.CHECKOUT_RESOURCE); - // return Either.right(error); - // } - // - // Either operationResult; - // Resource resource = null; - // boolean needToUnlockResource = false; - // - // log.debug("get resource from graph"); - // ResponseFormat errorResponse; - // Either eitherResourceResponse = - // getResourceForChange(resourceId, modifier, lifeCycleTransition); - // if (eitherResourceResponse.isRight()) { - // return eitherResourceResponse; - // } - // resource = eitherResourceResponse.left().value(); - // String resourceCurrVersion = resource.getResourceVersion(); - // LifecycleStateEnum resourceCurrState = resource.getLifecycleState(); - // - // if (inTransaction == false) { - // // lock resource - // Either eitherLockResource = - // lockResource(resource); - // if (eitherLockResource.isRight()) { - // errorResponse = eitherLockResource.right().value(); - // componentUtils.auditResource(errorResponse, modifier, resource, - // resourceCurrState.name(), resourceCurrVersion, - // lifeCycleTransition.getAuditingAction(), null); - // return Either.right(errorResponse); - // } - // needToUnlockResource = true; - // } - // - // try { - // Either resourceNotDeleted = - // validateResourceNotDeleted(modifier, lifeCycleTransition, resource, - // resourceCurrVersion); - // if (resourceNotDeleted.isRight()) { - // return Either.right(resourceNotDeleted.right().value()); - // } - // - // Either validateHighestVersion = - // validateHighestVersion(modifier, lifeCycleTransition, resource, - // resourceCurrVersion); - // if (validateHighestVersion.isRight()) { - // return Either.right(validateHighestVersion.right().value()); - // } - // - // Either ownerResult = - // lifeCycleTransition.getResourceOwner(resource); - // if (ownerResult.isRight()) { - // return Either.right(ownerResult.right().value()); - // } - // User owner = ownerResult.left().value(); - // log.debug("owner of resource {} is {}", resource.getUniqueId(), - // owner.getUserId()); - // - // LifecycleStateEnum oldState = resource.getLifecycleState(); - // - // Either commentValidationResult = - // validateComment(changeInfo, transitionEnum); - // if (commentValidationResult.isRight()) { - // errorResponse = commentValidationResult.right().value(); - // EnumMap auditingFields = new - // EnumMap(AuditingFieldsKeysEnum.class); - // auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, - // changeInfo.getUserRemarks()); - // componentUtils.auditResource(errorResponse, modifier, resource, - // resourceCurrState.name(), resourceCurrVersion, - // lifeCycleTransition.getAuditingAction(), auditingFields); - // return Either.right(errorResponse); - // } - // changeInfo.setUserRemarks(commentValidationResult.left().value()); - // - // Either stateValidationResult = - // lifeCycleTransition.validateResourceBeforeTransition(resource.getResourceName(), - // ComponentTypeEnum.RESOURCE, modifier, owner, oldState); - // if (stateValidationResult.isRight()) { - // errorResponse = stateValidationResult.right().value(); - // componentUtils.auditResource(errorResponse, modifier, resource, - // resourceCurrState.name(), resourceCurrVersion, - // lifeCycleTransition.getAuditingAction(), null); - // return Either.right(errorResponse); - // } - // - // operationResult = lifeCycleTransition.changeStateOperation(resource, - // modifier, owner, inTransaction); - // - // if (operationResult.isRight()) { - // errorResponse = operationResult.right().value(); - // log.debug("audit before sending response"); - // componentUtils.auditResource(errorResponse, modifier, resource, - // resourceCurrState.name(), resourceCurrVersion, - // lifeCycleTransition.getAuditingAction(), null); - // - // return Either.right(errorResponse); - // } - // Resource resourceAfterOperation = operationResult.left().value(); - // EnumMap auditingFields = new - // EnumMap(AuditingFieldsKeysEnum.class); - // auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, - // changeInfo.getUserRemarks()); - // componentUtils.auditResource(componentUtils.getResponseFormat(ActionStatus.OK), - // modifier, resourceAfterOperation, resourceCurrState.name(), - // resourceCurrVersion, lifeCycleTransition.getAuditingAction(), - // auditingFields); - // return operationResult; - // - // } finally { - // log.debug("unlock resource {}", resourceId); - // if (needToUnlockResource && resource != null) { - // resource.setUniqueId(resourceId); - // graphLockOperation.unlockResource(resource); - // } - // } - + } + + private boolean isComponentVFCMT(Component component, ComponentTypeEnum componentType){ + if (componentType.equals(ComponentTypeEnum.RESOURCE)){ + ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition)component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); + if (resourceType.equals(ResourceTypeEnum.VFCMT)){ + return true; + } + } + return false; } public Either changeComponentState(ComponentTypeEnum componentType, String componentId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, @@ -309,12 +192,8 @@ public class LifecycleBusinessLogic { ResponseFormat error = componentUtils.getInvalidContentErrorAndAudit(modifier, AuditingActionEnum.CHECKOUT_RESOURCE); return Either.right(error); } - ComponentBusinessLogic bl = getComponentBL(componentType); - - Either operationResult = null; Component component = null; - // boolean needToUnlockResource = false; - log.debug("get resource from graph"); + log.info("get resource from graph"); ResponseFormat errorResponse; Either eitherResourceResponse = getComponentForChange(componentType, componentId, modifier, lifeCycleTransition, changeInfo); @@ -325,110 +204,133 @@ public class LifecycleBusinessLogic { String resourceCurrVersion = component.getVersion(); LifecycleStateEnum resourceCurrState = component.getLifecycleState(); + log.info("lock component {}", componentId); // lock resource if (inTransaction == false && needLock) { Either eitherLockResource = lockComponent(componentType, component); if (eitherLockResource.isRight()) { errorResponse = eitherLockResource.right().value(); componentUtils.auditComponent(errorResponse, modifier, component, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, null); + log.error("lock component {} failed", componentId); return Either.right(errorResponse); } - // needToUnlockResource = true; } + log.info("after lock component {}", componentId); try { Either commentValidationResult = validateComment(changeInfo, transitionEnum); if (commentValidationResult.isRight()) { errorResponse = commentValidationResult.right().value(); - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks()); componentUtils.auditComponent(errorResponse, modifier, component, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields); return Either.right(errorResponse); } changeInfo.setUserRemarks(commentValidationResult.left().value()); - + log.info("after validate component"); Either validateHighestVersion = validateHighestVersion(modifier, lifeCycleTransition, component, resourceCurrVersion, componentType); if (validateHighestVersion.isRight()) { return Either.right(validateHighestVersion.right().value()); } - - Either ownerResult = lifeCycleTransition.getComponentOwner(component, componentType, inTransaction); - if (ownerResult.isRight()) { - return Either.right(ownerResult.right().value()); - } - User owner = ownerResult.left().value(); - log.debug("owner of resource {} is {}", component.getUniqueId(), owner.getUserId()); - - LifecycleStateEnum oldState = component.getLifecycleState(); - - Either stateValidationResult = lifeCycleTransition.validateBeforeTransition(component, componentType, modifier, owner, oldState, changeInfo); - if (stateValidationResult.isRight()) { - errorResponse = stateValidationResult.right().value(); - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks()); - componentUtils.auditComponent(errorResponse, modifier, component, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields); - return Either.right(errorResponse); - - } - - operationResult = lifeCycleTransition.changeState(componentType, component, bl, modifier, owner, false, inTransaction); - - if (operationResult.isRight()) { - errorResponse = operationResult.right().value(); - log.debug("audit before sending response"); - componentUtils.auditComponentAdmin(errorResponse, modifier, component, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType); - - return Either.right(errorResponse); + log.info("after validate Highest Version"); + if (isComponentVFCMT(component,componentType)){ + Either changeVFCMTStateResponse = changeVFCMTState(componentType, modifier, transitionEnum, changeInfo, inTransaction, component); + if (changeVFCMTStateResponse.isRight()){ + return changeVFCMTStateResponse; + } } - Component resourceAfterOperation = operationResult.left().value(); - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks()); - componentUtils.auditComponent(componentUtils.getResponseFormat(ActionStatus.OK), modifier, resourceAfterOperation, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields); - return operationResult; + return changeState(component, lifeCycleTransition, componentType, modifier, changeInfo, inTransaction); } finally { - log.debug("unlock component {}", componentId); + log.info("unlock component {}", componentId); if (inTransaction == false && needLock && component != null) { component.setUniqueId(componentId); NodeTypeEnum nodeType = componentType.getNodeType(); + log.info("During change state, another component {} has been created/updated", componentId); + graphLockOperation.unlockComponent(componentId, nodeType); - // Handle component change in the cache of the side affect of - // the operation - if (operationResult != null && operationResult.isLeft()) { - Component componentAfterOpertion = operationResult.left().value(); - String uniqueId = componentAfterOpertion.getUniqueId(); - if (false == componentId.equals(uniqueId)) { - log.debug("During change state, another component {} has been created/updated", uniqueId); - if (uniqueId != null) { - cacheManagerOperation.updateComponentInCache(uniqueId, componentAfterOpertion.getLastUpdateDate(), nodeType); - } - } - } + } + } - graphLockOperation.unlockComponent(componentId, nodeType); + } + /* + * special case for certification of VFCMT - VFCMT can be certified by Designer or Tester right after checkin + * in case the operation "submit for test" / "start testing" is done to "VFCMT" - please return error 400 + */ + private Either changeVFCMTState(ComponentTypeEnum componentType, User modifier, + LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, + Component component) { + LifecycleStateEnum oldState = component.getLifecycleState(); + if (transitionEnum.equals(LifeCycleTransitionEnum.START_CERTIFICATION) || + transitionEnum.equals(LifeCycleTransitionEnum.CERTIFICATION_REQUEST)){ + return Either.right(componentUtils.getResponseFormat( + ActionStatus.RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID, transitionEnum.getDisplayName())); + } //certify is done directly from checkin + else if (transitionEnum.equals(LifeCycleTransitionEnum.CERTIFY) && oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN)){ + //we will call for submit for testing first and then for certify + Either actionResponse = changeState(component, + stateTransitions.get(LifeCycleTransitionEnum.CERTIFICATION_REQUEST.name()), + componentType, modifier, changeInfo, inTransaction); + if (actionResponse.isRight()) { + return actionResponse; } + actionResponse = changeState(component, + stateTransitions.get(LifeCycleTransitionEnum.START_CERTIFICATION.name()), + componentType, modifier, changeInfo, inTransaction); + if (actionResponse.isRight()) { + return actionResponse; + } } + return Either.left(null); + } + + private Either changeState(Component component, LifeCycleTransition lifeCycleTransition, + ComponentTypeEnum componentType, User modifier, LifecycleChangeInfoWithAction changeInfo,boolean inTransaction){ + ResponseFormat errorResponse; + + LifecycleStateEnum oldState = component.getLifecycleState(); + String resourceCurrVersion = component.getVersion(); + ComponentBusinessLogic bl = getComponentBL(componentType); + + Either ownerResult = lifeCycleTransition.getComponentOwner(component, componentType, inTransaction); + if (ownerResult.isRight()) { + return Either.right(ownerResult.right().value()); + } + User owner = ownerResult.left().value(); + log.info("owner of resource {} is {}", component.getUniqueId(), owner.getUserId()); + + Either stateValidationResult = lifeCycleTransition.validateBeforeTransition(component, componentType, modifier, owner, oldState, changeInfo); + if (stateValidationResult.isRight()) { + log.error("Failed to validateBeforeTransition"); + errorResponse = stateValidationResult.right().value(); + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks()); + componentUtils.auditComponent(errorResponse, modifier, component, oldState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields); + return Either.right(errorResponse); + } + + Either operationResult = lifeCycleTransition.changeState(componentType, component, bl, modifier, owner, false, inTransaction); + + if (operationResult.isRight()) { + errorResponse = operationResult.right().value(); + log.info("audit before sending error response"); + componentUtils.auditComponentAdmin(errorResponse, modifier, component, oldState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType); + + return Either.right(errorResponse); + } + Component resourceAfterOperation = operationResult.left().value(); + EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks()); + componentUtils.auditComponent(componentUtils.getResponseFormat(ActionStatus.OK), modifier, resourceAfterOperation, oldState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields); + return operationResult; } private Either getComponentForChange(ComponentTypeEnum componentType, String componentId, User modifier, LifeCycleTransition lifeCycleTransition, LifecycleChangeInfoWithAction changeInfo) { - Either eitherResourceResponse = Either.right(StorageOperationStatus.GENERAL_ERROR); - switch (componentType) { - case SERVICE: - eitherResourceResponse = serviceOperation.getComponent(componentId, true); - break; - case PRODUCT: - eitherResourceResponse = productOperation.getComponent(componentId, true); - break; - case RESOURCE: - eitherResourceResponse = resourceOperation.getComponent(componentId, true); - break; - default: - break; - } + Either eitherResourceResponse = toscaOperationFacade.getToscaElement(componentId); - ResponseFormat errorResponse = null; + ResponseFormat errorResponse; if (eitherResourceResponse.isRight()) { ActionStatus actionStatus = componentUtils.convertFromStorageResponse(eitherResourceResponse.right().value(), componentType); errorResponse = componentUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); @@ -494,28 +396,6 @@ public class LifecycleBusinessLogic { } - private Either getResourceForChange(String resourceId, User modifier, LifeCycleTransition lifeCycleTransition) { - Either eitherResourceResponse = resourceOperation.getResource(resourceId, true); - - ResponseFormat errorResponse = null; - if (eitherResourceResponse.isRight()) { - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(eitherResourceResponse.right().value()); - errorResponse = componentUtils.getResponseFormatByResource(actionStatus, ""); - log.debug("audit before sending response"); - // For audit of not found, resourceName should be uniqueID according - // to Ella - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceId); - componentUtils.auditResource(errorResponse, modifier, null, "", "", lifeCycleTransition.getAuditingAction(), null); - - return Either.right(errorResponse); - } - Resource resource = eitherResourceResponse.left().value(); - - return Either.left(resource); - - } - private Either validateComment(LifecycleChangeInfoWithAction changeInfo, LifeCycleTransitionEnum transitionEnum) { String comment = changeInfo.getUserRemarks(); if (LifeCycleTransitionEnum.CANCEL_CERTIFICATION == transitionEnum || LifeCycleTransitionEnum.CERTIFY == transitionEnum || LifeCycleTransitionEnum.FAIL_CERTIFICATION == transitionEnum || LifeCycleTransitionEnum.CHECKIN == transitionEnum @@ -548,25 +428,39 @@ public class LifecycleBusinessLogic { private ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum) { ComponentBusinessLogic businessLogic; switch (componentTypeEnum) { - case RESOURCE: { - businessLogic = this.resourceBusinessLogic; - break; - } - case SERVICE: { - businessLogic = this.serviceBusinessLogic; - break; - } - case PRODUCT: { - businessLogic = this.productBusinessLogic; - break; - } - - default: { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "getComponentBL"); - throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue()); - } + case RESOURCE: { + businessLogic = this.resourceBusinessLogic; + break; + } + case SERVICE: { + businessLogic = this.serviceBusinessLogic; + break; + } + case PRODUCT: { + businessLogic = this.productBusinessLogic; + break; + } + + default: { + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "getComponentBL"); + throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue()); + } } return businessLogic; } + + public Either getLatestComponentByUuid(ComponentTypeEnum componentTypeEnum, String uuid) { + + Either latestVersionEither = toscaOperationFacade.getLatestComponentByUuid(uuid); + + if (latestVersionEither.isRight()) { + + return Either.right(componentUtils.getResponseFormat(componentUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentTypeEnum), uuid)); + } + + Component latestComponent = latestVersionEither.left().value(); + + return Either.left(latestComponent); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java index 918140b0af..8a80e0bb64 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java @@ -22,15 +22,23 @@ package org.openecomp.sdc.be.components.lifecycle; import java.util.Arrays; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; +import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -45,14 +53,18 @@ public class StartCertificationTransition extends LifeCycleTransition { private static Logger log = LoggerFactory.getLogger(StartCertificationTransition.class.getName()); - public StartCertificationTransition(ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation) { - super(componentUtils, lifecycleOperation); + public StartCertificationTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); // authorized roles Role[] rsrcServiceStartCertificationRoles = { Role.ADMIN, Role.TESTER }; addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(rsrcServiceStartCertificationRoles)); addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(rsrcServiceStartCertificationRoles)); // TODO to be later defined for product + + //additional authorized roles for resource type + Role[] resourceRoles = { Role.DESIGNER}; + addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles)); } @Override @@ -69,22 +81,38 @@ public class StartCertificationTransition extends LifeCycleTransition { public Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { log.debug("start performing certification test for resource {}", component.getUniqueId()); - - NodeTypeEnum nodeType = (componentType.equals(ComponentTypeEnum.SERVICE)) ? NodeTypeEnum.Service : NodeTypeEnum.Resource; - Either stateChangeResult = lifeCycleOperation.startComponentCertification(nodeType, component, modifier, owner, inTransaction); - if (stateChangeResult.isRight()) { - log.debug("start certification failed on graph"); - StorageOperationStatus response = stateChangeResult.right().value(); - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); - - if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { - actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; + Either result = null; + try{ + Either stateChangeResult = lifeCycleOperation.startCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); + if (stateChangeResult.isRight()) { + log.debug("start certification failed on graph"); + StorageOperationStatus response = stateChangeResult.right().value(); + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); + + if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { + actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; + } + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + result = Either.right(responseFormat); + } + else { + result = Either.left(ModelConverter.convertFromToscaElement(stateChangeResult.left().value())); + } + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); + if (inTransaction == false) { + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } + } else { + if (inTransaction == false) { + log.debug("operation success. do commit"); + titanDao.commit(); + } } - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - return Either.right(responseFormat); } - - return Either.left(stateChangeResult.left().value()); + return result; } @Override @@ -93,11 +121,11 @@ public class StartCertificationTransition extends LifeCycleTransition { log.debug("validate before start certification test. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); // validate user - Either userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo); + Either userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); if (userValidationResponse.isRight()) { return userValidationResponse; } - + if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN) || oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase()); return Either.right(error); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java index fcb211bc3e..277cd173aa 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java @@ -21,25 +21,24 @@ package org.openecomp.sdc.be.components.lifecycle; import java.util.Arrays; -import java.util.List; - import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.user.Role; -import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -50,8 +49,8 @@ public class UndoCheckoutTransition extends LifeCycleTransition { private static Logger log = LoggerFactory.getLogger(CheckoutTransition.class.getName()); private ArtifactsBusinessLogic artifactsManager; - public UndoCheckoutTransition(ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation) { - super(componentUtils, lifecycleOperation); + public UndoCheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); // authorized roles Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; @@ -86,7 +85,7 @@ public class UndoCheckoutTransition extends LifeCycleTransition { log.debug("validate before undo checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); // validate user - Either userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo); + Either userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); if (userValidationResponse.isRight()) { return userValidationResponse; } @@ -111,59 +110,29 @@ public class UndoCheckoutTransition extends LifeCycleTransition { Either result = null; log.debug("start performing undo-checkout for resource {}", component.getUniqueId()); - Either, StorageOperationStatus> artifactsRes = lifeCycleOperation.getComponentOperation(componentType.getNodeType()).getComponentArtifactsForDelete(component.getUniqueId(), componentType.getNodeType(), true); - if (artifactsRes.isRight()) { - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(artifactsRes.right().value()); - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - result = Either.right(responseFormat); - return result; - } - // TODO - start transaction try { - NodeTypeEnum nodeType = componentType.getNodeType(); - - // 1. perform undo checkout on graph (update status and delete - // current version) - Either undoCheckoutResourceResult = lifeCycleOperation.undoCheckout(nodeType, component, modifier, owner, true); + Either undoCheckoutResourceResult = lifeCycleOperation.undoCheckout(component.getUniqueId()); if (undoCheckoutResourceResult.isRight()) { log.debug("checkout failed on graph"); StorageOperationStatus response = undoCheckoutResourceResult.right().value(); ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - result = Either.right(responseFormat); - return result; + result = Either.right(responseFormat); } - - // 2. delete unrelated artifacts - // use artifacts API to delete artifacts from swift / elasticsearch - - if (artifactsRes.left().value() != null) { - List artifacts = artifactsRes.left().value(); - StorageOperationStatus deleteAllResourceArtifacts = artifactsManager.deleteAllComponentArtifactsIfNotOnGraph(artifacts); - - if (!deleteAllResourceArtifacts.equals(StorageOperationStatus.OK)) { - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(deleteAllResourceArtifacts); - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - result = Either.right(responseFormat); - return result; - } + else { + result = Either.left(ModelConverter.convertFromToscaElement(undoCheckoutResourceResult.left().value())); } - - result = Either.left(undoCheckoutResourceResult.left().value()); } finally { if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Change LifecycleState - Undo Checkout failed on graph"); BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Undo Checkout failed on graph"); - log.debug("operation failed. do rollback"); - lifeCycleOperation.getResourceOperation().getTitanGenericDao().rollback(); + titanDao.rollback(); } else { log.debug("operation success. do commit"); - lifeCycleOperation.getResourceOperation().getTitanGenericDao().commit(); + titanDao.commit(); } } - return result; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java index edfe56ebfa..921aefaa8e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java @@ -24,7 +24,7 @@ import java.io.Serializable; public enum CategoryTypeEnum implements Serializable { - CATEGORY("category"), SUBCATEGORY("sub-category"), GROUPING("grouping"); + CATEGORY("category"), SUBCATEGORY("subcategory"), GROUPING("grouping"); private String value; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java new file mode 100644 index 0000000000..46505b843e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java @@ -0,0 +1,218 @@ +package org.openecomp.sdc.be.datamodel.utils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; +import org.openecomp.sdc.be.ui.model.UiResourceDataTransfer; +import org.openecomp.sdc.be.ui.model.UiResourceMetadata; +import org.openecomp.sdc.be.ui.model.UiServiceDataTransfer; +import org.openecomp.sdc.be.ui.model.UiServiceMetadata; + +public class UiComponentDataConverter { + + public static void setUiTranferDataByFieldName(UiComponentDataTransfer dataTransfer, Component component, String fieldName) { + + switch (ComponentFieldsEnum.findByValue(fieldName)) { + + case INPUTS: + if(component.getInputs() == null){ + dataTransfer.setInputs(new ArrayList<>()); + } else { + dataTransfer.setInputs(component.getInputs()); + } + break; + + case COMPONENT_INSTANCE_RELATION: + if(component.getComponentInstancesRelations() == null){ + dataTransfer.setComponentInstancesRelations(new ArrayList<>()); + } else { + dataTransfer.setComponentInstancesRelations(component.getComponentInstancesRelations()); + } + + break; + + case GROUPS: + if(component.getGroups() == null){ + dataTransfer.setGroups(new ArrayList<>()); + } else { + dataTransfer.setGroups(component.getGroups()); + } + break; + + case COMPONENT_INSTANCES: + if(component.getComponentInstances() == null) { + dataTransfer.setComponentInstances(new ArrayList<>()); + } else { + dataTransfer.setComponentInstances(component.getComponentInstances()); + } + break; + + case COMPONENT_INSTANCES_PROPERTIES: + if(component.getComponentInstancesProperties() == null) { + dataTransfer.setComponentInstancesProperties(new HashMap<>()); + } else { + dataTransfer.setComponentInstancesProperties(component.getComponentInstancesProperties()); + } + break; + + case CAPABILITIES: + if(component.getCapabilities() == null) { + dataTransfer.setCapabilities(new HashMap<>()); + } else { + dataTransfer.setCapabilities(component.getCapabilities()); + } + break; + + case REQUIREMENTS: + if(component.getRequirements() == null) { + dataTransfer.setRequirements(new HashMap<>()); + } else { + dataTransfer.setRequirements(component.getRequirements()); + } + break; + + case DEPLOYMENT_ARTIFACTS: + if(component.getDeploymentArtifacts() == null) { + dataTransfer.setDeploymentArtifacts(new HashMap<>()); + } else { + dataTransfer.setDeploymentArtifacts(component.getDeploymentArtifacts()); + } + break; + + case TOSCA_ARTIFACTS: + if(component.getToscaArtifacts() == null) { + dataTransfer.setToscaArtifacts(new HashMap<>()); + } else { + dataTransfer.setToscaArtifacts(component.getToscaArtifacts()); + } + break; + + case ARTIFACTS: + if(component.getArtifacts() == null) { + dataTransfer.setArtifacts(new HashMap<>()); + } else { + dataTransfer.setArtifacts(component.getArtifacts()); + } + break; + + case COMPONENT_INSTANCES_ATTRIBUTES: + if(component.getComponentInstancesAttributes() == null) { + dataTransfer.setComponentInstancesAttributes(new HashMap<>()); + } else { + dataTransfer.setComponentInstancesAttributes(component.getComponentInstancesAttributes()); + } + break; + + case COMPONENT_INSTANCE_INPUTS: + if(component.getComponentInstancesInputs() == null) { + dataTransfer.setComponentInstancesInputs(new HashMap<>()); + } else { + dataTransfer.setComponentInstancesInputs(component.getComponentInstancesInputs()); + } + + break; + + + default: + break; + } + + } + + + public static UiComponentDataTransfer getUiDataTransferFromResourceByParams(Resource resource, List paramsToReturn) { + UiResourceDataTransfer dataTransfer = new UiResourceDataTransfer(); + + for(String fieldName: paramsToReturn){ + + switch (ComponentFieldsEnum.findByValue(fieldName)) { + + case PROPERTIES: + if(resource.getProperties() == null) { + dataTransfer.setProperties(new ArrayList<>()); + } else { + dataTransfer.setProperties(resource.getProperties()); + } + break; + + case INTERFACES: + if(resource.getInterfaces() == null) { + dataTransfer.setInterfaces(new HashMap<>()); + } else { + dataTransfer.setInterfaces(resource.getInterfaces()); + } + break; + + case DERIVED_FROM: + if(resource.getDerivedFrom() == null) { + dataTransfer.setDerivedFrom(new ArrayList<>()); + } else { + dataTransfer.setDerivedFrom(resource.getDerivedFrom()); + } + break; + + case ATTRIBUTES: + if(resource.getAttributes() == null) { + dataTransfer.setAttributes(new ArrayList<>()); + } else { + dataTransfer.setAttributes(resource.getAttributes()); + } + break; + + case ADDITIONAL_INFORMATION: + if(resource.getAdditionalInformation() == null) { + dataTransfer.setAdditionalInformation(new ArrayList<>()); + } else { + dataTransfer.setAdditionalInformation(resource.getAdditionalInformation()); + } + break; + case METADATA: + UiResourceMetadata metadata = new UiResourceMetadata(resource.getCategories(), resource.getDerivedFrom(), (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()); + dataTransfer.setMetadata(metadata); + break; + + default: + setUiTranferDataByFieldName(dataTransfer, resource, fieldName); + } + } + + return dataTransfer; + } + + public static UiComponentDataTransfer getUiDataTransferFromServiceByParams(Service service, List paramsToReturn) { + UiServiceDataTransfer dataTransfer = new UiServiceDataTransfer(); + + for(String fieldName: paramsToReturn){ + + switch (ComponentFieldsEnum.findByValue(fieldName)) { + + case SERVICE_API_ARTIFACTS: + if(service.getServiceApiArtifacts() == null) { + dataTransfer.setServiceApiArtifacts(new HashMap<>()); + } else { + dataTransfer.setServiceApiArtifacts(service.getServiceApiArtifacts()); + } + + break; + + case METADATA: + UiServiceMetadata metadata = new UiServiceMetadata(service.getCategories(), (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition().getMetadataDataDefinition()); + dataTransfer.setMetadata(metadata); + break; + default: + setUiTranferDataByFieldName(dataTransfer, service, fieldName); + } + } + + return dataTransfer; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java index 5670239ef7..7b49d3fcea 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java @@ -25,6 +25,10 @@ import java.util.List; import javax.servlet.http.HttpServletRequest; +import org.openecomp.portalsdk.core.onboarding.crossapi.IPortalRestAPIService; +import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIException; +import org.openecomp.portalsdk.core.restful.domain.EcompRole; +import org.openecomp.portalsdk.core.restful.domain.EcompUser; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -39,11 +43,6 @@ import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoader; -import org.openecomp.portalsdk.core.onboarding.crossapi.IPortalRestAPIService; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIException; -import org.openecomp.portalsdk.core.restful.domain.EcompRole; -import org.openecomp.portalsdk.core.restful.domain.EcompUser; - import fj.data.Either; /* @@ -76,7 +75,7 @@ public class EcompIntImpl implements IPortalRestAPIService { Either newASDCUser = EcompUserConverter.convertEcompUserToUser(user); if (newASDCUser.isRight()) { BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to convert user", ErrorSeverity.INFO); - log.debug("Failed to create user {}",user.toString()); + log.debug("Failed to create user {}", user.toString()); throw new PortalAPIException("Failed to create user " + newASDCUser.right().value()); } else if (newASDCUser.left().value() == null) { BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "NULL pointer returned from user converter", ErrorSeverity.INFO); @@ -292,23 +291,29 @@ public class EcompIntImpl implements IPortalRestAPIService { String updatedRole = null; if (roles == null) { - throw new PortalAPIException("Error: Recieved null for roles"); + throw new PortalAPIException("Error: Recieved null for roles"); } else if (roles.iterator().hasNext()) { EcompRole ecompRole = roles.iterator().next(); updatedRole = EcompRoleConverter.convertEcompRoleToRole(ecompRole); log.debug("pushing role: {} to user: {}", updatedRole, loginId); + Either updateUserRoleResponse = userBusinessLogic.updateUserRole(modifier, loginId, updatedRole); + if (updateUserRoleResponse.isRight()) { + log.debug("Error: Failed to update role"); + BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to update role", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to update role" + updateUserRoleResponse.right().value().toString()); + } } else { log.debug("Error: No roles in List"); BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to fetch roles", ErrorSeverity.INFO); - throw new PortalAPIException("Error: No roles in List"); - } - - Either updateUserRoleResponse = userBusinessLogic.updateUserRole(modifier, loginId, updatedRole); - if (updateUserRoleResponse.isRight()) { - log.debug("Error: Failed to update role"); - BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to update role", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to update role" + updateUserRoleResponse.right().value().toString()); - } + //throw new PortalAPIException("Error: No roles in List"); + //in this cases we want to deactivate the user + Either deActivateUserResponse = userBusinessLogic.deActivateUser(modifier, loginId); + if (deActivateUserResponse.isRight()) { + log.debug("Error: Failed to deactivate user {}",loginId); + BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to deactivate user", ErrorSeverity.INFO); + throw new PortalAPIException(deActivateUserResponse.right().value().getFormattedMessage()); + } + } } @Override @@ -359,7 +364,7 @@ public class EcompIntImpl implements IPortalRestAPIService { if (USERNAME != null && PASSWORD != null) { if (!USERNAME.equals("") && !PASSWORD.equals("")) { - log.debug("User authenticated - Username: {} Password: {}", USERNAME, PASSWORD); + log.debug("User authenticated - Username: ,Password: {}", USERNAME, PASSWORD); return true; } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java index ca970ce45f..4ee3605703 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java @@ -20,12 +20,11 @@ package org.openecomp.sdc.be.ecomp.converters; +import org.openecomp.portalsdk.core.restful.domain.EcompRole; import org.openecomp.sdc.be.user.Role; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.openecomp.portalsdk.core.restful.domain.EcompRole; - public final class EcompRoleConverter { private static Logger log = LoggerFactory.getLogger(EcompRoleConverter.class.getName()); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java index e83b53c2a4..19ef31feaf 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java @@ -24,13 +24,12 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Set; +import org.openecomp.portalsdk.core.restful.domain.EcompRole; +import org.openecomp.portalsdk.core.restful.domain.EcompUser; import org.openecomp.sdc.be.dao.utils.UserStatusEnum; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.Role; -import org.openecomp.portalsdk.core.restful.domain.EcompRole; -import org.openecomp.portalsdk.core.restful.domain.EcompUser; - import fj.data.Either; public final class EcompUserConverter { @@ -38,13 +37,6 @@ public final class EcompUserConverter { private EcompUserConverter() { } - // private static final EcompUserConverter instance = new - // EcompUserConverter(); - - /* - * public static EcompUserConverter getInsatnce() { return instance; } - */ - public static Either convertUserToEcompUser(User asdcUser) { EcompUser convertedUser = new EcompUser(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java index ecdce79b29..ec1a460417 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java @@ -40,11 +40,12 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.servlets.BeGenericServlet; +import org.openecomp.sdc.be.servlets.AbstractValidationsServlet; import org.openecomp.sdc.be.servlets.RepresentationUtils; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; @@ -71,12 +72,14 @@ import fj.data.Either; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Singleton -public class ArtifactExternalServlet extends BeGenericServlet { +public class ArtifactExternalServlet extends AbstractValidationsServlet { @Context private HttpServletRequest request; private static Logger log = LoggerFactory.getLogger(ArtifactExternalServlet.class.getName()); + + private static String startLog = "Start handle request of "; /** * Uploads an artifact to resource or service @@ -92,60 +95,58 @@ public class ArtifactExternalServlet extends BeGenericServlet { @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact uploaded"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Asset not found") }) public Response uploadArtifact(@PathParam("assetType") final String assetType, @PathParam("uuid") final String uuid, @ApiParam(value = "json describe the artifact", required = true) String data) { - - Wrapper responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat = null; + init(log); + + Wrapper responseWrapper = new Wrapper<>(); String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER); String requestURI = request.getRequestURI(); String userId = request.getHeader(Constants.USER_ID_HEADER); String url = request.getMethod() + " " + requestURI; - log.debug("Start handle request of {}", url); + log.debug("{} {}", startLog, url); ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + if (componentType == null) { log.debug("uploadArtifact: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); } - EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { - log.debug("uploadArtifact: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + if (responseWrapper.isEmpty()) { + validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper); } - if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { - log.debug("uploadArtifact: Missing USER_ID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT); - getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + if (responseWrapper.isEmpty() ) { + validateHttpCspUserIdHeader(userId, responseWrapper); } - if (responseWrapper.isEmpty()) { - try { + Response response = null; + try { + if (responseWrapper.isEmpty()) { ServletContext context = request.getSession().getServletContext(); ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either uploadArtifactEither = artifactsLogic.uploadArtifactToComponentByUUID(data, request, componentType, uuid, additionalParams); + Either uploadArtifactEither = artifactsLogic.uploadArtifactToComponentByUUID(data, request, componentType, uuid, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Create)); if (uploadArtifactEither.isRight()) { log.debug("failed to upload artifact"); - responseFormat = uploadArtifactEither.right().value(); - getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + responseWrapper.setInnerElement(uploadArtifactEither.right().value()); } else { Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); Map headers = new HashMap<>(); headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation)); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams); - responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.OK)); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers); } - } catch (Exception e) { - final String message = "failed to upload artifact to a resource or service"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } + if( response == null ){ + response = buildErrorResponse(responseWrapper.getInnerElement()); } + return response; + } catch (Exception e) { + final String message = "failed to upload artifact to a resource or service"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + getComponentsUtils().auditExternalUploadArtifact(responseWrapper.getInnerElement(), componentTypeValue, request, additionalParams); } - return responseWrapper.getInnerElement(); } /** @@ -171,51 +172,51 @@ public class ArtifactExternalServlet extends BeGenericServlet { String requestURI = request.getRequestURI(); String userId = request.getHeader(Constants.USER_ID_HEADER); String url = request.getMethod() + " " + requestURI; - log.debug("Start handle request of {}", url); + log.debug("{} {}", startLog, url); ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); if (componentType == null) { log.debug("uploadArtifact: assetType parameter {} is not valid", assetType); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } - EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { log.debug("uploadArtifact: Missing X-ECOMP-InstanceID header"); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { log.debug("uploadArtifact: Missing USER_ID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT); - getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } - if (responseWrapper.isEmpty()) { - try { + try { + if (responseWrapper.isEmpty()) { ServletContext context = request.getSession().getServletContext(); ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either uploadArtifactEither = artifactsLogic.uploadArtifactToRiByUUID(data, request, componentType, uuid, resourceInstanceName, additionalParams); + Either uploadArtifactEither = artifactsLogic.uploadArtifactToRiByUUID(data, request, componentType, uuid, resourceInstanceName, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Create)); if (uploadArtifactEither.isRight()) { log.debug("failed to upload artifact"); responseFormat = uploadArtifactEither.right().value(); - getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } else { Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); Map headers = new HashMap<>(); headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation)); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams); responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); } - } catch (Exception e) { - final String message = "failed to upload artifact to a resource instance"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); - } + } + }catch (Exception e) { + final String message = "failed to upload artifact to a resource instance"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentTypeValue, request, additionalParams); } return responseWrapper.getInnerElement(); } @@ -243,52 +244,51 @@ public class ArtifactExternalServlet extends BeGenericServlet { String requestURI = request.getRequestURI(); String userId = request.getHeader(Constants.USER_ID_HEADER); String url = request.getMethod() + " " + requestURI; - log.debug("Start handle request of {}", url); + log.debug("{} {}", startLog, url); ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); if (componentType == null) { log.debug("updateArtifact: assetType parameter {} is not valid", assetType); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } - EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - - // Mandatory if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { log.debug("updateArtifact: Missing X-ECOMP-InstanceID header"); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { - log.debug("updateArtifact: Missing USER_ID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT); - getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams); + log.debug("updateArtifact: Missing USER_ID"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } - if (responseWrapper.isEmpty()) { - try { + try { + if (responseWrapper.isEmpty()) { ServletContext context = request.getSession().getServletContext(); ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either uploadArtifactEither = artifactsLogic.updateArtifactOnComponentByUUID(data, request, componentType, uuid, artifactUUID, additionalParams); + Either uploadArtifactEither = artifactsLogic.updateArtifactOnComponentByUUID(data, request, componentType, uuid, artifactUUID, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Update)); if (uploadArtifactEither.isRight()) { log.debug("failed to update artifact"); responseFormat = uploadArtifactEither.right().value(); - getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } else { Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); Map headers = new HashMap<>(); headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation)); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams); responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); } - } catch (Exception e) { - final String message = "failed to update artifact on a resource or service"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); } + } catch (Exception e) { + final String message = "failed to update artifact on a resource or service"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams); } return responseWrapper.getInnerElement(); } @@ -317,51 +317,52 @@ public class ArtifactExternalServlet extends BeGenericServlet { String requestURI = request.getRequestURI(); String userId = request.getHeader(Constants.USER_ID_HEADER); String url = request.getMethod() + " " + requestURI; - log.debug("Start handle request of {}", url); + log.debug("{} {}", startLog, url); ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); if (componentType == null) { log.debug("updateArtifactOnResourceInstance: assetType parameter {} is not valid", assetType); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } - EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { log.debug("updateArtifactOnResourceInstance: Missing X-ECOMP-InstanceID header"); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { log.debug("updateArtifactOnResourceInstance: Missing USER_ID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT); - getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } - if (responseWrapper.isEmpty()) { - try { + try { + if (responseWrapper.isEmpty()) { ServletContext context = request.getSession().getServletContext(); ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either uploadArtifactEither = artifactsLogic.updateArtifactOnRiByUUID(data, request, componentType, uuid, resourceInstanceName, artifactUUID, additionalParams); + Either uploadArtifactEither = artifactsLogic.updateArtifactOnRiByUUID(data, request, componentType, uuid, resourceInstanceName, artifactUUID, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Update)); if (uploadArtifactEither.isRight()) { log.debug("failed to update artifact"); responseFormat = uploadArtifactEither.right().value(); - getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } else { Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); Map headers = new HashMap<>(); headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation)); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams); responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); } - } catch (Exception e) { - final String message = "failed to update artifact on resource instance"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); } + } catch (Exception e) { + final String message = "failed to update artifact on resource instance"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams); } return responseWrapper.getInnerElement(); } @@ -383,57 +384,56 @@ public class ArtifactExternalServlet extends BeGenericServlet { public Response deleteArtifact(@PathParam("assetType") final String assetType, @PathParam("uuid") final String uuid, @PathParam("artifactUUID") final String artifactUUID) { Wrapper responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat; + ResponseFormat responseFormat = null; String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); String requestURI = request.getRequestURI(); String url = request.getMethod() + " " + requestURI; - log.debug("Start handle request of {}", url); - + log.debug("{} {}", startLog, url); ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); if (componentType == null) { log.debug("deleteArtifact: assetType parameter {} is not valid", assetType); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } - EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { log.debug("deleteArtifact: Missing X-ECOMP-InstanceID header"); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { log.debug("deleteArtifact: Missing USER_ID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT); - getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } - if (responseWrapper.isEmpty()) { - try { + try { + if (responseWrapper.isEmpty()) { ServletContext context = request.getSession().getServletContext(); ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either uploadArtifactEither = artifactsLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID, additionalParams); + Either uploadArtifactEither = artifactsLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Delete)); if (uploadArtifactEither.isRight()) { log.debug("failed to delete artifact"); responseFormat = uploadArtifactEither.right().value(); - getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } else { Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); Map headers = new HashMap<>(); headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation)); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams); responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); } - } catch (Exception e) { - final String message = "failed to delete an artifact of a resource or service"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); } + } catch (Exception e) { + final String message = "failed to delete an artifact of a resource or service"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams); } return responseWrapper.getInnerElement(); } @@ -456,57 +456,57 @@ public class ArtifactExternalServlet extends BeGenericServlet { @PathParam("artifactUUID") final String artifactUUID) { Wrapper responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat; + ResponseFormat responseFormat = null; String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); String requestURI = request.getRequestURI(); String url = request.getMethod() + " " + requestURI; - log.debug("Start handle request of {}", url); - + log.debug("{} {}", startLog, url); ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); if (componentType == null) { log.debug("deleteArtifactOnResourceInsatnce: assetType parameter {} is not valid", assetType); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } - EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { log.debug("deleteArtifactOnResourceInsatnce: Missing X-ECOMP-InstanceID header"); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { log.debug("deleteArtifactOnResourceInsatnce: Missing USER_ID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT); - getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } - if (responseWrapper.isEmpty()) { - try { + try { + if (responseWrapper.isEmpty()) { ServletContext context = request.getSession().getServletContext(); ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either uploadArtifactEither = artifactsLogic.deleteArtifactOnRiByUUID(request, componentType, uuid, resourceInstanceName, artifactUUID, additionalParams); + Either uploadArtifactEither = artifactsLogic.deleteArtifactOnRiByUUID(request, componentType, uuid, resourceInstanceName, artifactUUID, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Delete)); if (uploadArtifactEither.isRight()) { log.debug("failed to delete artifact"); responseFormat = uploadArtifactEither.right().value(); - getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } else { Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); Map headers = new HashMap<>(); headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation)); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams); responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); } - } catch (Exception e) { - final String message = "failed to delete an artifact of a resource instance"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); - } + } + } catch (Exception e) { + final String message = "failed to delete an artifact of a resource instance"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams); } return responseWrapper.getInnerElement(); } @@ -530,33 +530,32 @@ public class ArtifactExternalServlet extends BeGenericServlet { @PathParam("uuid") final String uuid, @PathParam("artifactUUID") final String artifactUUID) { Wrapper responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat; + ResponseFormat responseFormat = null; String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER); String requestURI = request.getRequestURI(); String url = request.getMethod() + " " + requestURI; - log.debug("Start handle request of {}", url); + log.debug("{} {}", startLog, url); ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); if (componentType == null) { log.debug("downloadComponentArtifact: assetType parameter {} is not valid", assetType); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } - EnumMap additionalParam = new EnumMap<>(AuditingFieldsKeysEnum.class); - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { log.debug("downloadComponentArtifact: Missing X-ECOMP-InstanceID header"); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } - if (responseWrapper.isEmpty()) { - try { + try { + if (responseWrapper.isEmpty()) { ServletContext context = request.getSession().getServletContext(); ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either downloadComponentArtifactEither = artifactsLogic.downloadComponentArtifactByUUIDs(componentType, uuid, artifactUUID, additionalParam); + Either downloadComponentArtifactEither = artifactsLogic.downloadComponentArtifactByUUIDs(componentType, uuid, artifactUUID, additionalParams); if (downloadComponentArtifactEither.isRight()) { responseFormat = downloadComponentArtifactEither.right().value(); - getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } else { byte[] value = downloadComponentArtifactEither.left().value(); @@ -564,15 +563,16 @@ public class ArtifactExternalServlet extends BeGenericServlet { Map headers = new HashMap<>(); headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByByteArray(value)); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam); responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers)); } - } catch (Exception e) { - final String message = "failed to download an artifact of a resource or service"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); } + } catch (Exception e) { + final String message = "failed to download an artifact of a resource or service"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams); } return responseWrapper.getInnerElement(); } @@ -597,33 +597,33 @@ public class ArtifactExternalServlet extends BeGenericServlet { @PathParam("uuid") final String uuid, @PathParam("resourceInstanceName") final String resourceInstanceName, @PathParam("artifactUUID") final String artifactUUID) { Wrapper responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat; + ResponseFormat responseFormat = null; String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER); String requestURI = request.getRequestURI(); String url = request.getMethod() + " " + requestURI; - log.debug("Start handle request of {}", url); + log.debug("{} {}", startLog, url); ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); if (componentType == null) { log.debug("downloadResourceInstanceArtifact: assetType parameter {} is not valid", assetType); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } - EnumMap additionalParam = new EnumMap<>(AuditingFieldsKeysEnum.class); - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { log.debug("downloadResourceInstanceArtifact: Missing X-ECOMP-InstanceID header"); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } - if (responseWrapper.isEmpty()) { - try { + try { + if (responseWrapper.isEmpty()) { ServletContext context = request.getSession().getServletContext(); ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either downloadResourceArtifactEither = artifactsLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID, additionalParam); + Either downloadResourceArtifactEither = artifactsLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID, additionalParams); if (downloadResourceArtifactEither.isRight()) { responseFormat = downloadResourceArtifactEither.right().value(); - getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } else { byte[] value = downloadResourceArtifactEither.left().value(); @@ -631,15 +631,16 @@ public class ArtifactExternalServlet extends BeGenericServlet { Map headers = new HashMap<>(); headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByByteArray(value)); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam); responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers)); } - } catch (Exception e) { - final String message = "failed to download an artifact of a resource instance"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); } + } catch (Exception e) { + final String message = "failed to download an artifact of a resource instance"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams); } return responseWrapper.getInnerElement(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java index 662399142e..2c7de7032c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java @@ -26,9 +26,10 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.distribution.servlet.DistributionCatalogServlet; import org.openecomp.sdc.be.externalapi.servlet.representation.ArtifactMetadata; import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata; @@ -44,7 +45,7 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; import org.openecomp.sdc.exception.ResponseFormat; @@ -60,8 +61,9 @@ public class AssetMetadataConverter { @Autowired private ComponentsUtils componentsUtils; + @Autowired - private ResourceOperation resourceOperation; + protected ToscaOperationFacade toscaOperationFacade; /* * Relative asset’s URL. Should be used in REST GET API to download the asset’s CSAR. https://{serverBaseURL}/{csarPath} can be obtained from (HttpServletRequest)request.getServerName() @@ -70,19 +72,13 @@ public class AssetMetadataConverter { if (componentList == null || componentList.isEmpty()) { return Either.left(new LinkedList<>()); } - List retResList = new LinkedList<>(); - Component component = componentList.iterator().next(); - ComponentTypeEnum componentType = component.getComponentType(); for (Component curr : componentList) { - - Either resMetaData = convertToMetadata(componentType, serverBaseURL, detailed, curr); - + Either resMetaData = convertToSingleAssetMetadata(curr, serverBaseURL, detailed); if (resMetaData.isRight()) { return Either.right(resMetaData.right().value()); } - retResList.add(resMetaData.left().value()); } @@ -90,6 +86,19 @@ public class AssetMetadataConverter { } + public Either convertToSingleAssetMetadata(T component, String serverBaseURL, boolean detailed) { + ComponentTypeEnum componentType = component.getComponentType(); + Either resMetaData = convertToMetadata(componentType, serverBaseURL, detailed, component); + + if (resMetaData.isRight()) { + return Either.right(resMetaData.right().value()); + } + else{ + return Either.left(resMetaData.left().value()); + } + + } + private Either convertToMetadata(ComponentTypeEnum componentType, String serverBaseURL, boolean detailed, Component curr) { switch (componentType) { @@ -188,12 +197,12 @@ public class AssetMetadataConverter { private T convertToResourceMetadata(T assetToPopulate, Resource resource, String serverBaseURL, boolean detailed) { assetToPopulate = convertToAsset(assetToPopulate, resource, serverBaseURL, detailed); - CategoryDefinition categoryDefinition = resource.getCategories().iterator().next(); - assetToPopulate.setCategory(categoryDefinition.getName()); - - SubCategoryDefinition subCategoryDefinition = categoryDefinition.getSubcategories().iterator().next(); - - assetToPopulate.setSubCategory(subCategoryDefinition.getName()); + CategoryDefinition categoryDefinition; + if(resource.getCategories() != null && !resource.getCategories().isEmpty()){ + categoryDefinition = resource.getCategories().iterator().next(); + assetToPopulate.setCategory(categoryDefinition.getName()); + assetToPopulate.setSubCategory(categoryDefinition.getSubcategories().iterator().next().getName()); + } assetToPopulate.setResourceType(resource.getResourceType().name()); assetToPopulate.setLifecycleState(resource.getLifecycleState().name()); assetToPopulate.setLastUpdaterUserId(resource.getLastUpdaterUserId()); @@ -232,7 +241,7 @@ public class AssetMetadataConverter { assetToPopulate.setLastUpdaterFullName(resource.getLastUpdaterFullName()); assetToPopulate.setToscaResourceName(resource.getToscaResourceName()); - + assetToPopulate.setDescription(resource.getDescription()); return Either.left(assetToPopulate); } @@ -276,9 +285,8 @@ public class AssetMetadataConverter { } private List populateAssetWithArtifacts(Component component, Map artifacts) { - List artifactMetaList = null; - if (artifacts != null) { - artifactMetaList = new LinkedList<>(); + List artifactMetaList = new LinkedList<>(); + if (artifacts != null) { Collection artefactDefList = artifacts.values(); for (ArtifactDefinition artifactDefinition : artefactDefList) { @@ -292,11 +300,11 @@ public class AssetMetadataConverter { } private ArtifactMetadata convertToArtifactMetadata(ArtifactDefinition artifact, String componentType, String componentUUID, String resourceInstanceName) { - // /asdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID} - final String COMPONENT_ARTIFACT_URL = "/asdc/v1/catalog/%s/%s/artifacts/%s"; + // /sdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID} + final String COMPONENT_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/artifacts/%s"; - // /asdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID} - final String RESOURCE_INSTANCE_ARTIFACT_URL = "/asdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s"; + // /sdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID} + final String RESOURCE_INSTANCE_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s"; ArtifactMetadata metadata = new ArtifactMetadata(); @@ -315,52 +323,55 @@ public class AssetMetadataConverter { metadata.setArtifactUUID(artifact.getArtifactUUID()); metadata.setArtifactVersion(artifact.getArtifactVersion()); metadata.setGeneratedFromUUID(artifact.getGeneratedFromId()); - + metadata.setArtifactLabel(artifact.getArtifactLabel()); + metadata.setArtifactGroupType(artifact.getArtifactGroupType().getType()); return metadata; } private Either, StorageOperationStatus> convertToResourceInstanceMetadata(List componentInstances, String componentType, String componentUUID) { List retList = new LinkedList<>(); - Map uuidDuplicatesMap = new HashMap<>(); + Map> uuidDuplicatesMap = new HashMap<>(); for (ComponentInstance componentInstance : componentInstances) { ResourceInstanceMetadata metadata = new ResourceInstanceMetadata(); String componentUid = componentInstance.getComponentUid(); - String invariantUUID; + String invariantUUID, resourceUUID; if (!uuidDuplicatesMap.containsKey(componentUid)) { - Either getInvarUuidresponse = resourceOperation.getInvariantUUID(NodeTypeEnum.Resource, componentInstance.getComponentUid(), false); - if (getInvarUuidresponse.isRight()) { - log.debug("convertToResourceInstanceMetadata: Failed getting Invariant UUID"); - return Either.right(getInvarUuidresponse.right().value()); + Either eitherResource = toscaOperationFacade.getToscaElement(componentInstance.getComponentUid()); + if (eitherResource.isRight()) { + log.debug("convertToResourceInstanceMetadata: Failed getting resource with Uid: {}", componentInstance.getComponentUid()); + return Either.right(eitherResource.right().value()); } else { - invariantUUID = getInvarUuidresponse.left().value(); - uuidDuplicatesMap.put(componentUid, invariantUUID); + final Resource resource = eitherResource.left().value(); + invariantUUID = resource.getInvariantUUID(); + resourceUUID = resource.getUUID(); + ImmutablePair uuidInvariantUUIDPair = new ImmutablePair<>(resourceUUID, invariantUUID); + uuidDuplicatesMap.put(componentUid, uuidInvariantUUIDPair); } } else { - invariantUUID = uuidDuplicatesMap.get(componentUid); + invariantUUID = uuidDuplicatesMap.get(componentUid).getRight(); + resourceUUID = uuidDuplicatesMap.get(componentUid).getLeft(); } metadata.setResourceInvariantUUID(invariantUUID); + metadata.setResourceUUID(resourceUUID); metadata.setResourceInstanceName(componentInstance.getName()); metadata.setResourceName(componentInstance.getComponentName()); metadata.setResourceVersion(componentInstance.getComponentVersion()); - metadata.setResourceType(componentInstance.getOriginType().getValue()); - metadata.setResourceUUID(componentInstance.getComponentUid()); - - Collection values = componentInstance.getDeploymentArtifacts().values(); - LinkedList artifactMetaList = new LinkedList<>(); - - for (ArtifactDefinition artifactDefinition : values) { - ArtifactMetadata converted = convertToArtifactMetadata(artifactDefinition, componentType, componentUUID, componentInstance.getNormalizedName()); - artifactMetaList.add(converted); + metadata.setResoucreType(componentInstance.getOriginType().getValue()); + + if(MapUtils.isNotEmpty(componentInstance.getDeploymentArtifacts())){ + LinkedList artifactMetaList = new LinkedList<>(); + Collection values = componentInstance.getDeploymentArtifacts().values(); + for (ArtifactDefinition artifactDefinition : values) { + ArtifactMetadata converted = convertToArtifactMetadata(artifactDefinition, componentType, componentUUID, componentInstance.getNormalizedName()); + artifactMetaList.add(converted); + } + metadata.setArtifacts(artifactMetaList); } - - metadata.setArtifacts(artifactMetaList); - retList.add(metadata); } - return Either.left(retList); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java index 1b8d6fdb75..552ad163ec 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java @@ -21,19 +21,23 @@ package org.openecomp.sdc.be.externalapi.servlet; import java.io.ByteArrayInputStream; +import java.io.IOException; import java.io.InputStream; -import java.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.function.Predicate; +import java.util.Optional; +import java.util.stream.Collectors; import javax.inject.Singleton; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; @@ -42,27 +46,50 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.http.NameValuePair; +import org.codehaus.jackson.JsonGenerationException; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.elasticsearch.common.Strings; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.impl.ElementBusinessLogic; +import org.openecomp.sdc.be.components.impl.ImportUtils; +import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; +import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; +import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoBase; +import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata; -import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.be.servlets.BeGenericServlet; +import org.openecomp.sdc.be.servlets.AbstractValidationsServlet; import org.openecomp.sdc.be.servlets.RepresentationUtils; +import org.openecomp.sdc.be.utils.CommonBeUtils; import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.util.GeneralUtility; +import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.web.context.WebApplicationContext; import com.jcabi.aspects.Loggable; import com.wordnik.swagger.annotations.ApiOperation; @@ -75,12 +102,11 @@ import fj.data.Either; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Singleton -public class AssetsDataServlet extends BeGenericServlet { +public class AssetsDataServlet extends AbstractValidationsServlet { @Context private HttpServletRequest request; - private AssetMetadataConverter assetMetadataUtils; private static Logger log = LoggerFactory.getLogger(AssetsDataServlet.class.getName()); @GET @@ -89,7 +115,8 @@ public class AssetsDataServlet extends BeGenericServlet { @ApiOperation(value = "Fetch list of assets", httpMethod = "GET", notes = "Returns list of assets", response = Response.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Assets Fetched"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Asset not found") }) - public Response getAssetList(@PathParam("assetType") final String assetType, @QueryParam("category") String category, @QueryParam("subCategory") String subCategory, @QueryParam("distributionStatus") String distributionStatus) { + public Response getAssetList(@PathParam("assetType") final String assetType, @QueryParam("category") String category, @QueryParam("subCategory") String subCategory, @QueryParam("distributionStatus") String distributionStatus, + @QueryParam("resourceType") String resourceType) { Response response = null; ResponseFormat responseFormat = null; @@ -98,8 +125,7 @@ public class AssetsDataServlet extends BeGenericServlet { String requestURI = request.getRequestURI(); String url = request.getMethod() + " " + requestURI; log.debug("Start handle request of {}", url); - String serverBaseURL = request.getRequestURL().toString(); - + AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST; EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); @@ -118,7 +144,7 @@ public class AssetsDataServlet extends BeGenericServlet { ServletContext context = request.getSession().getServletContext(); ElementBusinessLogic elementLogic = getElementBL(context); - getAssetUtils(context); + AssetMetadataConverter assetMetadataUtils = getAssetUtils(context); Map filters = new HashMap(); if (category != null) { @@ -130,6 +156,16 @@ public class AssetsDataServlet extends BeGenericServlet { if (distributionStatus != null) { filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus); } + if (resourceType != null) { + ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType); + if( resourceTypeEnum == null ){ + log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + return buildErrorResponse(responseFormat); + } + filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name()); + } Either, ResponseFormat> assetTypeData = elementLogic.getFilteredCatalogComponents(assetType, filters, query); @@ -140,7 +176,7 @@ public class AssetsDataServlet extends BeGenericServlet { return buildErrorResponse(responseFormat); } else { log.debug("getAssetList: Asset Fetching Success"); - Either, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), serverBaseURL, false); + Either, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, false); if (resMetadata.isRight()) { log.debug("getAssetList: Asset conversion Failed"); responseFormat = resMetadata.right().value(); @@ -176,7 +212,6 @@ public class AssetsDataServlet extends BeGenericServlet { String requestURI = request.getRequestURI(); String url = request.getMethod() + " " + requestURI; log.debug("Start handle request of {}", url); - String serverBaseURL = request.getRequestURL().toString(); EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); @@ -196,7 +231,7 @@ public class AssetsDataServlet extends BeGenericServlet { try { ServletContext context = request.getSession().getServletContext(); ElementBusinessLogic elementLogic = getElementBL(context); - getAssetUtils(context); + AssetMetadataConverter assetMetadataUtils = getAssetUtils(context); Either, ResponseFormat> assetTypeData = elementLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid); @@ -209,7 +244,7 @@ public class AssetsDataServlet extends BeGenericServlet { } else { log.debug("getAssetList: Asset Fetching Success"); additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, assetTypeData.left().value().iterator().next().getName()); - Either, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), serverBaseURL, true); + Either, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, true); if (resMetadata.isRight()) { log.debug("getAssetList: Asset conversion Failed"); responseFormat = resMetadata.right().value(); @@ -230,12 +265,6 @@ public class AssetsDataServlet extends BeGenericServlet { } } - private void getAssetUtils(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - assetMetadataUtils = webApplicationContext.getBean(AssetMetadataConverter.class); - } - @GET @Path("/{assetType}/{uuid}/toscaModel") @Produces(MediaType.APPLICATION_OCTET_STREAM) @@ -297,4 +326,438 @@ public class AssetsDataServlet extends BeGenericServlet { return response; } } + + /** + * Creates a new Resource + * + * @param assetType + * @param data + * @return + */ + @POST + @Path("/{assetType}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "creates a resource", httpMethod = "POST", notes = "creates a resource", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact uploaded"), + @ApiResponse(code = 401, message = "Authorization required"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Resource already exist") }) + public Response createResource(@PathParam("assetType") final String assetType, @ApiParam(value = "json describe the artifact", required = true) String data) { + init(log); + + Wrapper responseWrapper = new Wrapper<>(); + String requestURI = request.getRequestURI(); + String userId = request.getHeader(Constants.USER_ID_HEADER); + String url = request.getMethod() + " " + requestURI; + log.debug("Start handle request of {}", url); + Resource resource = null; + User modifier = null; + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + ServletContext context = request.getSession().getServletContext(); + ResourceBusinessLogic resourceBL = getResourceBL(context); + try { + // Validate X-ECOMP-InstanceID Header + if (responseWrapper.isEmpty()) { + validateXECOMPInstanceIDHeader(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), + responseWrapper); + } + // Validate USER_ID Header + if (responseWrapper.isEmpty()) { + validateHttpCspUserIdHeader(userId, responseWrapper); + } + // Validate assetType + if (responseWrapper.isEmpty()) { + if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) ){ + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + } + //Validate resource type + if(responseWrapper.isEmpty()){ + JSONParser parser = new JSONParser(); + JSONObject jsonObj = (JSONObject) parser.parse(data); + String resourceType = (String) jsonObj.get(FilterKeyEnum.RESOURCE_TYPE.getName()); + if( StringUtils.isEmpty(resourceType) || !ResourceTypeEnum.containsName(resourceType) ){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, (String) jsonObj.get("name")); + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + } + // Convert the user json to a resource + if (responseWrapper.isEmpty()) { + modifier = new User(); + modifier.setUserId(userId); + Either eitherResource = getComponentsUtils() + .convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, + null, ComponentTypeEnum.RESOURCE); + if( eitherResource.isRight() ){ + responseWrapper.setInnerElement(eitherResource.right().value()); + } + else{ + resource = eitherResource.left().value(); + } + + } + //validate name exist + if(responseWrapper.isEmpty()){ + if( Strings.isEmpty(resource.getName())){ + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( + ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue())); + + } + } + + if(responseWrapper.isEmpty()){ + resource.setDerivedFrom(Arrays.asList("tosca.nodes.Root")); + resource.setSystemName(ValidationUtils.convertToSystemName(resource.getName())); + resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(ResourceTypeEnum.VFCMT.name(), + resource.getSystemName())); + handleCategories(context, data, resource, responseWrapper); + } + // Create the resource in the dataModel + if (responseWrapper.isEmpty()) { + Either eitherCreateResponse = resourceBL.createResource(resource, null, + modifier, null, null); + if (eitherCreateResponse.isRight()) { + responseWrapper.setInnerElement(eitherCreateResponse.right().value()); + } else { + resource = eitherCreateResponse.left().value(); + } + } + Response response; + //Build Response and store it in the response Wrapper + if (responseWrapper.isEmpty()) { + response = buildCreatedResourceResponse(resource, context, responseWrapper); + } + else{ + response = buildErrorResponse(responseWrapper.getInnerElement()); + } + return response; + + } catch (Exception e) { + final String message = "failed to create vfc monitoring template resource"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + finally{ + prepareAdditionalAudit(resource, additionalParams); + + getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(), + ComponentTypeEnum.RESOURCE.getValue(), AuditingActionEnum.CREATE_RESOURCE_BY_API.getName(), request, + additionalParams); + } + } + + private void prepareAdditionalAudit(Resource resource, EnumMap additionalParams) { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, StringUtils.EMPTY); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, StringUtils.EMPTY); + + if( resource != null ){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, resource.getUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, resource.getInvariantUUID()); + } else { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, StringUtils.EMPTY); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, StringUtils.EMPTY); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, StringUtils.EMPTY); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, StringUtils.EMPTY); + } + } + + private Response buildCreatedResourceResponse(Component resource, ServletContext context, + Wrapper responseWrapper) throws IOException, JsonGenerationException, JsonMappingException { + ResponseFormat responseFormat; + Response response; + AssetMetadataConverter assetMetadataUtils = getAssetUtils(context); + Either resMetadata = assetMetadataUtils + .convertToSingleAssetMetadata(resource, request.getRequestURL().toString(), + true); + if (resMetadata.isRight()) { + log.debug("Asset conversion Failed"); + responseFormat = resMetadata.right().value(); + responseWrapper.setInnerElement(responseFormat); + response = buildErrorResponse(responseFormat); + } + else{ + final AssetMetadata assetData = resMetadata.left().value(); + assetData.setToscaModelURL(null); + + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.CREATED)); + Object representation = RepresentationUtils.toRepresentation(assetData); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation); + } + return response; + } + + private void handleCategories(ServletContext context, String data, Resource resource, + Wrapper responseWrapper) { + try { + JSONParser parser = new JSONParser(); + JSONObject jsonObj = (JSONObject) parser.parse(data); + String category = (String) jsonObj.get(CategoryTypeEnum.CATEGORY.getValue()); + String subcategory = (String) jsonObj.get(CategoryTypeEnum.SUBCATEGORY.getValue()); + if (Strings.isEmpty(category)) { + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( + ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue())); + } + else if (Strings.isEmpty(subcategory)) { + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( + ActionStatus.COMPONENT_MISSING_SUBCATEGORY)); + } + if (responseWrapper.isEmpty()) { + ElementBusinessLogic elementLogic = getElementBL(context); + // get All Categories + Either, ActionStatus> allResourceCategories = elementLogic + .getAllResourceCategories(); + // Error fetching categories + if (allResourceCategories.isRight()) { + responseWrapper.setInnerElement( + getComponentsUtils().getResponseFormat(allResourceCategories.right().value())); + } else { + addCategories(resource, category, subcategory, allResourceCategories, responseWrapper); + } + } + } catch (Exception e) { + log.debug("Exception occured in addCategories: {}", e.getMessage(), e); + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + private void addCategories(Resource resource, String category, String subcategory, + Either, ActionStatus> allResourceCategories, + Wrapper responseWrapper) { + Optional optionalCategory = + // Stream of all the categories + allResourceCategories.left().value().stream() + // filter in only relevant category + .filter(e -> e.getName().equals(category)) + // get the result + .findAny(); + if (!optionalCategory.isPresent()) { + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( + ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue())); + } else { + CategoryDefinition categoryDefinition = optionalCategory.get(); + + List subCaregories = + // Stream of all sub-categories of the relevant + // category + categoryDefinition.getSubcategories().stream() + // filter in only relevant sub-category + .filter(e -> e.getName().equals(subcategory)) + // get the result + .collect(Collectors.toList()); + + if( subCaregories.isEmpty() ){ + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( + ActionStatus.COMPONENT_INVALID_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue())); + } + else{ + categoryDefinition.setSubcategories(subCaregories); + resource.setCategories(Arrays.asList(categoryDefinition)); + } + + } + } + + + /** + * Changing the lifecycle of an asset + * @param jsonChangeInfo The description - request body + * @param assetType The requested asset type.Valid values are: resources / services (for VFCMT – use "resources") + * @param uuid The uuid of the desired resource to be changed + * @param lifecycleTransition The lifecycle operation to be performed on the asset.Valid values are:Checkin / Checkout / CERTIFICATION_REQUEST + * @return + */ + @POST + @Path("/{assetType}/{uuid}/lifecycleState/{lifecycleOperation}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource state changed"), @ApiResponse(code = 403, message = "Asset is already checked-out by another user")}) + public Response changeResourceState(@ApiParam(value = "LifecycleChangeInfo - relevant for checkin", required = false) String jsonChangeInfo, + @ApiParam(value = "validValues: resources / services ", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam(value = "assetType") final String assetType, + @ApiParam(value = "id of component to be changed") @PathParam(value = "uuid") final String uuid, + @ApiParam(allowableValues = "checkout, checkin", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition) { + Response response = null; + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + + init(log); + + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("Start handle request of {}", url); + + //get the business logic + ServletContext context = request.getSession().getServletContext(); + LifecycleBusinessLogic businessLogic = getLifecycleBL(context); + + Wrapper responseWrapper = runValidations(assetType); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + Component component = null; + Component responseObject = null; + User modifier = null; + String userId = request.getHeader(Constants.USER_ID_HEADER); + + try{ + if (responseWrapper.isEmpty()) { + //get user + Either eitherGetUser = getUser(request, userId); + if (eitherGetUser.isRight()) { + ResponseFormat responseFormat = eitherGetUser.right().value(); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } + modifier = eitherGetUser.left().value(); + + //get the component id from the uuid + Either latestVersion = businessLogic.getLatestComponentByUuid(componentType, uuid); + if (latestVersion.isRight()) { + ResponseFormat responseFormat = latestVersion.right().value(); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } + component = latestVersion.left().value(); + String componentId = component.getUniqueId(); + + //validate the transition is valid + Either validateEnum = validateTransitionEnum(lifecycleTransition, modifier); + if (validateEnum.isRight()) { + ResponseFormat responseFormat = validateEnum.right().value(); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } + LifeCycleTransitionEnum transitionEnum = validateEnum.left().value(); + + //create changeInfo + LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction(); + try { + if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) { + ObjectMapper mapper = new ObjectMapper(); + changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks()); + } + } + catch (Exception e) { + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject"); + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("failed to convert from json {}", jsonChangeInfo, e); + ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(modifier, AuditingActionEnum.CHECKOUT_RESOURCE); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } + + //execute business logic + Either actionResponse = businessLogic.changeComponentState(componentType, componentId, modifier, transitionEnum, changeInfo, false, true); + if (actionResponse.isRight()) { + log.info("failed to change resource state"); + ResponseFormat responseFormat = actionResponse.right().value(); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } + + log.debug("change state successful !!!"); + responseObject = actionResponse.left().value(); + response = buildCreatedResourceResponse(responseObject, context, responseWrapper); + } else { + response = buildErrorResponse(responseWrapper.getInnerElement()); + } + + return response; + } catch (Exception e) { + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Change Lifecycle State"); + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State"); + log.debug("change lifecycle state failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } finally{ + auditChnageLifecycleAction(additionalParams, responseWrapper, componentType, component, responseObject, modifier, userId); + } + } + + private void auditChnageLifecycleAction(EnumMap additionalParams, + Wrapper responseWrapper, ComponentTypeEnum componentType, Component component, + Component responseObject, User modifier, String userId) { + if (modifier!=null){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFullName()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + } else { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, userId); + } + + if (component!=null){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, component.getVersion()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, component.getLifecycleState().name()); + } else { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, ""); + } + + if (responseObject!=null){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, responseObject.getVersion()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, responseObject.getUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, responseObject.getInvariantUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,responseObject.getLifecycleState().name()); + } else { + if (component!=null){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, component.getVersion()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, component.getUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, component.getInvariantUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,component.getLifecycleState().name()); + } else { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,""); + } + } + + getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(), + componentType.getValue(), AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName(), request, + additionalParams); + } + + private Wrapper runValidations(final String assetType) { + Wrapper responseWrapper = new Wrapper<>(); + + // Validate X-ECOMP-InstanceID Header + if (responseWrapper.isEmpty()) { + String instanceId = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER); + validateXECOMPInstanceIDHeader(instanceId,responseWrapper); + } + // Validate USER_ID Header + if (responseWrapper.isEmpty()) { + validateHttpCspUserIdHeader(request.getHeader(Constants.USER_ID_HEADER),responseWrapper); + } + // Validate assetType + if (responseWrapper.isEmpty()) { + if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) && !AssetTypeEnum.SERVICES.getValue().equals(assetType)){ + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + } + + return responseWrapper; + } + + + private Either validateTransitionEnum(final String lifecycleTransition, User user) { + LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT; + try { + transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition); + } catch (IllegalArgumentException e) { + log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString()); + ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, AuditingActionEnum.CHECKOUT_RESOURCE); + return Either.right(error); + } + return Either.left(transitionEnum); + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java index f4194cf2f5..15ebceaa5d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java @@ -30,7 +30,9 @@ public class ArtifactMetadata { private String artifactUUID; private String artifactVersion; private String generatedFromUUID; - + private String artifactLabel; + private String artifactGroupType; + public String getArtifactName() { return artifactName; } @@ -103,4 +105,20 @@ public class ArtifactMetadata { this.generatedFromUUID = generatedFromUUID; } + public String getArtifactLabel() { + return artifactLabel; + } + + public void setArtifactLabel(String artifactLabel) { + this.artifactLabel = artifactLabel; + } + + public String getArtifactGroupType() { + return artifactGroupType; + } + + public void setArtifactGroupType(String artifactGroupType) { + this.artifactGroupType = artifactGroupType; + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java index ea282ec2e8..0952feea05 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java @@ -28,6 +28,7 @@ public class ResourceAssetDetailedMetadata extends ResourceAssetMetadata { private String toscaResourceName; private List resources; private List artifacts; + private String description; public String getLastUpdaterFullName() { return lastUpdaterFullName; @@ -60,4 +61,13 @@ public class ResourceAssetDetailedMetadata extends ResourceAssetMetadata { public void setArtifacts(List artifactMetaList) { this.artifacts = artifactMetaList; } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java index 547bb301f8..a53422f311 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java @@ -27,7 +27,7 @@ public class ResourceInstanceMetadata { private String resourceName; private String resourceInvariantUUID; private String resourceVersion; - private String resourceType; + private String resoucreType; private String resourceUUID; private List artifacts; @@ -63,12 +63,12 @@ public class ResourceInstanceMetadata { this.resourceVersion = resourceVersion; } - public String getResourceType() { - return resourceType; + public String getResoucreType() { + return resoucreType; } - public void setResourceType(String resourceType) { - this.resourceType = resourceType; + public void setResoucreType(String resoucreType) { + this.resoucreType = resoucreType; } public String getResourceUUID() { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java index f7e1d758ac..de95790f4e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java @@ -77,7 +77,7 @@ public class BasicAuthenticationFilter implements ContainerRequestFilter { if (basic.equalsIgnoreCase("Basic")) { try { String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8"); - log.debug("Credentials: {}", credentials); + log.debug("Credentials: {}" , credentials); checkUserCredentiles(requestContext, credentials); } catch (UnsupportedEncodingException e) { log.error("Authentication Filter Failed Couldn't retrieve authentication", e); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java index f6c11d062e..d24743534c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java @@ -38,6 +38,7 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.common.api.Constants; @@ -115,6 +116,17 @@ public class BeServletFilter implements ContainerRequestFilter, ContainerRespons outHttpResponse(responseContext); + log.debug("Close transaction from filter"); + TitanDao titanDao = getTitanDao(); + if ( titanDao != null ){ + if (responseContext.getStatus() == Response.Status.OK.getStatusCode() || responseContext.getStatus() == Response.Status.CREATED.getStatusCode() ){ + titanDao.commit(); + log.debug("Doing commit from filter"); + }else{ + titanDao.rollback(); + log.debug("Doing rollback from filter"); + } + } // Cleaning up MDC.clear(); ThreadLocalsHolder.cleanup(); @@ -126,7 +138,7 @@ public class BeServletFilter implements ContainerRequestFilter, ContainerRespons } private String processMdcFields(ContainerRequestContext requestContext) { - // userId for logging + // UserId for logging String userId = requestContext.getHeaderString(Constants.USER_ID_HEADER); MDC.put("userId", userId); @@ -165,7 +177,13 @@ public class BeServletFilter implements ContainerRequestFilter, ContainerRespons WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); return webApplicationContext.getBean(ComponentsUtils.class); } + private TitanDao getTitanDao() { + ServletContext context = this.sr.getSession().getServletContext(); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(TitanDao.class); + } // Extracted for purpose of clear method name, for logback %M parameter private void inHttpRequest() { if (isInfoLog()) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java index 9e2abebdc5..ea2582cd1b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java @@ -41,9 +41,9 @@ import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.graph.datatype.AdditionalInformationEnum; +import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.Component; @@ -454,51 +454,57 @@ public class ComponentsUtils { getAuditingManager().auditEvent(auditingFields); } - public void auditExternalCrudApiArtifact(ResponseFormat responseFormat, String componentType, String actionEnum, HttpServletRequest request, EnumMap additionalParams) { + public void auditExternalCrudApi(ResponseFormat responseFormat, String componentType, String actionEnum, HttpServletRequest request, EnumMap additionalParams) { log.trace("Inside auditing for audit action {}", actionEnum); String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER); String requestURI = request.getRequestURI(); - int status = responseFormat.getStatus(); - String message = ""; EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; + int status = 0; + String message = ""; + if(responseFormat != null){ + status = responseFormat.getStatus(); + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); } - message += responseFormat.getFormattedMessage(); auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum); auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType); auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - + if (additionalParams != null) { auditingFields.putAll(additionalParams); + if(!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME)){ + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, ""); + } } getAuditingManager().auditEvent(auditingFields); } public void auditExternalDownloadArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap additionalParams) { - auditExternalCrudApiArtifact(responseFormat, componentType, AuditingActionEnum.DOWNLOAD_ARTIFACT.getName(), request, additionalParams); + auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.DOWNLOAD_ARTIFACT.getName(), request, additionalParams); } public void auditExternalUploadArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap additionalParams) { additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER)); additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ""); - auditExternalCrudApiArtifact(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), request, additionalParams); + auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), request, additionalParams); } public void auditExternalUpdateArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap additionalParams) { additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER)); additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ""); - auditExternalCrudApiArtifact(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), request, additionalParams); + auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), request, additionalParams); } public void auditExternalDeleteArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap additionalParams) { additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER)); additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ""); - auditExternalCrudApiArtifact(responseFormat, componentType, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), request, additionalParams); + auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), request, additionalParams); } public void auditCategory(ResponseFormat responseFormat, User modifier, String categoryName, String subCategoryName, String groupingName, AuditingActionEnum actionEnum, String componentType) { @@ -603,6 +609,9 @@ public class ComponentsUtils { case CATEGORY_NOT_FOUND: responseEnum = ActionStatus.COMPONENT_CATEGORY_NOT_FOUND; break; + case INVALID_PROPERTY: + responseEnum = ActionStatus.INVALID_PROPERTY; + break; default: responseEnum = ActionStatus.GENERAL_ERROR; break; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java index fff6fd15a4..cfa108ed80 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java @@ -78,11 +78,8 @@ public class DownloadArtifactLogic { String payloadStr = new String(artifactPayload); byte[] decodedPayload = artifactPayload; - boolean isEncoded = GeneralUtility.isBase64Encoded(payloadStr); - if (isEncoded) { - log.debug("payload is encoded. perform decode"); - decodedPayload = Base64.decode(new String(artifactPayload)); - } + log.debug("payload is encoded. perform decode"); + decodedPayload = Base64.decode(new String(artifactPayload)); final InputStream artifactStream = new ByteArrayInputStream(decodedPayload); log.debug("found artifact for with id: {}", artifactId); try { @@ -106,7 +103,7 @@ public class DownloadArtifactLogic { } catch (IOException e) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Failed to stream artifact data on the response"); BeEcompErrorManager.getInstance().logBeSystemError("Failed to stream artifact data on the response"); - log.debug("Failed to stream artifact data on the response: {}", e.getMessage()); + log.debug("Failed to stream artifact data on the response: {}", e.getMessage(), e); response = buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Failed to stream artifact data on the response"); return response; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java index fca7bf38d8..fa051a9e3d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java @@ -28,7 +28,7 @@ import java.util.Set; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.config.Configuration.DeploymentArtifactTypeConfig; +import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -205,7 +205,7 @@ public class ArtifactTemplateInfo { if (!artifactTypeExist) { BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact", "-Not supported artifact type ", correctType); - log.debug("Not supported artifact type = {}", correctType); + log.debug("Not supported artifact type = {}" , correctType); return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, correctType)); } @@ -275,8 +275,8 @@ public class ArtifactTemplateInfo { return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); } if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) { - if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType())) { - Either.left(true); + if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) { + return Either.left(true); } return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); } @@ -285,7 +285,7 @@ public class ArtifactTemplateInfo { } if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { - Either.left(true); + return Either.left(true); } return Either.left(true); } @@ -324,7 +324,7 @@ public class ArtifactTemplateInfo { private static Either, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) { - Map deploymentArtifacts = null; + Map deploymentArtifacts = null; List artifactTypes = new ArrayList(); if (parentType.equals(NodeTypeEnum.Service)) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java index 24d9c5644d..05af87d789 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java @@ -20,20 +20,19 @@ package org.openecomp.sdc.be.info; -import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupInstance; +import org.openecomp.sdc.be.model.GroupProperty; public class GroupDefinitionInfo { private String name; // the id is unique per group instance on graph. private String uniqueId; + + // the id is unique per group instance on graph. + private String groupInstanceUniqueId; // the group UUID should be changed when one of the artifacts/component // instances has been changed. @@ -46,12 +45,15 @@ public class GroupDefinitionInfo { private String version; private String invariantUUID; + private String customizationUUID; Boolean isBase = null; // artifacts - list of artifact uid. All artifacts in the group must already // be uploaded to the VF private List artifacts; + + private List properties; public GroupDefinitionInfo() { super(); @@ -63,6 +65,21 @@ public class GroupDefinitionInfo { this.setVersion(other.getVersion()); this.setGroupUUID(other.getGroupUUID()); this.setInvariantUUID(other.getInvariantUUID()); + this.setProperties(other.convertToGroupProperties()); + + + } + + public GroupDefinitionInfo(GroupInstance other) { + this.setName(other.getGroupName()); + this.setUniqueId(other.getGroupUid()); + this.setGroupInstanceUniqueId(other.getUniqueId()); + this.setVersion(other.getVersion()); + this.setGroupUUID(other.getGroupUUID()); + this.setCustomizationUUID(other.getCustomizationUUID()); + this.setInvariantUUID(other.getInvariantUUID()); + this.setProperties(other.convertToGroupInstancesProperties()); + } @@ -105,6 +122,15 @@ public class GroupDefinitionInfo { public void setVersion(String version) { this.version = version; } + + + public String getCustomizationUUID() { + return customizationUUID; + } + + public void setCustomizationUUID(String customizationUUID) { + this.customizationUUID = customizationUUID; + } public Boolean getIsBase() { return isBase; @@ -121,10 +147,29 @@ public class GroupDefinitionInfo { public void setArtifacts(List artifacts) { this.artifacts = artifacts; } + + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + + + public String getGroupInstanceUniqueId() { + return groupInstanceUniqueId; + } + + public void setGroupInstanceUniqueId(String groupInstanceUniqueId) { + this.groupInstanceUniqueId = groupInstanceUniqueId; + } @Override public String toString() { return "GroupDefinitionInfo [" + super.toString() + ", isBase=" + isBase + ", artifacts=" + artifacts + "]"; } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java index 8471a801ac..4a7e925639 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java @@ -20,9 +20,6 @@ package org.openecomp.sdc.be.info; -import java.util.List; -import java.util.Map; - public class GroupTemplateInfo { String groupName; boolean isBase; @@ -30,7 +27,6 @@ public class GroupTemplateInfo { public GroupTemplateInfo() { super(); - // TODO Auto-generated constructor stub } public String getGroupName() { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java index 95038b1830..25b6b3564b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java @@ -29,6 +29,8 @@ import java.util.Set; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.model.ArtifactDefinition; +import java.util.Optional; + public class MergedArtifactInfo { private List createdArtifact; @@ -70,7 +72,25 @@ public class MergedArtifactInfo { public List getListToDissotiateArtifactFromGroup(List deletedArtifacts) { List resList = new ArrayList(); for (ArtifactDefinition artifactDefinition : createdArtifact) { - if (!parsetArtifactsNames.contains(artifactDefinition.getArtifactName())) { + boolean isDissotiate = true; + if(parsetArtifactsNames.contains(artifactDefinition.getArtifactName())){ + isDissotiate = false; + }else{ + if (artifactDefinition.getGeneratedFromId() != null && !artifactDefinition.getGeneratedFromId().isEmpty()){ + Optional op = createdArtifact.stream().filter(p -> p.getUniqueId().equals(artifactDefinition.getGeneratedFromId())).findAny(); + if(op.isPresent()){ + ArtifactDefinition generatedFromArt = op.get(); + if(parsetArtifactsNames.contains(generatedFromArt.getArtifactName())){ + isDissotiate = false; + } + } + else{ + isDissotiate = true; + } + + } + } + if (isDissotiate) { boolean isDeleted = false; for (ArtifactDefinition deletedArtifact : deletedArtifacts) { if (artifactDefinition.getUniqueId().equalsIgnoreCase(deletedArtifact.getUniqueId())) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java index d40a3d4433..38629ab7a1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java @@ -29,6 +29,8 @@ import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; +import org.openecomp.portalsdk.core.onboarding.ueb.UebException; +import org.openecomp.portalsdk.core.onboarding.ueb.UebManager; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; @@ -43,9 +45,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import org.openecomp.portalsdk.core.onboarding.ueb.UebException; -import org.openecomp.portalsdk.core.onboarding.ueb.UebManager; - public class BEAppContextListener extends AppContextListener implements ServletContextListener { private static final String MANIFEST_FILE_NAME = "/META-INF/MANIFEST.MF"; @@ -68,7 +67,7 @@ public class BEAppContextListener extends AppContextListener implements ServletC DownloadArtifactLogic downloadArtifactLogic = new DownloadArtifactLogic(); context.getServletContext().setAttribute(Constants.DOWNLOAD_ARTIFACT_LOGIC_ATTR, downloadArtifactLogic); - context.getServletContext().setAttribute(Constants.SDC_RELEASE_VERSION_ATTR, getVersionFromManifest(context)); + context.getServletContext().setAttribute(Constants.ASDC_RELEASE_VERSION_ATTR, getVersionFromManifest(context)); // Monitoring service BeMonitoringService bms = new BeMonitoringService(context.getServletContext()); @@ -115,7 +114,7 @@ public class BEAppContextListener extends AppContextListener implements ServletC try { Manifest mf = new Manifest(inputStream); Attributes atts = mf.getMainAttributes(); - version = atts.getValue(Constants.SDC_RELEASE_VERSION_ATTR); + version = atts.getValue(Constants.ASDC_RELEASE_VERSION_ATTR); if (version == null || version.isEmpty()) { log.warn("failed to read ASDC version from MANIFEST."); } else { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java index 0e8addf692..d8f834c970 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java @@ -25,6 +25,7 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; +import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.util.EnumMap; import java.util.HashMap; @@ -40,6 +41,7 @@ import javax.ws.rs.core.Response; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.codehaus.jackson.map.ObjectMapper; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; @@ -92,7 +94,6 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { @Autowired protected ComponentsUtils componentsUtils; - private static final Object LOCK = new Object(); private Logger log = null; protected void init(Logger log) { @@ -101,28 +102,20 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } - private void initLog(Logger log) { + private synchronized void initLog(Logger log) { if (this.log == null) { - synchronized (LOCK) { - if (this.log == null) { - this.log = log; - } - - } + this.log = log; } } - private void initSpringFromContext() { + private synchronized void initSpringFromContext() { if (servletUtils == null) { - synchronized (LOCK) { - if (servletUtils == null) { - ServletContext context = servletRequest.getSession().getServletContext(); - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - servletUtils = webApplicationContext.getBean(ServletUtils.class); - resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class); - } - } + ServletContext context = servletRequest.getSession().getServletContext(); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context + .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + servletUtils = webApplicationContext.getBean(ServletUtils.class); + resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class); } } @@ -137,10 +130,10 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } } - protected void validateUserExist(Wrapper responseWrapper, Wrapper userWrapper, String userId) { - log.debug("get user {} from DB", userId); + protected void validateUserExist(Wrapper responseWrapper, Wrapper userWrapper, String userUserId) { + log.debug("get user {} from DB", userUserId); // get user details - if (userId == null) { + if (userUserId == null) { log.info("user userId is null"); Response response = returnMissingInformation(new User()); responseWrapper.setInnerElement(response); @@ -148,11 +141,11 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { else { IUserBusinessLogic userAdmin = getServletUtils().getUserAdmin(); - Either eitherCreator = userAdmin.getUser(userId, false); + Either eitherCreator = userAdmin.getUser(userUserId, false); if (eitherCreator.isRight()) { - log.info("user is not listed. userId={}", userId); + log.info("user is not listed. userId={}", userUserId); User user = new User(); - user.setUserId(userId); + user.setUserId(userUserId); Response response = returnMissingInformation(user); responseWrapper.setInnerElement(response); } else { @@ -202,6 +195,16 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { responseWrapper.setInnerElement(errorResponse); } + } + protected void validateCsar(Wrapper responseWrapper, File file, String payloadName) throws FileNotFoundException { + InputStream fileInputStream = new FileInputStream(file); + Map unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream)); + if (payloadName == null || payloadName.isEmpty() || unzippedFolder.isEmpty()) { + log.info("Invalid json was received. payloadName should be yml file name"); + Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + responseWrapper.setInnerElement(errorResponse); + } + } protected void fillZipContents(Wrapper yamlStringWrapper, File file) throws FileNotFoundException { @@ -219,6 +222,33 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { log.debug("received yaml: {}", yamlAsString); yamlStringWrapper.setInnerElement(yamlAsString); } + + protected void fillPayloadDataFromFile(Wrapper responseWrapper, UploadResourceInfo uploadResourceInfoWrapper, File file) { + try(InputStream fileInputStream = new FileInputStream(file);){ + + byte [] data = new byte[(int)file.length()]; + if( fileInputStream.read(data) == -1){ + log.info("Invalid json was received."); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + + Response errorResp = buildErrorResponse(responseFormat); + responseWrapper.setInnerElement(errorResp); + } + String payloadData = Base64.encodeBase64String(data); + uploadResourceInfoWrapper.setPayloadData(payloadData); + + + + } catch (IOException e) { + log.info("Invalid json was received or Error while closing input Stream."); + log.debug("Invalid json was received or Error while closing input Stream. {}", e.getMessage(), e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + + Response errorResp = buildErrorResponse(responseFormat); + responseWrapper.setInnerElement(errorResp); + + } + } protected void validateUserRole(Wrapper errorResponseWrapper, User user, ResourceAuthorityTypeEnum resourceAuthority) { log.debug("validate user role"); @@ -248,7 +278,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } else { if (!resourceAuthorityEnum.isBackEndImport()) { isValid = resourceInfoObject.getPayloadName() != null && !resourceInfoObject.getPayloadName().isEmpty(); - // TODO Tal only resource name is checked + //Tal only resource name is checked } else { isValid = true; } @@ -256,6 +286,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } } catch (JsonSyntaxException e) { + log.debug("Invalid json was received. {}", e.getMessage(), e); isValid = false; } @@ -294,8 +325,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { protected void validatePayloadIsTosca(Wrapper responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) { log.debug("checking payload is valid tosca"); boolean isValid; - String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload; - Map mappedToscaTemplate = (Map) new Yaml().load(heatDecodedPayload); + Map mappedToscaTemplate = (Map) new Yaml().load(toscaPayload); Either findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION); if (findFirstToscaStringElement.isRight()) { @@ -337,9 +367,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { protected void validatePayloadNameSpace(Wrapper responseWrapper, UploadResourceInfo resourceInfo, User user, String toscaPayload) { boolean isValid; String nameSpace = ""; - - String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload; - Map mappedToscaTemplate = (Map) new Yaml().load(heatDecodedPayload); + Map mappedToscaTemplate = (Map) new Yaml().load(toscaPayload); Either, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); if (toscaElement.isRight() || toscaElement.left().value().size() != 1) { isValid = false; @@ -357,7 +385,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } else { String str1 = nameSpace.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); String[] findTypes = str1.split("\\."); - if (ResourceTypeEnum.contains(findTypes[0].toUpperCase())) { + if (ResourceTypeEnum.containsName(findTypes[0].toUpperCase())) { String type = findTypes[0].toUpperCase(); resourceInfo.setResourceType(type); } else { @@ -370,8 +398,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { protected void validatePayloadIsSingleResource(Wrapper responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) { log.debug("checking payload contains single resource"); boolean isValid; - String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload; - Map mappedToscaTemplate = (Map) new Yaml().load(heatDecodedPayload); + Map mappedToscaTemplate = (Map) new Yaml().load(toscaPayload); Either, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); if (toscaElement.isRight()) { isValid = false; @@ -392,8 +419,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { protected void validatePayloadIsNotService(Wrapper responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaPayload) { log.debug("checking payload is not a tosca service"); - String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload; - Map mappedToscaTemplate = (Map) new Yaml().load(heatDecodedPayload); + Map mappedToscaTemplate = (Map) new Yaml().load(toscaPayload); Either toscaElement = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL); if (toscaElement.isLeft()) { @@ -406,24 +432,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } } - - protected void validatePayloadIsTopologyTemplate(Wrapper responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaPayload) { - log.debug("checking payload is a tosca topology template"); - String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload; - Map mappedToscaTemplate = (Map) new Yaml().load(heatDecodedPayload); - Either toscaElement = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL); - - if (toscaElement.isRight()) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - - } - + protected void validateToscaTemplatePayloadName(Wrapper responseWrapper, UploadResourceInfo uploadResourceInfo, User user) { String toscaTemplatePayloadName = uploadResourceInfo.getPayloadName(); boolean isValidSuffix = false; @@ -495,7 +504,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { responseWrapper.setInnerElement(errorResponse); } else { String toscaPayload = resourceInfo.getPayloadData(); - String decodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload; + String decodedPayload = new String(Base64.decodeBase64(toscaPayload)); yamlStringWrapper.setInnerElement(decodedPayload); } @@ -510,13 +519,26 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { if (responseWrapper.isEmpty()) { validateDataNotNull(responseWrapper, file, resourceInfoJsonString); } - if (responseWrapper.isEmpty()) { - validateZip(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName()); - } - - // Fill PayLoad From File - if (responseWrapper.isEmpty()) { - fillToscaTemplateFromZip(yamlStringWrapper, uploadResourceInfoWrapper.getInnerElement().getPayloadName(), file); + if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){ + if (responseWrapper.isEmpty()) { + validateZip(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName()); + } + + // Fill PayLoad From File + if (responseWrapper.isEmpty()) { + fillToscaTemplateFromZip(yamlStringWrapper, uploadResourceInfoWrapper.getInnerElement().getPayloadName(), file); + } + }else{ + + if (responseWrapper.isEmpty()) { + validateCsar(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName()); + } + + // Fill PayLoad From File + if (responseWrapper.isEmpty()) { + fillPayloadDataFromFile(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), file); + } + } } else { @@ -548,12 +570,12 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } } } - - protected void commonGeneralValidations(Wrapper responseWrapper, Wrapper userWrapper, Wrapper uploadResourceInfoWrapper, ResourceAuthorityTypeEnum resourceAuthorityEnum, String userId, + + protected void commonGeneralValidations(Wrapper responseWrapper, Wrapper userWrapper, Wrapper uploadResourceInfoWrapper, ResourceAuthorityTypeEnum resourceAuthorityEnum, String userUserId, String resourceInfoJsonString) { if (responseWrapper.isEmpty()) { - validateUserExist(responseWrapper, userWrapper, userId); + validateUserExist(responseWrapper, userWrapper, userUserId); } if (responseWrapper.isEmpty()) { @@ -575,7 +597,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { private void validateResourceType(Wrapper responseWrapper, UploadResourceInfo uploadResourceInfo, User user) { String resourceType = uploadResourceInfo.getResourceType(); - if (resourceType == null || !ResourceTypeEnum.contains(resourceType)) { + if (resourceType == null || !ResourceTypeEnum.containsName(resourceType)) { ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); Response errorResponse = buildErrorResponse(responseFormat); EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); @@ -610,7 +632,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } } - protected void topologyTemplatePayloadValidations(Wrapper responseWrapper, Wrapper yamlStringWrapper, User user, UploadResourceInfo uploadResourceInfo) { + /*protected void topologyTemplatePayloadValidations(Wrapper responseWrapper, Wrapper yamlStringWrapper, User user, UploadResourceInfo uploadResourceInfo) { if (responseWrapper.isEmpty()) { validatePayloadIsYml(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement()); @@ -622,16 +644,23 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { validatePayloadIsTopologyTemplate(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement()); } - } + }*/ protected void handleImport(Wrapper responseWrapper, User user, UploadResourceInfo resourceInfoObject, String yamlAsString, ResourceAuthorityTypeEnum authority, boolean createNewVersion, String resourceUniqueId) { - Either, ResponseFormat> createOrUpdateResponse = null; - Response response = null; + Either, ResponseFormat> createOrUpdateResponse; + Response response; Object representation = null; if (CsarValidationUtils.isCsarPayloadName(resourceInfoObject.getPayloadName())) { log.debug("import resource from csar"); + createOrUpdateResponse = importResourceFromUICsar(resourceInfoObject, user, resourceUniqueId); + //if (createOrUpdateResponse.isLeft()){ + // LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(); + // lifecycleChangeInfo.setUserRemarks("certification on import"); + // Function> validator = (resource) -> resourceImportManager.getResourceBusinessLogic().validatePropertiesDefaultValues(createOrUpdateResponse.left().value().left); + //} + } else if (!authority.isUserTypeResource()) { log.debug("import normative type resource"); createOrUpdateResponse = resourceImportManager.importNormativeResource(yamlAsString, resourceInfoObject, user, createNewVersion, true); @@ -645,7 +674,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { try { representation = RepresentationUtils.toRepresentation(createOrUpdateResponse.left().value().getLeft()); } catch (IOException e) { - e.printStackTrace(); + log.debug("Error while building resource representation : {}", e.getMessage(), e); } ActionStatus successStatus = createOrUpdateResponse.left().value().right; response = buildOkResponse(getComponentsUtils().getResponseFormat(successStatus), representation); @@ -655,9 +684,9 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { private Either, ResponseFormat> importResourceFromUICsar(UploadResourceInfo resourceInfoObject, User user, String resourceUniqueId) { - Either createOrUpdateResourceRes = null; + Either createOrUpdateResourceRes; ImmutablePair result = null; - ActionStatus actionStatus = null; + ActionStatus actionStatus; org.openecomp.sdc.be.model.Resource resource = new org.openecomp.sdc.be.model.Resource(); String payloadName = resourceInfoObject.getPayloadName(); fillResourceFromResourceInfoObject(resource, resourceInfoObject); @@ -673,7 +702,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { return Either.right(createOrUpdateResourceRes.right().value()); } if (resourceUniqueId == null || resourceUniqueId.isEmpty()) { - createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().createResource(resource, user, csarUIPayload, payloadName); + createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, csarUIPayload, payloadName); if (createOrUpdateResourceRes.isRight()) { return Either.right(createOrUpdateResourceRes.right().value()); } @@ -714,7 +743,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } log.debug("checking payload is valid tosca"); - String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaYaml)) ? new String(Base64.decodeBase64(toscaYaml)) : toscaYaml; + String heatDecodedPayload = toscaYaml; Map mappedToscaTemplate = (Map) new Yaml().load(heatDecodedPayload); Either findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION); @@ -775,8 +804,8 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { log.info("Failed to decode received csar", csarUUID); return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_NOT_FOUND, csarUUID)); } - - byte[] decodedPayload = (GeneralUtility.isBase64Encoded(payloadData)) ? Base64.decodeBase64(payloadData.getBytes(StandardCharsets.UTF_8)) : payloadData.getBytes(StandardCharsets.UTF_8); + + byte[] decodedPayload = Base64.decodeBase64(payloadData.getBytes(StandardCharsets.UTF_8)); if (decodedPayload == null) { log.info("Failed to decode received csar", csarUUID); return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_NOT_FOUND, csarUUID)); @@ -840,4 +869,59 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } return response; } + + protected void validateXECOMPInstanceIDHeader(String instanceIdHeader, Wrapper responseWrapper) { + ResponseFormat responseFormat; + if(StringUtils.isEmpty(instanceIdHeader) ){ + log.debug("Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + responseWrapper.setInnerElement(responseFormat); + } + } + + protected void validateHttpCspUserIdHeader(String header, Wrapper responseWrapper) { + ResponseFormat responseFormat; + if( StringUtils.isEmpty(header)){ + log.debug("MissingUSER_ID"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); + responseWrapper.setInnerElement(responseFormat); + } + } + + /** + * Convert json to Object object + * @param + * @param classSupplier + * @param json + * @return + */ + public Either parseToObject(String json, Supplier> classSupplier) { + + try { + T object = RepresentationUtils.fromRepresentation(json, classSupplier.get()); + return Either.left(object); + } catch (Exception e) { + log.debug("Failed to parse json to {} object", classSupplier.get().getName(), e); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + return Either.right(responseFormat); + } + } + + /** + * Convert json to Object object + * @param + * @param json + * @param type + * @return + */ + public Either, ResponseFormat> parseListOfObjects(String json, Type type) { + try { + List listOfObjects = gson.fromJson(json, type); + return Either.left(listOfObjects); + } catch (Exception e) { + log.debug("Failed to parse json to {} object", type.getClass().getName(), e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + return Either.right(responseFormat); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java index aaf8f96dca..560ab7d023 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java @@ -39,9 +39,9 @@ import javax.ws.rs.core.Response; import org.openecomp.sdc.be.components.impl.AdditionalInformationBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.WebAppContextWrapper; -import org.openecomp.sdc.be.model.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.model.AdditionalInformationDefinition; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.config.EcompErrorName; @@ -75,9 +75,9 @@ public class AdditionalInformationServlet extends BeGenericServlet { @ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 409, message = "Additional information key already exist") }) public Response createResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) { - return createAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userId, data); + return createAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userUserId, data); } @@ -89,9 +89,9 @@ public class AdditionalInformationServlet extends BeGenericServlet { @ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 409, message = "Additional information key already exist") }) public Response createServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, - @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) { - return createAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userId, data); + return createAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userUserId, data); } @@ -240,7 +240,7 @@ public class AdditionalInformationServlet extends BeGenericServlet { if (either.isRight()) { ResponseFormat responseFormat = either.right().value(); - log.info("Failed to create additional information {}. REason - {}", additionalInfoParameterInfo, responseFormat); + log.info("Failed to create additional information {}. Reason - {}", additionalInfoParameterInfo, responseFormat); return buildErrorResponse(responseFormat); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java index b7af00a7d2..b7fef4554f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java @@ -20,6 +20,8 @@ package org.openecomp.sdc.be.servlets; +import java.util.Map; + import javax.inject.Singleton; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; @@ -38,23 +40,18 @@ import javax.ws.rs.core.Response; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; -import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperation; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.ArtifactUiDownloadData; import org.openecomp.sdc.be.model.Operation; -import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; import com.jcabi.aspects.Loggable; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; @@ -75,8 +72,6 @@ public class ArtifactServlet extends BeGenericServlet { private static Logger log = LoggerFactory.getLogger(ArtifactServlet.class.getName()); - private Gson gson = new Gson(); - // *************** Resources @POST @Path("/resources/{resourceId}/artifacts") @@ -88,11 +83,10 @@ public class ArtifactServlet extends BeGenericServlet { public Response loadArtifact(@PathParam("resourceId") final String resourceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { return handleUploadRequest(data, request, resourceId, ComponentTypeEnum.RESOURCE); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "loadArtifact"); + } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifact"); log.debug("loadArtifact unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -109,11 +103,10 @@ public class ArtifactServlet extends BeGenericServlet { @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { return handleUpdateRequest(data, request, resourceId, artifactId, ComponentTypeEnum.RESOURCE); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "updateArtifact"); + } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifact"); log.debug("updateArtifact unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -129,11 +122,10 @@ public class ArtifactServlet extends BeGenericServlet { public Response deleteArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, null, null); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "deleteArtifact"); + } catch (Exception e) { log.debug("deleteArtifact unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } @@ -150,11 +142,10 @@ public class ArtifactServlet extends BeGenericServlet { public Response loadInformationArtifact(@PathParam("serviceId") final String serviceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { return handleUploadRequest(data, request, serviceId, ComponentTypeEnum.SERVICE); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "loadInformationArtifact"); + } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadInformationArtifact"); log.debug("loadInformationArtifact unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -171,11 +162,10 @@ public class ArtifactServlet extends BeGenericServlet { @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "updateInformationArtifact"); + } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateInformationArtifact"); log.debug("updateInformationArtifact unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -193,11 +183,10 @@ public class ArtifactServlet extends BeGenericServlet { @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "updateApiArtifact"); + } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateApiArtifact"); log.debug("updateApiArtifact unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -214,11 +203,10 @@ public class ArtifactServlet extends BeGenericServlet { @HeaderParam(value = Constants.MD5_HEADER) String origMd5) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "deleteApiArtifact"); + } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteApiArtifact"); log.debug("deleteApiArtifact unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -234,11 +222,10 @@ public class ArtifactServlet extends BeGenericServlet { public Response deleteInformationalArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "deleteInformationalArtifact"); + } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteInformationalArtifact"); log.debug("deleteInformationalArtifact unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -258,11 +245,10 @@ public class ArtifactServlet extends BeGenericServlet { public Response downloadServiceArtifactBase64(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { return handleDownloadRequest(request, serviceId, artifactId, null, ComponentTypeEnum.SERVICE, null); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "downloadServiceArtifactBase64"); + } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadServiceArtifactBase64"); log.debug("downloadServiceArtifactBase64 unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -278,11 +264,10 @@ public class ArtifactServlet extends BeGenericServlet { public Response downloadResourceArtifactBase64(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { return handleDownloadRequest(request, resourceId, artifactId, null, ComponentTypeEnum.RESOURCE, null); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "downloadResourceArtifactBase64"); + } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceArtifactBase64"); log.debug("downloadResourceArtifactBase64 unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -300,11 +285,10 @@ public class ArtifactServlet extends BeGenericServlet { @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { return handleDownloadRequest(request, componentInstanceId, artifactId, componentId, ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentType); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "downloadResourceInstanceArtifactBase64"); + } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64"); log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -325,11 +309,10 @@ public class ArtifactServlet extends BeGenericServlet { @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { - return handleArtifactRequest(data, request, resourceId, interfaceType, operation, null, ComponentTypeEnum.RESOURCE, ArtifactOperation.Create, null, null); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "loadArtifactToInterface"); + return handleArtifactRequest(data, request, resourceId, interfaceType, operation, null, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.Create, null, null); + } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifactToInterface"); log.debug("loadArtifactToInterface unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -348,11 +331,10 @@ public class ArtifactServlet extends BeGenericServlet { @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, interfaceType, operation); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "deleteArtifactToInterface"); + } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteArtifactToInterface"); log.debug("deleteArtifactToInterface unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -371,11 +353,10 @@ public class ArtifactServlet extends BeGenericServlet { @ApiParam(value = "json describe the artifact", required = true) String data) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { - return handleArtifactRequest(data, request, resourceId, interfaceType, operation, artifactId, ComponentTypeEnum.RESOURCE, ArtifactOperation.Update, null, null); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "updateArtifactToInterface"); + return handleArtifactRequest(data, request, resourceId, interfaceType, operation, artifactId, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.Update, null, null); + } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifactToInterface"); log.debug("updateArtifactToInterface unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -394,11 +375,10 @@ public class ArtifactServlet extends BeGenericServlet { @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { - return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperation.Update, componentId, containerComponentType); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "updateRIArtifact"); + return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.Update, componentId, containerComponentType); + } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateRIArtifact"); log.debug("updateRIArtifact unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -417,11 +397,10 @@ public class ArtifactServlet extends BeGenericServlet { @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { - return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperation.Update, componentId, containerComponentType); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "loadResourceInstanceHeatEnvArtifact"); + return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.Update, componentId, containerComponentType); + } catch (Exception e) { log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } @@ -439,11 +418,10 @@ public class ArtifactServlet extends BeGenericServlet { @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { - return handleArtifactRequest(data, request, componentInstanceId, null, null, null, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperation.Create, componentId, containerComponentType); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "loadResourceInstanceHeatEnvArtifact"); + return handleArtifactRequest(data, request, componentInstanceId, null, null, null, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.Create, componentId, containerComponentType); + } catch (Exception e) { log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } @@ -461,27 +439,69 @@ public class ArtifactServlet extends BeGenericServlet { @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); try { - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(containerComponentType); return handleDeleteRequest(request, componentInstanceId, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, null, null, componentId); - } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "deleteArtifact"); + } catch (Exception e) { log.debug("deleteArtifact unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } + + + @GET + @Path("/{containerComponentType}/{componentId}/artifactsByType/{artifactGroupType}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") }) + public Response getComponentArtifacts( + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleGetArtifactsRequest(request, componentId, null, artifactGroupType, containerComponentType); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64"); + log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifactsByType/{artifactGroupType}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") }) + public Response getComponentInstanceArtifacts( + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleGetArtifactsRequest(request,componentInstanceId , componentId, artifactGroupType, containerComponentType); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64"); + log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + // ////////// API END /////////////////////////// // ************ private ********************* private Response handleUploadRequest(String data, HttpServletRequest request, String componentId, ComponentTypeEnum componentType) { - return handleArtifactRequest(data, request, componentId, null, componentType, ArtifactOperation.Create); + return handleArtifactRequest(data, request, componentId, null, componentType, ArtifactOperationEnum.Create); } private Response handleUpdateRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType) { - return handleArtifactRequest(data, request, componentId, artifactId, componentType, ArtifactOperation.Update); + return handleArtifactRequest(data, request, componentId, artifactId, componentType, ArtifactOperationEnum.Update); } private Response handleDownloadRequest(HttpServletRequest request, String componentId, String artifactId, String parentId, ComponentTypeEnum componentType, String containerComponentType) { @@ -505,6 +525,25 @@ public class ArtifactServlet extends BeGenericServlet { } return response; } + + private Response handleGetArtifactsRequest(HttpServletRequest request, String componentId, String parentId, String artifactGroupType, String containerComponentType) { + String userId = request.getHeader(Constants.USER_ID_HEADER); + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + ComponentTypeEnum componentTypeEnum = parentId == null || parentId.isEmpty()? ComponentTypeEnum.findByParamName(containerComponentType): ComponentTypeEnum.RESOURCE_INSTANCE; + Either, ResponseFormat> actionResult = artifactsLogic.handleGetArtifactsByType(containerComponentType, parentId, componentTypeEnum, componentId, artifactGroupType, userId); + + Response response; + if (actionResult.isRight()) { + response = buildErrorResponse(actionResult.right().value()); + } else { + + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResult.left().value()); + } + + return response; + } + private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName) { return handleDeleteRequest(request, componentId, artifactId, componentType, interfaceType, operationName, null); @@ -514,7 +553,7 @@ public class ArtifactServlet extends BeGenericServlet { String userId = request.getHeader(Constants.USER_ID_HEADER); ServletContext context = request.getSession().getServletContext(); ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, ArtifactOperation.Delete, artifactId, null, null, null, interfaceType, operationName, + Either, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, artifactsLogic.new ArtifactOperationInfo (false, false, ArtifactOperationEnum.Delete), artifactId, null, null, null, interfaceType, operationName, parentId, null); Response response; if (actionResult.isRight()) { @@ -531,7 +570,7 @@ public class ArtifactServlet extends BeGenericServlet { } - private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String interfaceName, String operationName, String artifactId, ComponentTypeEnum componentType, ArtifactOperation operation, String parentId, + private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String interfaceName, String operationName, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operationEnum, String parentId, String containerComponentType) { ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); String origMd5 = request.getHeader(Constants.MD5_HEADER); @@ -540,7 +579,8 @@ public class ArtifactServlet extends BeGenericServlet { ServletContext context = request.getSession().getServletContext(); ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, interfaceName, operationName, parentId, + Either, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, + artifactsLogic.new ArtifactOperationInfo (false, false,operationEnum), artifactId, artifactInfo, origMd5, data, interfaceName, operationName, parentId, containerComponentType); Response response; if (actionResult.isRight()) { @@ -557,7 +597,7 @@ public class ArtifactServlet extends BeGenericServlet { } - private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperation operation) { + private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operation) { return handleArtifactRequest(data, servletRequest, componentId, null, null, artifactId, componentType, operation, null, null); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java index b5e64ae00e..c7bc481119 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java @@ -92,9 +92,7 @@ public class AttributeServlet extends AbstractValidationsServlet { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); - log.debug("data is {}", data); + log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data); try { Wrapper errorWrapper = new Wrapper<>(); @@ -103,7 +101,7 @@ public class AttributeServlet extends AbstractValidationsServlet { buildAttributeFromString(data, attributesWrapper, errorWrapper); if (errorWrapper.isEmpty()) { - AttributeBusinessLogic businessLogic = getBusinessLogic(context, () -> AttributeBusinessLogic.class); + AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); Either createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId); if (createAttribute.isRight()) { errorWrapper.setInnerElement(createAttribute.right().value()); @@ -173,7 +171,7 @@ public class AttributeServlet extends AbstractValidationsServlet { buildAttributeFromString(data, attributesWrapper, errorWrapper); if (errorWrapper.isEmpty()) { - AttributeBusinessLogic businessLogic = getBusinessLogic(context, () -> AttributeBusinessLogic.class); + AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); Either eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId); // update property if (eitherUpdateAttribute.isRight()) { @@ -233,7 +231,7 @@ public class AttributeServlet extends AbstractValidationsServlet { try { // delete the property - AttributeBusinessLogic businessLogic = getBusinessLogic(context, () -> AttributeBusinessLogic.class); + AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); Either eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId); if (eitherAttribute.isRight()) { log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value()); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java index f21b57f6fb..2d5402f709 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java @@ -20,6 +20,7 @@ package org.openecomp.sdc.be.servlets; +import java.util.EnumMap; import java.util.Map; import java.util.Map.Entry; import java.util.function.Supplier; @@ -43,20 +44,28 @@ import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.VFComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.api.IElementDAO; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.externalapi.servlet.AssetMetadataConverter; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.config.EcompErrorName; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.servlets.BasicServlet; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; +import fj.data.Either; + public class BeGenericServlet extends BasicServlet { @Context @@ -64,11 +73,11 @@ public class BeGenericServlet extends BasicServlet { private static Logger log = LoggerFactory.getLogger(BeGenericServlet.class.getName()); - /******************** New error response mechanism **************/ - + /******************** New error response mechanism + * @param additionalParams **************/ + protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) { - Response response = Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); - return response; + return Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); } protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity) { @@ -96,43 +105,64 @@ public class BeGenericServlet extends BasicServlet { } /*******************************************************************************************************/ + protected Either getUser(final HttpServletRequest request, String userId) { + Either eitherCreator = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false); + if (eitherCreator.isRight()) { + log.info("createResource method - user is not listed. userId= {}", userId); + ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION); + User user = new User("", "", userId, "", null, null); + + getComponentsUtils().auditResource(errorResponse, user, null, "", "", AuditingActionEnum.CHECKOUT_RESOURCE, null); + return Either.right(errorResponse); + } + return Either.left(eitherCreator.left().value()); + + } protected UserBusinessLogic getUserAdminManager(ServletContext context) { - return getBusinessLogic(context, () -> UserBusinessLogic.class); + return getClassFromWebAppContext(context, () -> UserBusinessLogic.class); } protected ResourceBusinessLogic getResourceBL(ServletContext context) { - return getBusinessLogic(context, () -> ResourceBusinessLogic.class); + return getClassFromWebAppContext(context, () -> ResourceBusinessLogic.class); } protected ComponentsCleanBusinessLogic getComponentCleanerBL(ServletContext context) { - return getBusinessLogic(context, () -> ComponentsCleanBusinessLogic.class); + return getClassFromWebAppContext(context, () -> ComponentsCleanBusinessLogic.class); } protected ServiceBusinessLogic getServiceBL(ServletContext context) { - return getBusinessLogic(context, () -> ServiceBusinessLogic.class); + return getClassFromWebAppContext(context, () -> ServiceBusinessLogic.class); } protected ProductBusinessLogic getProductBL(ServletContext context) { - return getBusinessLogic(context, () -> ProductBusinessLogic.class); + return getClassFromWebAppContext(context, () -> ProductBusinessLogic.class); } protected ArtifactsBusinessLogic getArtifactBL(ServletContext context) { - return getBusinessLogic(context, () -> ArtifactsBusinessLogic.class); + return getClassFromWebAppContext(context, () -> ArtifactsBusinessLogic.class); } protected ElementBusinessLogic getElementBL(ServletContext context) { - return getBusinessLogic(context, () -> ElementBusinessLogic.class); + return getClassFromWebAppContext(context, () -> ElementBusinessLogic.class); } protected MonitoringBusinessLogic getMonitoringBL(ServletContext context) { - return getBusinessLogic(context, () -> MonitoringBusinessLogic.class); + return getClassFromWebAppContext(context, () -> MonitoringBusinessLogic.class); } - protected SomeBusinessLogic getBusinessLogic(ServletContext context, Supplier> businessLogicClassGen) { + protected AssetMetadataConverter getAssetUtils(ServletContext context) { + return getClassFromWebAppContext(context, () -> AssetMetadataConverter.class); + } + + protected LifecycleBusinessLogic getLifecycleBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> LifecycleBusinessLogic.class); + } + + protected SomeClass getClassFromWebAppContext(ServletContext context, Supplier> businessLogicClassGen) { WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - SomeBusinessLogic monitoringBusinessLogic = webApplicationContext.getBean(businessLogicClassGen.get()); + SomeClass monitoringBusinessLogic = webApplicationContext.getBean(businessLogicClassGen.get()); return monitoringBusinessLogic; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java index ffcd9c68fc..51b0a1dff7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java @@ -135,17 +135,17 @@ public class BeMonitoringServlet extends BeGenericServlet { @Path("/version") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "return the ASDC application version", notes = "return the SDC application version", response = String.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "return SDC version"), @ApiResponse(code = 500, message = "Internal Error") }) + @ApiOperation(value = "return the ASDC application version", notes = "return the ASDC application version", response = String.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "return ASDC version"), @ApiResponse(code = 500, message = "Internal Error") }) public Response getSdcVersion(@Context final HttpServletRequest request) { try { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("Start handle request of {}", url); String version = getVersionFromContext(request); - log.debug("sdc version from manifest is: {}", version); + log.debug("asdc version from manifest is: {}", version); if (version == null || version.isEmpty()) { - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.SDC_VERSION_NOT_FOUND)); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.ASDC_VERSION_NOT_FOUND)); } HealthCheckInfo versionInfo = new HealthCheckInfo(); @@ -158,14 +158,14 @@ public class BeMonitoringServlet extends BeGenericServlet { } catch (Exception e) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "getSDCVersion"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getSDCVersion"); - log.debug("BE get SDC version unexpected exception", e); + log.debug("BE get ASDC version unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } private String getVersionFromContext(HttpServletRequest request) { ServletContext servletContext = request.getSession().getServletContext(); - String version = (String) servletContext.getAttribute(Constants.SDC_RELEASE_VERSION_ATTR); + String version = (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR); return version; } @@ -187,7 +187,7 @@ public class BeMonitoringServlet extends BeGenericServlet { object = gson.fromJson(content, clazz); object.setFields(null); } catch (Exception e) { - log.debug("Failed to convert the content {} to object. {}", content.substring(0, Math.min(50, content.length())), e); + log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e); } return object; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java index 4e6d0bcd7f..6a7ecbb5fe 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java @@ -30,6 +30,7 @@ import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; +import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; @@ -43,19 +44,24 @@ import javax.ws.rs.core.Response; import org.apache.commons.io.IOUtils; import org.codehaus.jackson.map.ObjectMapper; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.info.CreateAndAssotiateInfo; +import org.openecomp.sdc.be.info.GroupDefinitionInfo; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceAttribute; +import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; @@ -75,6 +81,7 @@ import fj.data.Either; /** * Root resource (exposed at "/" path) + * .json */ @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @@ -118,7 +125,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value()); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Component Instance"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Component Instance"); log.debug("create component instance failed with exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -131,7 +137,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateComponentInstance(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, + public Response updateComponentInstanceMetadata(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, @Context final HttpServletRequest request) { @@ -164,14 +170,13 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { Either convertResponse = convertToResourceInstance(data); if (convertResponse.isRight()) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Resource Instance - updateResourceInstance"); BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance"); log.debug("Failed to convert received data to BE format."); return buildErrorResponse(convertResponse.right().value()); } ComponentInstance resourceInstance = convertResponse.left().value(); - Either actionResponse = componentInstanceLogic.updateComponentInstance(containerComponentType, componentId, componentInstanceId, userId, resourceInstance); + Either actionResponse = componentInstanceLogic.updateComponentInstanceMetadata(containerComponentType, componentId, componentInstanceId, userId, resourceInstance); if (actionResponse.isRight()) { return buildErrorResponse(actionResponse.right().value()); @@ -179,7 +184,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Resource Instance"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance"); log.debug("update resource instance with exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -284,7 +288,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } return response; } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Resource Instance"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource Instance"); log.debug("delete resource instance with exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -324,7 +327,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { Either resultOp; if (regInfoW.isRight()) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Resource Instance - associateRIToRI"); BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - associateRIToRI"); log.debug("Failed to convert received data to BE format."); resultOp = Either.right(regInfoW.right().value()); @@ -343,7 +345,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return response; } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Associate Resource Instance"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Associate Resource Instance"); log.debug("associate resource instance to another RI with exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -379,7 +380,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { Either regInfoW = convertToRequirementCapabilityRelDef(data); if (regInfoW.isRight()) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Resource Instance - dissociateRIFromRI"); BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - dissociateRIFromRI"); log.debug("Failed to convert received data to BE format."); return buildErrorResponse(regInfoW.right().value()); @@ -394,7 +394,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Dissociate Resource Instance"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Dissociate Resource Instance"); log.debug("dissociate resource instance from service failed with exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -441,7 +440,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { Either convertStatus = convertJsonToObject(data, CreateAndAssotiateInfo.class); if (convertStatus.isRight()) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Resource Instance - createAndAssociateRIToRI"); BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - createAndAssociateRIToRI"); log.debug("Failed to convert received data to BE format."); Either formattedResponse = Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value())); @@ -456,7 +454,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value()); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create and Associate Resource Instance"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create and Associate Resource Instance"); log.debug("create and associate RI failed with exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -517,8 +514,77 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); } catch (Exception e) { - log.error("create and associate RI failed with exception: ", e.getMessage()); - log.debug("create and associate RI failed with exception", e); + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/input") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateResourceInstanceInput(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + try { + Wrapper dataWrapper = new Wrapper<>(); + Wrapper errorWrapper = new Wrapper<>(); + Wrapper propertyWrapper = new Wrapper<>(); + + validateInputStream(request, dataWrapper, errorWrapper); + ComponentInstanceInput property = null; + + if (errorWrapper.isEmpty()) { + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Either inputEither = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataWrapper.getInnerElement(), modifier, ComponentInstanceInput.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.SERVICE);; + if(inputEither.isRight()){ + log.debug("Failed to convert data to input definition. Status is {}", inputEither.right().value()); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + property = inputEither.left().value(); + + } + + if (property == null) { + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + + log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property); + + ServletContext context = request.getSession().getServletContext(); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either actionResponse = componentInstanceLogic.createOrUpdateInstanceInputValue(componentTypeEnum, componentId, componentInstanceId, property, userId); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + + ComponentInstanceInput resourceInstanceProperty = actionResponse.left().value(); + ObjectMapper mapper = new ObjectMapper(); + String result = mapper.writeValueAsString(resourceInstanceProperty); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } @@ -580,8 +646,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildResponseFromElement(errorWrapper, attributeWrapper); } catch (Exception e) { - log.error("create and associate RI failed with exception: ", e.getMessage()); - log.debug("create and associate RI failed with exception", e); + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } @@ -617,8 +682,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); } catch (Exception e) { - log.error("create and associate RI failed with exception: ", e.getMessage()); - log.debug("create and associate RI failed with exception", e); + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } @@ -638,9 +702,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("Start handle request of {}", url); try { - - log.debug("Start handle request of {}", url); - InputStream inputStream = request.getInputStream(); byte[] bytes = IOUtils.toByteArray(inputStream); @@ -664,7 +725,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { Either convertResponse = convertToResourceInstance(data); if (convertResponse.isRight()) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Resource Instance - updateResourceInstance"); BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance"); log.debug("Failed to convert received data to BE format."); return buildErrorResponse(convertResponse.right().value()); @@ -679,14 +739,149 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Resource Instance"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance"); log.debug("update resource instance with exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}/property") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateGroupInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "group instance id") @PathParam("groupInstanceId") final String groupInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + try { + Wrapper dataWrapper = new Wrapper<>(); + Wrapper errorWrapper = new Wrapper<>(); + Wrapper propertyWrapper = new Wrapper<>(); + + validateInputStream(request, dataWrapper, errorWrapper); + if (errorWrapper.isEmpty()) { + validateClassParse(dataWrapper.getInnerElement(), propertyWrapper, () -> ComponentInstanceProperty.class, errorWrapper); + } + + if (!errorWrapper.isEmpty()) { + return buildErrorResponse(errorWrapper.getInnerElement()); + } + + ComponentInstanceProperty property = propertyWrapper.getInnerElement(); + + log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property); + + ServletContext context = request.getSession().getServletContext(); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either actionResponse = componentInstanceLogic.createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, componentInstanceId, groupInstanceId, property, userId); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + + ComponentInstanceProperty resourceInstanceProperty = actionResponse.left().value(); + ObjectMapper mapper = new ObjectMapper(); + String result = mapper.writeValueAsString(resourceInstanceProperty); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @GET + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupInstId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Group not found") }) + public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("groupInstId") final String groupInstId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET) Start handle request of {}", url); + + try { + + GroupBusinessLogic businessLogic = this.getGroupBL(context); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + Either actionResponse = businessLogic.getGroupInstWithArtifactsById(componentTypeEnum, componentId, componentInstanceId, groupInstId, userId, false); + + if (actionResponse.isRight()) { + log.debug("failed to get all non abstract {}", containerComponentType); + return buildErrorResponse(actionResponse.right().value()); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); + log.debug("getGroupArtifactById unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + //US831698 + @GET + @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get component instance properties", httpMethod = "GET", + notes = "Returns component instance properties", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Properties found"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Component/Component Instance - not found") }) + public Response getInstancePropertiesById(@PathParam("containerComponentType") final String containerComponentType, + @PathParam("containerComponentId") final String containerComponentId, + @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET) Start handle request of {}", url); + + try { + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum); + + Either, ResponseFormat> componentInstancePropertiesById = componentInstanceBL + .getComponentInstancePropertiesById(containerComponentType, containerComponentId, + componentInstanceUniqueId, userId); + + if (componentInstancePropertiesById.isRight()) { + log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}", + componentInstanceUniqueId, containerComponentType, containerComponentId); + return buildErrorResponse(componentInstancePropertiesById.right().value()); + } + + return buildOkResponse(getComponentsUtils(). + getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); + log.debug("getGroupArtifactById unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + private Either convertToResourceInstance(String data) { // Either convertStatus = @@ -700,7 +895,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return Either.left(resourceInstanceInfo); } - // TODO Tal New API for Multiple Items move on canvas private Either, ResponseFormat> convertToMultipleResourceInstance(String dataList) { Either convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstance[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE); @@ -723,11 +917,10 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { private Either convertJsonToObject(String data, Class clazz) { try { - log.trace("convert json to object. json=\n{}", data); + log.trace("convert json to object. json=\n {}", data); T t = null; t = gson.fromJson(data, clazz); if (t == null) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject"); BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); log.debug("object is null after converting from json"); return Either.right(ActionStatus.INVALID_CONTENT); @@ -735,7 +928,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return Either.left(t); } catch (Exception e) { // INVALID JSON - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject"); BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); log.debug("failed to convert from json", e); return Either.right(ActionStatus.INVALID_CONTENT); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java index c5bebb41bf..b28700ace4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java @@ -20,6 +20,11 @@ package org.openecomp.sdc.be.servlets; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.EnumMap; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -38,15 +43,27 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.apache.commons.collections.CollectionUtils; +import org.codehaus.jackson.JsonGenerationException; +import org.codehaus.jackson.map.JsonMappingException; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum; +import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; import org.openecomp.sdc.be.model.CapReqDef; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement; +import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.ComponentMetadataData; +import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.exception.ResponseFormat; @@ -70,12 +87,12 @@ public class ComponentServlet extends BeGenericServlet { private static Logger log = LoggerFactory.getLogger(ComponentServlet.class.getName()); @GET - @Path("/{componentType}/{componentId}/requirmentsCapabilities") + @Path("/{componentType}/{componentId}/conformanceLevelValidation") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class) + @ApiOperation(value = "Validate Component Conformance Level", httpMethod = "GET", notes = "Returns the result according to conformance level in BE config", response = Resource.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getRequirementAndCapabilities(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, + public Response conformanceLevelValidation(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { Response response; ServletContext context = request.getSession().getServletContext(); @@ -86,11 +103,11 @@ public class ComponentServlet extends BeGenericServlet { ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); if (componentTypeEnum != null) { ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context); - Either eitherRequirementsAndCapabilities = compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId); - if (eitherRequirementsAndCapabilities.isRight()) { - response = buildErrorResponse(eitherRequirementsAndCapabilities.right().value()); + Either eitherConformanceLevel = compBL.validateConformanceLevel(componentId, componentTypeEnum, userId); + if (eitherConformanceLevel.isRight()) { + response = buildErrorResponse(eitherConformanceLevel.right().value()); } else { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), gson.toJson(eitherRequirementsAndCapabilities.left().value())); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), gson.toJson(eitherConformanceLevel.left().value())); } } else { response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); @@ -98,6 +115,42 @@ public class ComponentServlet extends BeGenericServlet { return response; } + + @GET + @Path("/{componentType}/{componentId}/requirmentsCapabilities") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getRequirementAndCapabilities(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + Response response; + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + if (componentTypeEnum != null) { + try { + ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context); + Either eitherRequirementsAndCapabilities = compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId); + if (eitherRequirementsAndCapabilities.isRight()) { + response = buildErrorResponse(eitherRequirementsAndCapabilities.right().value()); + } else { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(eitherRequirementsAndCapabilities.left().value())); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capabilities and requirements for " + componentId); + log.debug("getRequirementAndCapabilities failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } else { + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + return response; + } @GET @Path("/{componentType}/latestversion/notabstract") @@ -119,7 +172,7 @@ public class ComponentServlet extends BeGenericServlet { ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); - log.debug("Received componentUids size is {}", (componentUids == null ? 0 : componentUids.size())); + log.debug("Received componentUids size is {}", componentUids == null ? 0 : componentUids.size()); Either, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, componentUids, userId); @@ -131,7 +184,6 @@ public class ComponentServlet extends BeGenericServlet { return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Certified Non Abstract" + componentType); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType); log.debug("getCertifiedNotAbstractComponents failed with exception", e); response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -153,8 +205,7 @@ public class ComponentServlet extends BeGenericServlet { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - if (log.isDebugEnabled()) - log.debug("(get) Start handle request of {}", url); + log.debug("(GET) Start handle request of {}", url); Response response = null; try { @@ -165,12 +216,8 @@ public class ComponentServlet extends BeGenericServlet { if (log.isDebugEnabled()) log.debug("Received componentUids size is {}", (componentUids == null ? 0 : componentUids.size())); - // long start = System.currentTimeMillis(); - Either, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, componentUids, userId); - // long endBl = System.currentTimeMillis(); - if (actionResponse.isRight()) { if (log.isDebugEnabled()) log.debug("failed to get all non abstract {}", componentType); @@ -180,15 +227,9 @@ public class ComponentServlet extends BeGenericServlet { Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); Response responseToReturn = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); - long endResp = System.currentTimeMillis(); - - // log.info("********** Time calculation in ms: BL {} , Response {}, - // Total {}", (endBl - start ), (endResp - endBl), (endResp - - // start)); return responseToReturn; } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Certified Non Abstract" + componentType); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType); log.debug("getCertifiedNotAbstractComponents failed with exception", e); response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -199,7 +240,7 @@ public class ComponentServlet extends BeGenericServlet { } @GET - @Path("/{componentType}/latestversion/notabstract/uidonly") + @Path("/{componentType}/latestversion/notabstract/metadata") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Get Component uid only", httpMethod = "GET", notes = "Returns componentId", response = Resource.class) @@ -215,7 +256,7 @@ public class ComponentServlet extends BeGenericServlet { ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); - Either>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponentsUidOnly(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, userId); + Either, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponentsMetadata(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, userId); if (actionResponse.isRight()) { log.debug("failed to get all non abstract {}", componentType); return buildErrorResponse(actionResponse.right().value()); @@ -224,7 +265,6 @@ public class ComponentServlet extends BeGenericServlet { return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Certified Non Abstract" + componentType); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType); log.debug("getCertifiedNotAbstractComponents failed with exception", e); response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -241,11 +281,11 @@ public class ComponentServlet extends BeGenericServlet { @ApiOperation(value = "Get Component instances", httpMethod = "GET", notes = "Returns component instances", response = Resource.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) public Response getComponentInstancesFilteredByPropertiesAndInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, - @QueryParam("searchText") String searchText, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid" + "" + "list", required = true) String data) { + @QueryParam("searchText") String searchText, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid" + " " + "list", required = true) String data) { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); + log.debug("(GET) Start handle request of {}", url); Response response = null; try { ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); @@ -253,18 +293,122 @@ public class ComponentServlet extends BeGenericServlet { Either, ResponseFormat> actionResponse = businessLogic.getComponentInstancesFilteredByPropertiesAndInputs(componentId, componentTypeEnum, userId, searchText); if (actionResponse.isRight()) { - log.debug("failed to get all component instances filtered by properties and inputs {}", componentType); + log.debug("failed to get all component instances filtered by properties and inputs", componentType); return buildErrorResponse(actionResponse.right().value()); } Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Instances filtered by properties & inputs" + componentType); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Instances filtered by properties & inputs" + componentType); log.debug("getComponentInstancesFilteredByPropertiesAndInputs failed with exception", e); response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); return response; } } + + + + /** + * This API is a generic api for ui - the api get a list of strings and return the data on the component according to to list. + * for example: list of the string "properties, inputs" will return component with the list of properties and inputs. + * + * @param componentType + * @param componentId + * @param dataParamsToReturn + * @param request + * @param userId + * @return + */ + + @GET + @Path("/{componentType}/{componentId}/filteredDataByParams") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Resource", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") }) + public Response getComponentDataFilteredByParams(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @QueryParam("include") final List dataParamsToReturn, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}" , userId); + + Response response = null; + + try { + String resourceIdLower = componentId.toLowerCase(); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); + + log.trace("get component with id {} filtered by ui params", componentId); + Either actionResponse = businessLogic.getComponentDataFilteredByParams(resourceIdLower, modifier, dataParamsToReturn); + + if (actionResponse.isRight()) { + log.debug("failed to get component data filtered by ui params"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get component filtered by ui params"); + log.debug("get resource failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + + @GET + @Path("/{componentType}/{componentId}/filteredproperties/{propertyNameFragment}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve properties belonging to component instances of specific component by name and optionally resource type", httpMethod = "GET", notes = "Returns properties belonging to component instances of specific component by name and optionally resource type", response = Map.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getFilteredComponentInstanceProperties( + @PathParam("componentType") final String componentType, + @PathParam("componentId") final String componentId, + @PathParam("propertyNameFragment") final String propertyNameFragment, + @QueryParam("resourceType") List resourceTypes, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + User user = new User(); + user.setUserId(userId); + log.debug("User Id is {}" , userId); + Response response = null; + try { + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); + Map> filters = new EnumMap<>(FilterKeyEnum.class); + List propertyNameFragments = new ArrayList<>(); + propertyNameFragments.add(propertyNameFragment); + filters.put(FilterKeyEnum.NAME_FRAGMENT, propertyNameFragments); + if(CollectionUtils.isNotEmpty(resourceTypes)){ + filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypes); + } + Either>, ResponseFormat> actionResponse = businessLogic.getFilteredComponentInstanceProperties(componentId, filters, userId); + if (actionResponse.isRight()) { + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Filtered Component Instance Properties"); + log.debug("Getting of filtered component instance properties failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java index 2a3a87d942..79202ac94f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java @@ -63,9 +63,7 @@ public class ConfigServlet extends BasicServlet { log.warn("Configuration of type {} was not found", Configuration.class); } log.debug("{}", configuration); - if (log.isInfoEnabled()) { - log.debug("Info level ENABLED..."); - } + log.info("Info level ENABLED..."); log.info("The value returned from getConfig is {}", configuration); result = gson.toJson(configuration); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java index 0603f267ab..5e9056ba75 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java @@ -204,7 +204,7 @@ public class ConsumerServlet extends BeGenericServlet { ConsumerDefinition consumer = null; Gson gson = new Gson(); try { - log.trace("convert json to object. json=\n{}", data); + log.trace("convert json to object. json=\n {}", data); consumer = gson.fromJson(data, ConsumerDefinition.class); if (consumer == null) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject"); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java index 4ba6b7516d..4f8bffa066 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java @@ -90,77 +90,6 @@ public class CsarBuildServlet extends ToscaDaoServlet { */ public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta"; - // protected void addToscaMetaToZip(ZipOutputStream zipOutputStream, - // TopologyService topService, IResourceUploader resUploader) throws - // IOException { - // String serviceVersion = topService.getTopologyVersion(); - // String serviceName = topService.getTopologyName(); - // StringBuffer buff = new StringBuffer(); - // - // String[] serviceToscaMeta = prepareToscaMetaHeader(serviceName); - // - // for( String toAppend : serviceToscaMeta){ - // buff.append(toAppend); - // } - // - // List toscaMetaComponents = - // prepareToscaMetaComponents(topService.getDependenciesYamls().keySet()); - // for( String toAppend : toscaMetaComponents ){ - // buff.append(toAppend); - // } - // - // Either - // getServiceArtifactsCollectionStatus = - // Either.right(ResourceUploadStatus.ERROR);//resUploader.getServiceArtifactsCollection(serviceName, - // serviceVersion); - // if(getServiceArtifactsCollectionStatus.isLeft()){ - // List toscaMetaArtifacts = - // prepareToscaMetaArtifacts(getServiceArtifactsCollectionStatus.left().value()); - // for( String toAppend : toscaMetaArtifacts ){ - // buff.append(toAppend); - // } - // } - // - // addZipEntry(zipOutputStream, TOSCA_META_PATH, buff.toString()); - // } - - // protected List prepareToscaMetaArtifacts( - // ServiceArtifactsDataCollection serviceArtifactsDataCollection) { - // List artifactsForToscaMeta = new ArrayList(); - // Iterator>> nodeTemplateArtifactsItr = - // serviceArtifactsDataCollection.getServiceArtifactDataMap().entrySet().iterator(); - // while( nodeTemplateArtifactsItr.hasNext() ){ - // Entry> nodeNameArtifacts = - // nodeTemplateArtifactsItr.next(); - // String nodeName = nodeNameArtifacts.getKey(); - // Iterator artifactDataItr = - // nodeNameArtifacts.getValue().iterator(); - // while( artifactDataItr.hasNext() ){ - // ArtifactData artifactData = artifactDataItr.next(); - // artifactsForToscaMeta.add("\n"); - // artifactsForToscaMeta.add("Name: "+getArtifactPath(nodeName, - // artifactData)+"\n"); - // artifactsForToscaMeta.add("Content-Type: - // application/"+getAppliactionMime(artifactData.getArtifactName())+"\n"); - // } - // } - // return artifactsForToscaMeta; - // } - - // protected List prepareToscaMetaComponents(Set components) - // { - // Iterator resourceNameItr = components.iterator(); - // List componentsForToscaMeta = new ArrayList(); - // while( resourceNameItr.hasNext() ){ - // String resourceName = resourceNameItr.next(); - // componentsForToscaMeta.add("\n"); - // componentsForToscaMeta.add("Name: "+getResourcePath(resourceName)+"\n"); - // componentsForToscaMeta.add("Content-Type: - // application/vnd.oasis.tosca.definitions.yaml\n"); - // - // } - // return componentsForToscaMeta; - // } protected String[] prepareToscaMetaHeader(String serviceName) { return new String[] { "TOSCA-Meta-File-Version: 1.0\n", "CSAR-Version: 1.1\n", "Created-By: INTERWISE\n", "\n", "Entry-Definitions: Definitions/" + serviceName + ".yaml\n", "\n", "Name: Definitions/" + serviceName + ".yaml\n", @@ -198,17 +127,6 @@ public class CsarBuildServlet extends ToscaDaoServlet { return mimeType; } - // protected void addResourcesToZip(ZipOutputStream zipOutputStream, - // TopologyService topService) throws IOException { - // Iterator> resourceNameDataItr = - // topService.getDependenciesYamls().entrySet().iterator(); - // while( resourceNameDataItr.hasNext() ){ - // Entry resourceNameData = resourceNameDataItr.next(); - // addZipEntry(zipOutputStream, getResourcePath(resourceNameData.getKey()), - // resourceNameData.getValue()); - // } - // } - protected String getArtifactPath(String nodeTamplateName, ESArtifactData artifactData) { // return "Scripts/"+nodeTamplateName+"/"+ // artifactData.getArtifactName(); @@ -219,57 +137,6 @@ public class CsarBuildServlet extends ToscaDaoServlet { return "Definitions/" + resourceName + ".yaml"; } - // protected void addArtifactsToZip(String serviceName, String - // serviceVersion, ZipOutputStream zipOutputStream, IResourceUploader - // resourceUploader) - // throws IOException { - // //Add Artifacts to Zip - // Either - // getServiceArtifactsCollectionStatus = - // Either.right(ResourceUploadStatus.ERROR);//resourceUploader.getServiceArtifactsCollection(serviceName, - // serviceVersion); - // if(getServiceArtifactsCollectionStatus.isLeft()){ - // Iterator>> nodeTemplateArtifactsItr - // =getServiceArtifactsCollectionStatus.left().value().getServiceArtifactDataMap().entrySet().iterator(); - // while( nodeTemplateArtifactsItr.hasNext() ){ - // Entry> nodeTemplateArtifacts = - // nodeTemplateArtifactsItr.next(); - // String nodeTamplateName = nodeTemplateArtifacts.getKey(); - // List artifacts = nodeTemplateArtifacts.getValue(); - // for(ArtifactData artifactData : artifacts ){ - // addZipEntry(zipOutputStream, - // getArtifactPath(nodeTamplateName,artifactData), artifactData.getData()); - // } - // - // } - // } - // } - - // private Response buildResponse(String fileName, ByteArrayOutputStream - // fileOutputStream) { - // final InputStream inputStream = new - // ByteArrayInputStream(fileOutputStream.toByteArray()); - // - // StreamingOutput stream = new StreamingOutput() { - // public void write(OutputStream output) throws WebApplicationException { - // try { - // IOUtils.copy(inputStream, output); - // } catch (Exception e) { - // throw new WebApplicationException(e); - // } - // } - // }; - // - // return - // Response.ok(stream).type(MediaType.APPLICATION_OCTET_STREAM_TYPE).header("content-disposition","attachment; - // filename = "+fileName).build(); - // } - - // protected void addZipEntry(ZipOutputStream zipOutputStream, String - // filePath, String data) throws IOException { - // addZipEntry(zipOutputStream, filePath, encodeString(data)); - // } - private byte[] encodeString(String data) throws CharacterCodingException { Charset charset = Charset.forName("UTF-8"); CharsetEncoder encoder = charset.newEncoder(); @@ -279,15 +146,6 @@ public class CsarBuildServlet extends ToscaDaoServlet { return ba; } - // private void addZipEntry(ZipOutputStream zipOutputStream, String - // filePath, byte[] data) throws IOException { - // log.debug("Adding to CSAR zip :{}", filePath); - // ZipEntry entry = new ZipEntry(filePath); - // zipOutputStream.putNextEntry(entry); - // zipOutputStream.write(data); - // zipOutputStream.closeEntry(); - // } - @Override public Logger getLogger() { return log; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java index 433a1bfc58..576fc29014 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java @@ -57,6 +57,7 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.GroupingDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.be.ui.model.UiCategories; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.config.EcompErrorName; @@ -126,6 +127,33 @@ public class ElementServlet extends BeGenericServlet { return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } + + @GET + @Path("/categories") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve the all resource, service and product categories", httpMethod = "GET", notes = "Retrieve the all resource, service and product categories", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns categories Ok"), @ApiResponse(code = 403, message = "Missing information"), + @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getAllCategories(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either either = elementBL.getAllCategories(userId); + if (either.isRight()) { + log.debug("No categories were found"); + return buildErrorResponse(either.right().value()); + } else { + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get All Categories"); + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Categories"); + log.debug("getAllCategories failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + @POST @Path("/category/{componentType}") @@ -388,7 +416,7 @@ public class ElementServlet extends BeGenericServlet { @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns artifactTypes Ok"), @ApiResponse(code = 404, message = "No artifactTypes were found"), @ApiResponse(code = 500, message = "Internal Server Error") }) public Response getArtifactTypes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(getArtifactTypes) Start handle request of {}", url); + log.debug("(GET - getArtifactTypes) Start handle request of {}", url); try { ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); @@ -568,7 +596,7 @@ public class ElementServlet extends BeGenericServlet { NodeTypeEnum nodeType = NodeTypeEnum.getByNameIgnoreCase(componentType); if (nodeType == null) { - log.info("componentType is not valid: {}", componentType); + log.info("componentType is not valid: {]", componentType); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java index bde8f93929..32fd06a2a8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java @@ -20,6 +20,8 @@ package org.openecomp.sdc.be.servlets; +import java.util.List; + import javax.inject.Singleton; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; @@ -40,6 +42,7 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.info.GroupDefinitionInfo; import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupProperty; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.common.api.Constants; @@ -48,8 +51,8 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.google.common.reflect.TypeToken; import com.google.gson.Gson; -import com.google.gson.GsonBuilder; import com.jcabi.aspects.Loggable; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; @@ -77,29 +80,33 @@ public class GroupServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Group not found") }) - public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Group not found") }) + public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(get) Start handle request of {}", url); - Response response = null; try { GroupBusinessLogic businessLogic = this.getGroupBL(context); ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - Either actionResponse = businessLogic.getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false); + Either actionResponse = businessLogic + .getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false); if (actionResponse.isRight()) { log.debug("failed to get all non abstract {}", containerComponentType); return buildErrorResponse(actionResponse.right().value()); } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), + actionResponse.left().value()); } catch (Throwable e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "getGroupArtifactById"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); log.debug("getGroupArtifactById unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -112,9 +119,15 @@ public class GroupServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Update Group Metadata", httpMethod = "PUT", notes = "Returns updated group definition", response = GroupDefinition.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateGroupMetadata(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId, - @ApiParam(value = "Service object to be Updated", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Updated"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateGroupMetadata( + @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId, + @ApiParam(value = "Service object to be Updated", required = true) String data, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); @@ -129,7 +142,7 @@ public class GroupServlet extends AbstractValidationsServlet { try { GroupBusinessLogic businessLogic = getGroupBL(context); - Either convertResponse = parseToGroup(data); + Either convertResponse = parseToObject(data, () -> GroupDefinition.class); if (convertResponse.isRight()) { log.debug("failed to parse group"); response = buildErrorResponse(convertResponse.right().value()); @@ -139,7 +152,8 @@ public class GroupServlet extends AbstractValidationsServlet { // Update GroupDefinition ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - Either actionResponse = businessLogic.updateGroupMetadata(componentId, user, groupUniqueId, componentTypeEnum, updatedGroup, true); + Either actionResponse = businessLogic + .validateAndUpdateGroupMetadata(componentId, user, componentTypeEnum, updatedGroup, true); if (actionResponse.isRight()) { log.debug("failed to update GroupDefinition"); @@ -152,7 +166,6 @@ public class GroupServlet extends AbstractValidationsServlet { return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Group Metadata"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Metadata"); log.debug("update group metadata failed with exception", e); response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -162,20 +175,74 @@ public class GroupServlet extends AbstractValidationsServlet { } /** - * Convert data to GroupDefinition object - * - * @param groupJson + * Updates List of properties on a group (only values) + * @param containerComponentType + * @param componentId + * @param groupUniqueId + * @param data + * @param request + * @param userId * @return */ - public Either parseToGroup(String groupJson) { + @PUT + @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Updates List of properties on a group (only values)", httpMethod = "PUT", notes = "Returns updated list of properties", response = GroupDefinition.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Updated"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateGroupProperties(@PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId, + @ApiParam(value = "Service object to be Updated", required = true) String data, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + init(log); + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User user = new User(); + user.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - GroupDefinition groupDefinition = gson.fromJson(groupJson, GroupDefinition.class); - return Either.left(groupDefinition); + GroupBusinessLogic businessLogic = getGroupBL(context); + Either, ResponseFormat> convertResponse = parseListOfObjects(data, + new TypeToken>() { + }.getType()); + + if (convertResponse.isRight()) { + log.debug("failed to parse group Property"); + response = buildErrorResponse(convertResponse.right().value()); + return response; + } + List groupPropertyToUpdate = convertResponse.left().value(); + + // Update GroupDefinition + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + Either, ResponseFormat> actionResponse = businessLogic.validateAndUpdateGroupProperties( + componentId, groupUniqueId, user, componentTypeEnum, groupPropertyToUpdate, false); + + if (actionResponse.isRight()) { + log.debug("failed to update GroupDefinition"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + List groupProperty = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(groupProperty); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + } catch (Exception e) { - log.debug("Failed to parse json (group data) to GroupDefinition object"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - return Either.right(responseFormat); + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Properties"); + log.debug("update group properties failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java index e835c43e14..580b2bdb8b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java @@ -30,6 +30,7 @@ import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; +import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; @@ -38,6 +39,8 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.codehaus.jackson.map.ObjectMapper; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.InputsBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -52,6 +55,7 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.config.EcompErrorName; +import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -70,7 +74,7 @@ import fj.data.Either; @Path("/v1/catalog") @Api(value = "Input Catalog", description = "Input Servlet") @Singleton -public class InputsServlet extends BeGenericServlet { +public class InputsServlet extends AbstractValidationsServlet { private static Logger log = LoggerFactory.getLogger(ProductServlet.class.getName()); @@ -102,22 +106,80 @@ public class InputsServlet extends BeGenericServlet { } catch (Exception e) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Instance Inputs" + componentType); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs" + componentType); + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType); log.debug("getInputs failed with exception", e); response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); return response; } } + + + @POST + @Path("/{containerComponentType}/{componentId}/update/inputs") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource inputs", httpMethod = "POST", notes = "Returns updated input", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Input updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateComponentInputs( + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, + @ApiParam(value = "json describe the input", required = true) String data, @Context final HttpServletRequest request) { + + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + String userId = request.getHeader(Constants.USER_ID_HEADER); + + try { + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Either inputEither = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, modifier, InputDefinition.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.SERVICE);; + if(inputEither.isRight()){ + log.debug("Failed to convert data to input definition. Status is {}", inputEither.right().value()); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + InputDefinition input = inputEither.left().value(); + + log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", input); + + ServletContext context = request.getSession().getServletContext(); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(containerComponentType); + + InputsBusinessLogic businessLogic = getInputBL(context); + if (businessLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR)); + } + + Either actionResponse = businessLogic.updateInputValue(componentType, componentId, input, userId, true, false); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + + InputDefinition resourceInstanceProperty = actionResponse.left().value(); + ObjectMapper mapper = new ObjectMapper(); + String result = mapper.writeValueAsString(resourceInstanceProperty); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + @GET - @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComonentUid}/inputs") + @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/inputs") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Get Inputs only", httpMethod = "GET", notes = "Returns Inputs list", response = Resource.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) public Response getComponentInstanceInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId, - @PathParam("originComonentUid") final String originComonentUid, @Context final HttpServletRequest request, @QueryParam("fromName") String fromName, @QueryParam("amount") int amount, + @PathParam("originComponentUid") final String originComonentUid, @Context final HttpServletRequest request, @QueryParam("fromName") String fromName, @QueryParam("amount") int amount, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { ServletContext context = request.getSession().getServletContext(); @@ -128,7 +190,7 @@ public class InputsServlet extends BeGenericServlet { try { InputsBusinessLogic businessLogic = getInputBL(context); - Either, ResponseFormat> inputsResponse = businessLogic.getInputs(userId, originComonentUid, fromName, amount); + Either, ResponseFormat> inputsResponse = businessLogic.getComponentInstanceInputs(userId, componentId, instanceId, fromName, amount); if (inputsResponse.isRight()) { log.debug("failed to get component instance inputs {}", componentType); return buildErrorResponse(inputsResponse.right().value()); @@ -138,7 +200,7 @@ public class InputsServlet extends BeGenericServlet { } catch (Exception e) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Instance Inputs" + componentType); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs" + componentType); + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType); log.debug("getInputs failed with exception", e); response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); return response; @@ -157,13 +219,13 @@ public class InputsServlet extends BeGenericServlet { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); + log.debug("(GET) Start handle request of {}", url); Response response = null; try { InputsBusinessLogic businessLogic = getInputBL(context); - Either, ResponseFormat> inputPropertiesRes = businessLogic.getComponentInstancePropertiesByInputId(userId, instanceId, inputId); + Either, ResponseFormat> inputPropertiesRes = businessLogic.getComponentInstancePropertiesByInputId(userId, componentId, instanceId, inputId); if (inputPropertiesRes.isRight()) { log.debug("failed to get properties of input: {}, with instance id: {}", inputId, instanceId); return buildErrorResponse(inputPropertiesRes.right().value()); @@ -199,6 +261,43 @@ public class InputsServlet extends BeGenericServlet { InputsBusinessLogic businessLogic = getInputBL(context); Either, ResponseFormat> inputsRes = businessLogic.getInputsForComponentInput(userId, componentId, inputId); + + if (inputsRes.isRight()) { + log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId); + return buildErrorResponse(inputsRes.right().value()); + } + Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get inputs by input id {}, for component {} ", inputId, componentId); + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId); + log.debug("getInputsForComponentInput failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @GET + @Path("/{componentType}/{componentId}/inputs/{inputId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getInputsAndPropertiesForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + Response response = null; + + try { + InputsBusinessLogic businessLogic = getInputBL(context); + + Either inputsRes = businessLogic.getInputsAndPropertiesForComponentInput(userId, componentId, inputId, false); + if (inputsRes.isRight()) { log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId); return buildErrorResponse(inputsRes.right().value()); @@ -270,6 +369,8 @@ public class InputsServlet extends BeGenericServlet { } } + + @DELETE @Path("/{componentType}/{componentId}/delete/{inputId}/input") @Consumes(MediaType.APPLICATION_JSON) @@ -291,14 +392,13 @@ public class InputsServlet extends BeGenericServlet { try { InputsBusinessLogic businessLogic = getInputBL(context); - Either deleteInput = businessLogic.deleteInput(componentType, componentId, userId, inputId, true); + Either deleteInput = businessLogic.deleteInput(componentType, componentId, userId, inputId); if (deleteInput.isRight()){ ResponseFormat deleteResponseFormat = deleteInput.right().value(); response = buildErrorResponse(deleteResponseFormat); return response; } - InputDefinition inputDefinition = deleteInput.left().value(); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), inputDefinition); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput.left().value()); } catch (Exception e){ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete input for service {} with id: {}", componentId, inputId); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId); @@ -308,7 +408,46 @@ public class InputsServlet extends BeGenericServlet { } } + + + + /*@PUT + @Path("/{componentType}/{componentId}/edit/{inputId}/input") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete input from service", httpMethod = "DELETE", notes = "Delete service input", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Input deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Input not found") }) + public Response editInputValue ( + @PathParam("componentType") final String componentType, + @PathParam("componentId") final String componentId, + @PathParam("inputId") final String inputId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + Response response = null; + try { + InputsBusinessLogic businessLogic = getInputBL(context); + Either deleteInput = businessLogic.deleteInput(componentType, componentId, userId, inputId); + if (deleteInput.isRight()){ + ResponseFormat deleteResponseFormat = deleteInput.right().value(); + response = buildErrorResponse(deleteResponseFormat); + return response; + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput.left().value()); + } catch (Exception e){ + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete input for service {} with id: {}", componentId, inputId); + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId); + log.debug("Delete input failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + }*/ + protected InputsBusinessLogic getInputBL(ServletContext context) { WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java index 3f8bfd9149..019a6ba8fd 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java @@ -40,7 +40,6 @@ import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; import org.openecomp.sdc.be.model.User; @@ -50,7 +49,6 @@ import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.web.context.WebApplicationContext; import com.jcabi.aspects.Loggable; import com.wordnik.swagger.annotations.Api; @@ -92,9 +90,9 @@ public class LifecycleServlet extends BeGenericServlet { // get modifier from graph log.debug("get modifier properties"); - Either eitherGetUser = getUser(request, userId); + Either eitherGetUser = getUser(request, userId); if (eitherGetUser.isRight()) { - return eitherGetUser.right().value(); + return buildErrorResponse(eitherGetUser.right().value()); } User user = eitherGetUser.left().value(); @@ -130,27 +128,6 @@ public class LifecycleServlet extends BeGenericServlet { try { LifeCycleTransitionEnum transitionEnum = validateEnum.left().value(); ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection); - // if (componentType == ComponentTypeEnum.RESOURCE){ - // Either actionResponse = - // businessLogic.changeState(resourceIdLower, user, transitionEnum, - // changeInfo, false); - // - // if (actionResponse.isRight()){ - // log.info("failed to change resource state"); - // response = buildErrorResponse(actionResponse.right().value()); - // return response; - // } - // - // log.debug("change state successful !!!"); - // Object resource = - // RepresentationUtils.toRepresentation(actionResponse.left().value()); - // response = - // buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - // resource); - // return response; - // - // } else if (componentType == ComponentTypeEnum.SERVICE || - // componentType == ComponentTypeEnum.PRODUCT){ if (componentType != null) { Either actionResponse = businessLogic.changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true); @@ -192,25 +169,25 @@ public class LifecycleServlet extends BeGenericServlet { return Either.left(transitionEnum); } - private LifecycleBusinessLogic getLifecycleBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - LifecycleBusinessLogic resourceBl = webApplicationContext.getBean(LifecycleBusinessLogic.class); - return resourceBl; - } - - protected Either getUser(final HttpServletRequest request, String userId) { - - Either eitherCreator = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false); - if (eitherCreator.isRight()) { - log.info("createResource method - user is not listed. userId={}", userId); - ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION); - User user = new User("", "", userId, "", null, null); - - getComponentsUtils().auditResource(errorResponse, user, null, "", "", AuditingActionEnum.CHECKOUT_RESOURCE, null); - return Either.right(buildErrorResponse(errorResponse)); - } - return Either.left(eitherCreator.left().value()); - - } +// private LifecycleBusinessLogic getLifecycleBL(ServletContext context) { +// WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); +// WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); +// LifecycleBusinessLogic resourceBl = webApplicationContext.getBean(LifecycleBusinessLogic.class); +// return resourceBl; +// } +// +// protected Either getUser(final HttpServletRequest request, String userId) { +// +// Either eitherCreator = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false); +// if (eitherCreator.isRight()) { +// log.info("createResource method - user is not listed. userId= {}", userId); +// ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION); +// User user = new User("", "", userId, "", null, null); +// +// getComponentsUtils().auditResource(errorResponse, user, null, "", "", AuditingActionEnum.CHECKOUT_RESOURCE, null); +// return Either.right(buildErrorResponse(errorResponse)); +// } +// return Either.left(eitherCreator.left().value()); +// +// } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java index 2c693c71a8..df84e07b2c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java @@ -53,9 +53,9 @@ import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintSerialiser; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.resources.data.EntryData; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.config.EcompErrorName; @@ -97,13 +97,11 @@ public class PropertyServlet extends BeGenericServlet { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); - log.debug("data is {}", data); + log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data); try { // convert json to PropertyDefinition - Either, ActionStatus> either = getPropertyModel(data); + Either, ActionStatus> either = getPropertyModel(resourceId, data); if (either.isRight()) { ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value()); return buildErrorResponse(responseFormat); @@ -156,8 +154,7 @@ public class PropertyServlet extends BeGenericServlet { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); + log.debug("Start handle request of {}, modifier id is {}", url, userId); try { @@ -195,19 +192,18 @@ public class PropertyServlet extends BeGenericServlet { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); + log.debug("Start handle request of {} modifier id is {}", url, userId); try { // delete the property PropertyBusinessLogic businessLogic = getPropertyBL(context); - Either, ResponseFormat> status = businessLogic.deleteProperty(resourceId, propertyId, userId); + Either, ResponseFormat> status = businessLogic.deleteProperty(resourceId, propertyId, userId); if (status.isRight()) { log.debug("Failed to delete Property. Reason - ", status.right().value()); return buildErrorResponse(status.right().value()); } - EntryData property = status.left().value(); + Entry property = status.left().value(); String name = property.getKey(); PropertyDefinition propertyDefinition = property.getValue(); @@ -216,7 +212,6 @@ public class PropertyServlet extends BeGenericServlet { return buildOkResponse(responseFormat, propertyToJson(property)); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Property"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Property"); log.debug("delete property failed with exception", e); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); @@ -247,7 +242,7 @@ public class PropertyServlet extends BeGenericServlet { try { // convert json to PropertyDefinition - Either, ActionStatus> either = getPropertyModel(data); + Either, ActionStatus> either = getPropertyModel(resourceId, data); if (either.isRight()) { ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value()); return buildErrorResponse(responseFormat); @@ -285,54 +280,7 @@ public class PropertyServlet extends BeGenericServlet { } } - // private String propertyToJsonUi(Map.Entry - // property) { - // String name = property.getKey(); - // PropertyDefinition propertyDefinition = property.getValue(); - // JSONObject root = new JSONObject(); - // root.put("type", propertyDefinition.getType()); - // root.put("source", propertyDefinition.getDefaultValue()); - // root.put("name", name); - // root.put("description", propertyDefinition.getDescription()); - // root.put("uniqueId", propertyDefinition.getUniqueId()); - // return root.toString(); - // - // } - // - - // private Either getJsonModel(String data){ - // Either uiPropertyEither = getUiProperty(data); - // if (uiPropertyEither.isRight()){ - // log.error("Property conetnt is invalid - {}",data); - // return Either.right(ActionStatus.INVALID_CONTENT); - // } - // UiProperty uiProperty = uiPropertyEither.left().value(); - // String json = convertUiPropertyToJsonModel(uiProperty); - // return Either.left(json); - // } - // - - // private String convertUiPropertyToJsonModel(UiProperty uiProperty) { - // JSONObject root = new JSONObject(); - // JSONObject propertyD = new JSONObject(); - // propertyD.put("type",uiProperty.getType()); - // propertyD.put("required",false); - // propertyD.put("description",uiProperty.getDescription()); - // propertyD.put("isPassword",false); - // propertyD.put("defaultValue",uiProperty.getSource()); - // JSONArray jsonArr = new JSONArray(); - // JSONArray jsonR = new JSONArray(); - // jsonR.add(100); - // jsonR.add(500); - // JSONObject o = new JSONObject(); - // o.put("inRange", jsonR); - // jsonArr.add(o); - // propertyD.put("constraints",jsonArr); - // root.put(uiProperty.getName(), propertyD); - // return root.toString(); - // } - - private Either, ActionStatus> getPropertyModel(String data) { + private Either, ActionStatus> getPropertyModel(String resourceId, String data) { JSONParser parser = new JSONParser(); JSONObject root; try { @@ -353,7 +301,7 @@ public class PropertyServlet extends BeGenericServlet { PropertyDefinition propertyDefinition = convertJsonToObject.left().value(); // PropertyDefinition propertyDefinition = // gson.fromJson(jsonString , PropertyDefinition.class); - String uniqueId = UniqueIdBuilder.buildPropertyUniqueId("resourceId", (String) propertyName); + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, (String) propertyName); propertyDefinition.setUniqueId(uniqueId); properties.put(propertyName, propertyDefinition); } @@ -384,54 +332,7 @@ public class PropertyServlet extends BeGenericServlet { } } - // private Either,ActionStatus> - // getProperty(String data){ - // Type constraintType = new TypeToken() {}.getType(); - // PropertyConstraintDeserialiser propertyConstraintDeserialiser = new - // PropertyConstraintDeserialiser(); - // Gson gson = new - // GsonBuilder().registerTypeAdapter(constraintType,propertyConstraintDeserialiser).create(); - // JSONParser parser = new JSONParser(); - // JSONObject root; - // try { - // Map properties = new - // HashMap(); - // root = (JSONObject) parser.parse(data); - // Set keySet = root.keySet(); - // for (Object propertyName : keySet){ - // JSONObject val = (JSONObject) root.get(propertyName); - // String jsonString = val.toJSONString(); - // PropertyDefinition propertyDefinition = gson.fromJson(jsonString , - // PropertyDefinition.class); - // String uniqueId = UniqueIdBuilder.buildPropertyUniqueId("resourceId", - // (String)propertyName); - // propertyDefinition.setUniqueId(uniqueId); - // properties.put((String)propertyName,propertyDefinition); - // } - // return Either.left(properties); - // } catch (ParseException e) { - // log.error("Property conetnt is invalid - {}",data); - // return Either.right(ActionStatus.INVALID_CONTENT); - // } - // } - // - // private Either getUiProperty(String data) { - // try{ - // Gson gson = new Gson(); - // UiProperty uiProperty = gson.fromJson(data, UiProperty.class); - // return Either.left(uiProperty); - // }catch(JsonSyntaxException e){ - // log.warn("Problem create UiProperty from {}",data); - // log.debug("Problem create UiProperty from {}",data,e); - // return Either.right(ActionStatus.INVALID_CONTENT); - // } - // } - private String propertyToJson(Map.Entry property) { - // Type constraintType = new TypeToken() - // {}.getType(); - // Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new - // PropertyConstraintDeserialiser()).create(); JSONObject root = new JSONObject(); String propertyName = property.getKey(); PropertyDefinition propertyDefinition = property.getValue(); @@ -461,30 +362,13 @@ public class PropertyServlet extends BeGenericServlet { } - // private JSONObject getPropertyDefinitionJSONObject(PropertyDefinition - // propertyDefinition) { - // JSONObject root = new JSONObject(); - // root.put("type", propertyDefinition.getType()); - // root.put("required", propertyDefinition.isRequired()); - // root.put("defaultValue", propertyDefinition.getDefaultValue()); - // root.put("description", propertyDefinition.getDescription()); - // root.put("isPassword", propertyDefinition.isPassword()); - // List constraints = - // propertyDefinition.getConstraints(); - // for (PropertyConstraint p : constraints){ - // p.toString(); - // } - // root.put("constraints", propertyDefinition.getConstraints()); - // return root; - // } - private Either convertJsonToObject(String data, Class clazz) { T t = null; Type constraintType = new TypeToken() { }.getType(); Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); try { - log.trace("convert json to object. json=\n{}", data); + log.trace("convert json to object. json=\n {}", data); t = gson.fromJson(data, clazz); if (t == null) { log.info("object is null after converting from json"); @@ -504,7 +388,7 @@ public class PropertyServlet extends BeGenericServlet { }.getType(); Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintSerialiser()).create(); try { - log.trace("convert object to json. propertyDefinition={}", propertyDefinition.toString()); + log.trace("convert object to json. propertyDefinition= {}", propertyDefinition.toString()); String json = gson.toJson(propertyDefinition); if (json == null) { log.info("object is null after converting to json"); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java index 565911eaa9..5eed7eeb0d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java @@ -85,6 +85,7 @@ public class RepresentationUtils { JsonObject jsonElement = new JsonObject(); ArtifactDefinition resourceInfo = null; + try { Gson gson = new Gson(); jsonElement = gson.fromJson(content, jsonElement.getClass()); @@ -109,13 +110,19 @@ public class RepresentationUtils { payload = artifactPayload.getAsString(); } jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA); - resourceInfo = gson.fromJson(jsonElement, clazz); + String json = gson.toJson(jsonElement); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false); + mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); + + resourceInfo = mapper.readValue(json, clazz); resourceInfo.setPayloadData(payload); } catch (Exception e) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactInformationInvalidError, "Artifact Upload / Update"); BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update"); - log.debug("Failed to convert the content {} to object. {}", content.substring(0, Math.min(50, content.length())), e); + log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e); } return resourceInfo; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java index 673187b0a1..54ec6e3b15 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java @@ -56,41 +56,6 @@ public class ResourceArtifactDownloadServlet extends ToscaDaoServlet { private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - // @GET - // @Path("/{resourceName}/{resourceVersion}/artifacts") - // @Produces(MediaType.APPLICATION_JSON) - // public Response getResourceArtifactList(@PathParam("resourceName") final - // String resourceName, - // @PathParam("resourceVersion") final String resourceVersion, - // @Context final HttpServletRequest request){ - // - // - // String url = request.getMethod() + " " + request.getRequestURI(); - // log.info("Start handle request of {}", url); - // - // Response response = null; - // - // // get artifact list from dao - // IResourceUploader resourceDao = - // getResourceUploader(request.getSession().getServletContext()); - // if (resourceDao == null){ - // log.error("resource dao cannot be found"); - // response = buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, - // "Resource dao cannot be found"); - // return response; - // } - // Either, ResourceUploadStatus> getArtifactsStatus = - // resourceDao.getArtifacts(resourceName, resourceVersion); - // - // response = - // getLogic(request.getSession().getServletContext()).createArtifactListResponse(resourceName, - // getArtifactsStatus, getServletPath(request)); - // - // log.info("Finish handle request of {} | result = {}", url, response.getStatus() ); - // return response; - // - // } - @GET @Path("/{resourceName}/{resourceVersion}/artifacts/{artifactName}") // @Produces(MediaType.APPLICATION_OCTET_STREAM) @@ -118,7 +83,7 @@ public class ResourceArtifactDownloadServlet extends ToscaDaoServlet { } response = logic.downloadArtifact(resourceName, resourceVersion, artifactName, getArtifactStatus, artifactId); - log.info("Finish handle request of {} | result = {}", url, response.getStatus()); + log.info("Finish handle request of {} | result = {}", url, response.getStatus()); return response; } catch (Exception e) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java index 5cd765abe0..ef6ddb04ba 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java @@ -71,11 +71,12 @@ public class ResourceUploadServlet extends AbstractValidationsServlet { private static Logger log = LoggerFactory.getLogger(ResourceUploadServlet.class.getName()); public static final String NORMATIVE_TYPE_RESOURCE = "multipart"; + public static final String CSAR_TYPE_RESOURCE = "csar"; public static final String USER_TYPE_RESOURCE = "user-resource"; public static final String USER_TYPE_RESOURCE_UI_IMPORT = "user-resource-ui-import"; public enum ResourceAuthorityTypeEnum { - NORMATIVE_TYPE_BE(NORMATIVE_TYPE_RESOURCE, true, false), USER_TYPE_BE(USER_TYPE_RESOURCE, true, true), USER_TYPE_UI(USER_TYPE_RESOURCE_UI_IMPORT, false, true); + NORMATIVE_TYPE_BE(NORMATIVE_TYPE_RESOURCE, true, false), USER_TYPE_BE(USER_TYPE_RESOURCE, true, true), USER_TYPE_UI(USER_TYPE_RESOURCE_UI_IMPORT, false, true), CSAR_TYPE_BE(CSAR_TYPE_RESOURCE, true, true); private String urlPath; private boolean isBackEndImport, isUserTypeResource; @@ -150,9 +151,11 @@ public class ResourceUploadServlet extends AbstractValidationsServlet { fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, file); // PayLoad Validations - commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement()); + if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){ + commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement()); - specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum); + specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum); + } if (responseWrapper.isEmpty()) { handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, createNewVersion, null); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java index e3d39610a8..74d81ebd24 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java @@ -51,12 +51,10 @@ import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum; -import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.ResourceMetadataDefinition; import org.openecomp.sdc.be.model.UploadResourceInfo; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -100,7 +98,7 @@ public class ResourcesServlet extends AbstractValidationsServlet { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); // get modifier id User modifier = new User(); @@ -128,7 +126,7 @@ public class ResourcesServlet extends AbstractValidationsServlet { } Resource resource = convertResponse.left().value(); - Either actionResponse = businessLogic.createResource(resource, modifier, null, null); + Either actionResponse = businessLogic.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, modifier, null, null); if (actionResponse.isRight()) { log.debug("failed to create resource"); @@ -160,7 +158,7 @@ public class ResourcesServlet extends AbstractValidationsServlet { String payloadName = json.getString(ImportUtils.Constants.UI_JSON_PAYLOAD_NAME); isUIImport = payloadName != null && !payloadName.isEmpty(); } catch (Exception e) { - log.debug("failed to parse json sent from client, json:{}", data); + log.debug("failed to parse json sent from client, json:{}", data, e); isUIImport = false; } return isUIImport; @@ -177,8 +175,6 @@ public class ResourcesServlet extends AbstractValidationsServlet { commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString); - // TODO suspect next line is unnecessary - userWrapper.getInnerElement(); if (!CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) { fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, null); @@ -212,13 +208,13 @@ public class ResourcesServlet extends AbstractValidationsServlet { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); // get modifier id String userId = request.getHeader(Constants.USER_ID_HEADER); User modifier = new User(); modifier.setUserId(userId); - log.debug("modifier id is {}", userId); + log.debug("modifier id is {}" , userId); Response response = null; @@ -252,13 +248,13 @@ public class ResourcesServlet extends AbstractValidationsServlet { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); // get modifier id String userId = request.getHeader(Constants.USER_ID_HEADER); User modifier = new User(); modifier.setUserId(userId); - log.debug("modifier id is {}", userId); + log.debug("modifier id is {}" , userId); Response response = null; @@ -295,12 +291,12 @@ public class ResourcesServlet extends AbstractValidationsServlet { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); // get modifier id User modifier = new User(); modifier.setUserId(userId); - log.debug("modifier id is {}", userId); + log.debug("modifier id is {}" , userId); Response response = null; @@ -340,11 +336,11 @@ public class ResourcesServlet extends AbstractValidationsServlet { // get modifier id User modifier = new User(); modifier.setUserId(userId); - log.debug("modifier id is {}", userId); + log.debug("modifier id is {}" , userId); Response response = null; try { ResourceBusinessLogic businessLogic = getResourceBL(context); - Either, ResponseFormat> actionResponse = businessLogic.getResourceByNameAndVersion(resourceName, resourceVersion, userId); + Either actionResponse = businessLogic.getResourceByNameAndVersion(resourceName, resourceVersion, userId); if (actionResponse.isRight()) { response = buildErrorResponse(actionResponse.right().value()); return response; @@ -370,17 +366,17 @@ public class ResourcesServlet extends AbstractValidationsServlet { public Response validateResourceName(@PathParam("resourceName") final String resourceName, @QueryParam("subtype") String resourceType, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); // get modifier id User modifier = new User(); modifier.setUserId(userId); - log.debug("modifier id is {}", userId); + log.debug("modifier id is {}" , userId); Response response = null; try { ResourceBusinessLogic businessLogic = getResourceBL(context); - if (resourceType != null && !ResourceTypeEnum.contains(resourceType)) { + if (resourceType != null && !ResourceTypeEnum.containsName(resourceType)) { log.debug("invalid resource type received"); response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); return response; @@ -416,7 +412,7 @@ public class ResourcesServlet extends AbstractValidationsServlet { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); + log.debug("(get) Start handle request of {}" , url); Response response = null; try { @@ -452,7 +448,7 @@ public class ResourcesServlet extends AbstractValidationsServlet { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); + log.debug("(get) Start handle request of {}" , url); Response response = null; try { @@ -492,7 +488,7 @@ public class ResourcesServlet extends AbstractValidationsServlet { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); // get modifier id User modifier = new User(); @@ -510,8 +506,7 @@ public class ResourcesServlet extends AbstractValidationsServlet { response = buildErrorResponse(updateInfoResource.right().value()); return response; } - Either actionResponse = businessLogic.updateResourceMetadata(resourceIdLower, - updateInfoResource.left().value(), null, modifier, false); + Either actionResponse = businessLogic.updateResourceMetadata(resourceIdLower, updateInfoResource.left().value(), null, modifier, false); if (actionResponse.isRight()) { log.debug("failed to update resource metadata"); @@ -548,7 +543,7 @@ public class ResourcesServlet extends AbstractValidationsServlet { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); // get modifier id User modifier = new User(); @@ -607,7 +602,7 @@ public class ResourcesServlet extends AbstractValidationsServlet { * * @Produces(MediaType.APPLICATION_JSON) public Response getLatestVersionNotAbstractResources(@Context final HttpServletRequest request) { //TODO: any vlidations??? ServletContext context = request.getSession().getServletContext(); * - * String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(get) Start handle request of {}", url); Response response=null; + * String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(get) Start handle request of " + url); Response response=null; * * try { * @@ -653,7 +648,7 @@ public class ResourcesServlet extends AbstractValidationsServlet { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {}" , url); // retrieve user details userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java index 7e7068f5d7..05a6f5146c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java @@ -24,7 +24,9 @@ import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; +import java.lang.reflect.Type; import java.text.MessageFormat; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -46,6 +48,7 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.http.HttpStatus; +import org.codehaus.jackson.map.ObjectMapper; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -54,17 +57,18 @@ import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.GroupInstanceProperty; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.google.gson.reflect.TypeToken; import com.jcabi.aspects.Loggable; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; @@ -123,7 +127,6 @@ public class ServiceServlet extends AbstractValidationsServlet { return response; } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Service"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Service"); log.debug("create service failed with exception", e); response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -163,7 +166,6 @@ public class ServiceServlet extends AbstractValidationsServlet { } return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Validate Service Name"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name"); log.debug("validate service name failed with exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -187,9 +189,9 @@ public class ServiceServlet extends AbstractValidationsServlet { modifier.setUserId(userId); log.debug("modifier id is {}", userId); Wrapper responseWrapper = new Wrapper(); - Wrapper uuidWrapper = new Wrapper(); - Wrapper versionWrapper = new Wrapper(); - Wrapper userWrapper = new Wrapper(); + Wrapper uuidWrapper = new Wrapper<>(); + Wrapper versionWrapper = new Wrapper<>(); + Wrapper userWrapper = new Wrapper<>(); Wrapper componentWrapper = new Wrapper(); try { validateUserExist(responseWrapper, userWrapper, userId); @@ -217,7 +219,6 @@ public class ServiceServlet extends AbstractValidationsServlet { } } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Validate Service Name"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name"); log.debug("get Service Audit Records failed with exception", e); Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -278,7 +279,6 @@ public class ServiceServlet extends AbstractValidationsServlet { return response; } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Service"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service"); log.debug("delete service failed with exception", e); response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -315,7 +315,6 @@ public class ServiceServlet extends AbstractValidationsServlet { return response; } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Service"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service"); log.debug("delete service failed with exception", e); response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -367,7 +366,6 @@ public class ServiceServlet extends AbstractValidationsServlet { return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Service Metadata"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata"); log.debug("update service metadata failed with exception", e); response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -375,6 +373,67 @@ public class ServiceServlet extends AbstractValidationsServlet { } } + /** + * updates group instance property values + * Note, than in case of group instance updated successfully, related resourceInstance and containing component modification time will be updated + * @param serviceId + * @param componentInstanceId + * @param groupInstanceId + * @param data + * @param request + * @param userId + * @return + */ + @PUT + @Path("/{containerComponentType}/{serviceId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Group Instance Property Values", httpMethod = "PUT", notes = "Returns updated group instance", response = Service.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Instance Property Values Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateGroupInstancePropertyValues(@PathParam("serviceId") final String serviceId,@PathParam("componentInstanceId") final String componentInstanceId, @PathParam("groupInstanceId") final String groupInstanceId, @ApiParam(value = "Group instance object to be Updated", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + Response response = null; + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}",userId); + + ServiceBusinessLogic businessLogic; + Either, ResponseFormat> actionResponse = null; + try { + List updatedProperties; + Type listType = new TypeToken>(){}.getType(); + ArrayList newProperties = gson.fromJson(data, listType); + if (newProperties == null) { + actionResponse = Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + if(actionResponse == null){ + log.debug("Start handle update group instance property values request. Received group instance is {}", groupInstanceId); + businessLogic = getServiceBL(context); + actionResponse = businessLogic.updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties); + if(actionResponse.isRight()){ + actionResponse = Either.right(actionResponse.right().value()); + } + } + if(actionResponse.isLeft()){ + updatedProperties = actionResponse.left().value(); + ObjectMapper mapper = new ObjectMapper(); + String result = mapper.writeValueAsString(updatedProperties); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + } + else{ + response = buildErrorResponse(actionResponse.right().value()); + } + } catch (Exception e) { + log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return response; + } @GET @Path("/services/{serviceId}") @@ -412,7 +471,6 @@ public class ServiceServlet extends AbstractValidationsServlet { return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Service"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service"); log.debug("get service failed with exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -451,7 +509,6 @@ public class ServiceServlet extends AbstractValidationsServlet { return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Service by name and version"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service by name and version"); log.debug("get service failed with exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -492,7 +549,6 @@ public class ServiceServlet extends AbstractValidationsServlet { return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Service Distribution State"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Distribution State"); log.debug("updateServiceDistributionState failed with exception", e); response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -531,7 +587,6 @@ public class ServiceServlet extends AbstractValidationsServlet { Object result = RepresentationUtils.toRepresentation(service); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Activate Distribution"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution"); log.debug("activate distribution failed with exception", e); response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -570,7 +625,6 @@ public class ServiceServlet extends AbstractValidationsServlet { Object result = RepresentationUtils.toRepresentation(service); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Mark Distribution As Deployed"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Mark Distribution As Deployed"); log.debug("mark distribution as deployed failed with exception", e); response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -604,7 +658,6 @@ public class ServiceServlet extends AbstractValidationsServlet { } return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null); } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "tempUrlToBeDeleted"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("tempUrlToBeDeleted"); log.debug("failed with exception", e); response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -621,12 +674,9 @@ public class ServiceServlet extends AbstractValidationsServlet { @ApiResponse(code = 404, message = "Artifact not found") }) public Response downloadServiceArtifact(@PathParam("artifactName") final String artifactName, @Context final HttpServletRequest request) { Response response = null; - String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER); - String requestURI = request.getRequestURI(); try { log.debug("artifact name = {}", artifactName); - ServletContext context = request.getSession().getServletContext(); Either executeCommand = executeCommand(artifactName); @@ -640,7 +690,7 @@ public class ServiceServlet extends AbstractValidationsServlet { InputStream is = new ByteArrayInputStream(value); Map headers = new HashMap<>(); - String heatFileName = null; + String heatFileName; if (artifactName.indexOf(".") > -1) { heatFileName = artifactName.substring(0, artifactName.indexOf(".")) + ".heat"; } else { @@ -653,7 +703,6 @@ public class ServiceServlet extends AbstractValidationsServlet { return response; } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download heat artifact"); log.error("download artifact failed with exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } @@ -671,8 +720,7 @@ public class ServiceServlet extends AbstractValidationsServlet { heatTranslator = "/home/m98835/heat-translator-0.3.0/heat_translator.py"; } - log.debug("toscaFilesDir={}", toscaFilesDir); - log.debug("heatTranslator={}", heatTranslator); + log.debug("toscaFilesDir= {} | heatTranslator= {}", toscaFilesDir, heatTranslator); StringBuffer output = new StringBuffer(); @@ -702,19 +750,19 @@ public class ServiceServlet extends AbstractValidationsServlet { log.debug("waitFor = {}", waitFor); if (waitFor != 0) { - log.error("Failed running the command {}", command); + log.error("Failed runnign the command {}", command); return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); } BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); - String line = ""; + String line; while ((line = reader.readLine()) != null) { output.append(line + "\n"); } } catch (Exception e) { - log.error("Failed running the command {} {}", command, e); + log.error("Failed runnign the command {}", command, e); e.printStackTrace(); return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java index 0825a25cbe..6541da7e88 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java @@ -83,14 +83,13 @@ public class TypesFetchServlet extends AbstractValidationsServlet { if (responseWrapper.isEmpty()) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); + log.debug("Start handle request of {} | modifier id is {}", url, userId); PropertyBusinessLogic businessLogic = getPropertyBL(context); Either, ResponseFormat> allDataTypes = businessLogic.getAllDataTypes(); if (allDataTypes.isRight()) { - log.info("Failed to get all dara types. Reason - ", allDataTypes.right().value()); + log.info("Failed to get all dara types. Reason - {}", allDataTypes.right().value()); Response errorResponse = buildErrorResponse(allDataTypes.right().value()); responseWrapper.setInnerElement(errorResponse); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java index 6ba8c521f1..1fcc0fd404 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java @@ -42,6 +42,8 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.codehaus.jackson.JsonGenerationException; +import org.codehaus.jackson.map.JsonMappingException; import org.glassfish.jersey.media.multipart.FormDataParam; import org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager; import org.openecomp.sdc.be.components.impl.CategoriesImportManager; @@ -105,13 +107,11 @@ public class TypesUploadServlet extends AbstractValidationsServlet { @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Create Capability Type from yaml", httpMethod = "POST", notes = "Returns created Capability Type", response = Response.class) @ApiResponses(value = { @ApiResponse(code = 201, message = "Capability Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Capability Type already exist") }) + @ApiResponse(code = 409, message = "Capability Type already exist") }) public Response uploadCapabilityType(@ApiParam("FileInputStream") @FormDataParam("capabilityTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - capabilityTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> CapabilityTypeImportManager.class); ConsumerTwoParam, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> capabilityTypeImportManager.createCapabilityTypes(ymlPayload)); return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.CapabilityType.name()); - } @POST @@ -120,9 +120,8 @@ public class TypesUploadServlet extends AbstractValidationsServlet { @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Create Interface Lyfecycle Type from yaml", httpMethod = "POST", notes = "Returns created Interface Lifecycle Type", response = Response.class) @ApiResponses(value = { @ApiResponse(code = 201, message = "Interface Lifecycle Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Interface Lifecycle Type already exist") }) + @ApiResponse(code = 409, message = "Interface Lifecycle Type already exist") }) public Response uploadInterfaceLifecycleType(@ApiParam("FileInputStream") @FormDataParam("interfaceLifecycleTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - interfaceLifecycleTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> InterfaceLifecycleTypeImportManager.class); ConsumerTwoParam, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> interfaceLifecycleTypeImportManager.createLifecycleTypes(ymlPayload)); return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "Interface Types"); @@ -134,13 +133,11 @@ public class TypesUploadServlet extends AbstractValidationsServlet { @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created categories", response = Response.class) @ApiResponses(value = { @ApiResponse(code = 201, message = "Categories created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Category already exist") }) + @ApiResponse(code = 409, message = "Category already exist") }) public Response uploadCategories(@ApiParam("FileInputStream") @FormDataParam("categoriesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - categoriesImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> CategoriesImportManager.class); ConsumerTwoParam, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> categoriesImportManager.createCategories(ymlPayload)); return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "categories"); - } @POST @@ -149,13 +146,11 @@ public class TypesUploadServlet extends AbstractValidationsServlet { @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created data types", response = Response.class) @ApiResponses(value = { @ApiResponse(code = 201, message = "Data types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Data types already exist") }) + @ApiResponse(code = 409, message = "Data types already exist") }) public Response uploadDataTypes(@ApiParam("FileInputStream") @FormDataParam("dataTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - dataTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> DataTypeImportManager.class); ConsumerTwoParam, String> createElementsMethod = (responseWrapper, ymlPayload) -> createDataTypes(responseWrapper, ymlPayload); return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.DataType.getName()); - } @POST @@ -164,12 +159,10 @@ public class TypesUploadServlet extends AbstractValidationsServlet { @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Create GroupTypes from yaml", httpMethod = "POST", notes = "Returns created group types", response = Response.class) @ApiResponses(value = { @ApiResponse(code = 201, message = "group types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "group types already exist") }) + @ApiResponse(code = 409, message = "group types already exist") }) public Response uploadGroupTypes(@ApiParam("FileInputStream") @FormDataParam("groupTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - groupTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> GroupTypeImportManager.class); ConsumerTwoParam, String> createElementsMethod = (responseWrapper, ymlPayload) -> createGroupTypes(responseWrapper, ymlPayload); - return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.GroupType.getName()); } @@ -179,14 +172,11 @@ public class TypesUploadServlet extends AbstractValidationsServlet { @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Create PolicyTypes from yaml", httpMethod = "POST", notes = "Returns created policy types", response = Response.class) @ApiResponses(value = { @ApiResponse(code = 201, message = "policy types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "policy types already exist") }) + @ApiResponse(code = 409, message = "policy types already exist") }) public Response uploadPolicyTypes(@ApiParam("FileInputStream") @FormDataParam("policyTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - policyTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> PolicyTypeImportManager.class); ConsumerTwoParam, String> createElementsMethod = (responseWrapper, ymlPayload) -> createPolicyTypes(responseWrapper, ymlPayload); - return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.PolicyType.getName()); - } private Response uploadElementTypeServletLogic(ConsumerTwoParam, String> createElementsMethod, File file, final HttpServletRequest request, String creator, String elementTypeName) { @@ -221,7 +211,7 @@ public class TypesUploadServlet extends AbstractValidationsServlet { return responseWrapper.getInnerElement(); } catch (Exception e) { - log.debug("create {} failed with exception: {}", elementTypeName, e); + log.debug("create {} failed with exception:", elementTypeName, e); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create " + elementTypeName); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } @@ -233,8 +223,13 @@ public class TypesUploadServlet extends AbstractValidationsServlet { Response response = buildErrorResponse(eitherResult.right().value()); responseWrapper.setInnerElement(response); } else { - Response response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), eitherResult.left().value()); - responseWrapper.setInnerElement(response); + try { + Response response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), RepresentationUtils.toRepresentation(eitherResult.left().value())); + responseWrapper.setInnerElement(response); + } catch (Exception e) { + Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + responseWrapper.setInnerElement(response); + } } } @@ -248,20 +243,16 @@ public class TypesUploadServlet extends AbstractValidationsServlet { private void createGroupTypes(Wrapper responseWrapper, String groupTypesYml) { final Supplier>, ResponseFormat>> generateElementTypeFromYml = () -> groupTypeImportManager.createGroupTypes(groupTypesYml); buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.GROUP_TYPE_ALREADY_EXIST, NodeTypeEnum.GroupType.name()); - } // policy types private void createPolicyTypes(Wrapper responseWrapper, String policyTypesYml) { final Supplier>, ResponseFormat>> generateElementTypeFromYml = () -> policyTypeImportManager.createPolicyTypes(policyTypesYml); buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.POLICY_TYPE_ALREADY_EXIST, NodeTypeEnum.PolicyType.name()); - } // data types - private void buildStatusForElementTypeCreate(Wrapper responseWrapper, Supplier>, ResponseFormat>> generateElementTypeFromYml, - ActionStatus alreadyExistStatus, String elementTypeName) { - + private void buildStatusForElementTypeCreate(Wrapper responseWrapper, Supplier>, ResponseFormat>> generateElementTypeFromYml, ActionStatus alreadyExistStatus, String elementTypeName) { Either>, ResponseFormat> eitherResult = generateElementTypeFromYml.get(); if (eitherResult.isRight()) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java index c700c31a64..a477bcf4fb 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java @@ -108,7 +108,7 @@ public class UserAdminServlet extends BeGenericServlet { } catch (Exception e) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get User"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User"); - log.debug("get user failed with unexpected error: {}", e); + log.debug("get user failed with unexpected error: {}", e.getMessage(), e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } @@ -140,7 +140,7 @@ public class UserAdminServlet extends BeGenericServlet { * * @ApiResponse(code = 409, message = "User already exists"), * - * @ApiResponse(code = 500, message = "Internal Server Error") }) public Response updateUser(@ApiParam(value="userId of user to get", required=true) @PathParam("userId") final String UserIdUpdateUser, + * @ApiResponse(code = 500, message = "Internal Server Error") }) public Response updateUser(@ApiParam(value="userId of user to get", required=true) @PathParam("userId") final String userIdUpdateUser, * * @Context final HttpServletRequest request, * @@ -157,7 +157,7 @@ public class UserAdminServlet extends BeGenericServlet { * Response response = null; * * try { UserAdminBuisinessLogic businessLogic = getUserAdminManager(context); User updateInfoUser = getComponentsUtils().convertJsonToObject(data, modifier, User.class, AuditingActionEnum.UPDATE_USER).left().value(); Either - * updateUserResponse = null;// businessLogic.updateUser(modifier, UserIdUpdateUser, updateInfoUser); + * updateUserResponse = null;// businessLogic.updateUser(modifier, userIdUpdateUser, updateInfoUser); * * if (updateUserResponse.isRight()) { log.debug("failed to update user metadata"); response = buildErrorResponse(updateUserResponse.right().value()); return response; } response = * buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateUserResponse.left().value()); return response; @@ -216,7 +216,7 @@ public class UserAdminServlet extends BeGenericServlet { @ApiOperation(value = "update user role", notes = "Update user role", response = User.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Update user OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information/Restricted operation"), @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response updateUserRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String UserIdUpdateUser, @Context final HttpServletRequest request, + public Response updateUserRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userIdUpdateUser, @Context final HttpServletRequest request, @ApiParam(value = "json describe the update role", required = true) String data, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierUserId) { ServletContext context = request.getSession().getServletContext(); @@ -234,7 +234,7 @@ public class UserAdminServlet extends BeGenericServlet { try { UserBusinessLogic businessLogic = getUserAdminManager(context); User updateInfoUser = getComponentsUtils().convertJsonToObject(data, modifier, User.class, AuditingActionEnum.UPDATE_USER).left().value(); - Either updateUserResponse = businessLogic.updateUserRole(modifier, UserIdUpdateUser, updateInfoUser.getRole()); + Either updateUserResponse = businessLogic.updateUserRole(modifier, userIdUpdateUser, updateInfoUser.getRole()); if (updateUserResponse.isRight()) { log.debug("failed to update user role"); @@ -402,13 +402,12 @@ public class UserAdminServlet extends BeGenericServlet { @ApiOperation(value = "Retrieve the list of all active ASDC users or only group of users having specific roles.", httpMethod = "GET", notes = "Returns list of users with the specified roles, or all of users in the case of empty 'roles' header", response = User.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns users Ok"), @ApiResponse(code = 204, message = "No provisioned ASDC users of requested role"), @ApiResponse(code = 403, message = "Restricted Access"), @ApiResponse(code = 400, message = "Missing content"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getUsersList(@Context final HttpServletRequest request, @ApiParam(value = "Any active user's USER_ID") @HeaderParam(Constants.USER_ID_HEADER) final String userId, + public Response getUsersList(@Context final HttpServletRequest request, @ApiParam(value = "Any active user's USER_ID ") @HeaderParam(Constants.USER_ID_HEADER) final String userId, @ApiParam(value = "TESTER,DESIGNER,PRODUCT_STRATEGIST,OPS,PRODUCT_MANAGER,GOVERNOR, ADMIN OR all users by not typing anything") @QueryParam("roles") final String roles) { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); + log.debug("Start handle request of {} modifier id is {}", url, userId); List rolesList = new ArrayList<>(); if (roles != null && !roles.trim().isEmpty()) { @@ -450,11 +449,10 @@ public class UserAdminServlet extends BeGenericServlet { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + log.debug("Start handle request of {} modifier id is {}", url, userIdHeader); User modifier = new User(); modifier.setUserId(userIdHeader); - log.debug("modifier id is {}", userIdHeader); Response response = null; try { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java b/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java index 4027144911..876066b9ba 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java @@ -161,7 +161,7 @@ public class SwitchoverDetector { if (message == null) { message = e.getClass().getName(); } - switchoverLogger.debug("Error occured during switchover detector query, Result is {}", message); + logger.debug("Error occured during switchover detector query, Result is {}", message, e); } } if (null == result) { @@ -178,14 +178,18 @@ public class SwitchoverDetector { @Override public void run() { - switchoverLogger.trace("Executing Switchover Detector Task - Start"); + logger.trace("Executing Switchover Detector Task - Start"); initializeSiteMode(); Boolean beRes = queryBe(); Boolean feRes = queryFe(); - Boolean updateRequired = siteMode == SwitchoverDetectorState.STANDBY.getState() && (beRes || feRes); + if (null == beRes || null == feRes) { + return; + } + + Boolean updateRequired = siteMode == SwitchoverDetectorState.STANDBY.getState() && (beRes || feRes) & (beMatch != beRes || feMatch != feRes); updateSiteModeAndPriority(beRes && feRes, siteMode == SwitchoverDetectorState.STANDBY.getState(), updateRequired); @@ -232,7 +236,8 @@ public class SwitchoverDetector { if (message == null) { message = e.getClass().getName(); } - switchoverLogger.error("Error occured during change site priority request, Result is {}", message); + + logger.debug("Error occured during change site priority request, Result is {}", message, e); } } @@ -252,7 +257,8 @@ public class SwitchoverDetector { if (message == null) { message = e.getClass().getName(); } - switchoverLogger.error("Error occured during publish network request, Result is {}", message); + + logger.debug("Error occured during publish network request, Result is {}", message, e); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java index 85b4493c8e..13356e5de4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java @@ -24,6 +24,7 @@ import java.util.List; import org.openecomp.sdc.generator.data.ArtifactType; + public class ArtifactTypes { private List artifactTypes; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java index d1f2557413..b21e064a82 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java @@ -24,8 +24,11 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; @@ -33,8 +36,6 @@ import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.resources.data.CapabilityData; -import org.openecomp.sdc.be.resources.data.RequirementData; import org.openecomp.sdc.be.tosca.model.SubstitutionMapping; import org.openecomp.sdc.be.tosca.model.ToscaCapability; import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; @@ -42,14 +43,18 @@ import org.openecomp.sdc.be.tosca.model.ToscaNodeType; import org.openecomp.sdc.be.tosca.model.ToscaProperty; import org.openecomp.sdc.be.tosca.model.ToscaRequirement; import org.openecomp.sdc.be.tosca.model.ToscaTemplateCapability; +import org.openecomp.sdc.common.util.ValidationUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.google.common.collect.Lists; + import fj.data.Either; public class CapabiltyRequirementConvertor { private static CapabiltyRequirementConvertor instance; - + public final static String PATH_DELIMITER = "."; + protected CapabiltyRequirementConvertor() { } @@ -131,8 +136,8 @@ public class CapabiltyRequirementConvertor { return Either.left(nodeType); } - public Either convertRequirements(Component component, SubstitutionMapping substitutionMapping) { - Map toscaRequirements = convertRequirementsAsMap(component); + public Either convertSubstitutionMappingRequirements(Component component, SubstitutionMapping substitutionMapping) { + Map toscaRequirements = convertSubstitutionMappingRequirementsAsMap(component); if (!toscaRequirements.isEmpty()) { substitutionMapping.setRequirements(toscaRequirements); } @@ -145,9 +150,9 @@ public class CapabiltyRequirementConvertor { Map> requirements = component.getRequirements(); List> toscaRequirements = new ArrayList<>(); if (requirements != null) { - boolean isNodeType = ToscaUtils.isNodeType(component); + boolean isNodeType = ToscaUtils.isAtomicType(component); for (Map.Entry> entry : requirements.entrySet()) { - entry.getValue().stream().filter(r -> (!isNodeType || (isNodeType && component.getUniqueId().equals(r.getOwnerId())))).forEach(r -> { + entry.getValue().stream().filter(r -> (!isNodeType || (isNodeType && component.getUniqueId().equals(r.getOwnerId())) || (isNodeType && r.getOwnerId() == null))).forEach(r -> { ImmutablePair pair = convertRequirement(component, isNodeType, r); Map requirement = new HashMap<>(); @@ -163,17 +168,25 @@ public class CapabiltyRequirementConvertor { return toscaRequirements; } - private Map convertRequirementsAsMap(Component component) { + private String getSubPathByFirstDelimiterAppearance(String path) { + return path.substring(path.indexOf(PATH_DELIMITER) + 1); + } + + private String getSubPathByLastDelimiterAppearance(String path) { + return path.substring(path.lastIndexOf(PATH_DELIMITER) + 1); + } + + //This function calls on Substitution Mapping region - the component is always non-atomic + private Map convertSubstitutionMappingRequirementsAsMap(Component component) { Map> requirements = component.getRequirements(); - Map toscaRequirements = new HashMap<>(); + Map toscaRequirements = new HashMap<>(); if (requirements != null) { - boolean isNodeType = ToscaUtils.isNodeType(component); for (Map.Entry> entry : requirements.entrySet()) { - entry.getValue().stream().filter(r -> (!isNodeType || (isNodeType && component.getUniqueId().equals(r.getOwnerId())))).forEach(r -> { - ImmutablePair pair = convertRequirement(component, isNodeType, r); - toscaRequirements.put(pair.left, pair.right); + entry.getValue().stream().forEach(r -> { + String fullReqName = getRequirementPath(r); + log.debug("the requirement {} belongs to resource {} ", fullReqName, component.getUniqueId()); + toscaRequirements.put(fullReqName, new String[]{r.getOwnerName(), getSubPathByFirstDelimiterAppearance(fullReqName)}); }); - log.debug("Finish convert Requirements for node type"); } } else { @@ -182,17 +195,25 @@ public class CapabiltyRequirementConvertor { return toscaRequirements; } + private String getRequirementPath(RequirementDefinition r) { + List pathArray = Lists.reverse(r.getPath().stream() + .map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))) + .collect(Collectors.toList())); + return new StringBuilder().append(String.join(PATH_DELIMITER, pathArray)).append(PATH_DELIMITER).append(r.getName()).toString(); + + } + private ImmutablePair convertRequirement(Component component, boolean isNodeType, RequirementDefinition r) { String name = r.getName(); if (!isNodeType) { - name = r.getOwnerName() + "." + name; + name = getRequirementPath(r); } log.debug("the requirement {} belongs to resource {} ", name, component.getUniqueId()); ToscaRequirement toscaRequirement = new ToscaRequirement(); List occurences = new ArrayList<>(); occurences.add(Integer.valueOf(r.getMinOccurrences())); - if (r.getMaxOccurrences().equals(RequirementData.MAX_OCCURRENCES)) { + if (r.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { occurences.add(r.getMaxOccurrences()); } else { occurences.add(Integer.valueOf(r.getMaxOccurrences())); @@ -212,9 +233,9 @@ public class CapabiltyRequirementConvertor { Map> capabilities = component.getCapabilities(); Map toscaCapabilities = new HashMap<>(); if (capabilities != null) { - boolean isNodeType = ToscaUtils.isNodeType(component); + boolean isNodeType = ToscaUtils.isAtomicType(component); for (Map.Entry> entry : capabilities.entrySet()) { - entry.getValue().stream().filter(c -> (!isNodeType || (isNodeType && component.getUniqueId().equals(c.getOwnerId())))).forEach(c -> { + entry.getValue().stream().filter(c -> (!isNodeType || (isNodeType && component.getUniqueId().equals(c.getOwnerId())) || (isNodeType && c.getOwnerId() == null) )).forEach(c -> { convertCapabilty(component, toscaCapabilities, isNodeType, c, dataTypes); }); @@ -225,11 +246,39 @@ public class CapabiltyRequirementConvertor { return toscaCapabilities; } + + //This function calls on Substitution Mapping region - the component is always non-atomic + public Map convertSubstitutionMappingCapabilities(Component component, Map dataTypes) { + Map> capabilities = component.getCapabilities(); + Map toscaCapabilities = new HashMap<>(); + if (capabilities != null) { + for (Map.Entry> entry : capabilities.entrySet()) { + entry.getValue().stream().forEach(c -> { + String fullCapName = getCapabilityPath(c); + log.debug("the capabilty {} belongs to resource {} ", fullCapName, component.getUniqueId()); + toscaCapabilities.put(fullCapName, new String[]{c.getOwnerName(), getSubPathByFirstDelimiterAppearance(fullCapName)}); + }); + } + } else { + log.debug("No Capabilities for node type"); + } + return toscaCapabilities; + } + + private String getCapabilityPath(CapabilityDefinition c) { + List pathArray = Lists.reverse(c.getPath().stream() + .map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))) + .collect(Collectors.toList())); + return new StringBuilder().append(String.join(PATH_DELIMITER, pathArray)).append(PATH_DELIMITER).append(c.getName()).toString(); + } + + + private void convertCapabilty(Component component, Map toscaCapabilities, boolean isNodeType, CapabilityDefinition c, Map dataTypes) { String name = c.getName(); if (!isNodeType) { - name = c.getOwnerName() + "." + name; + name = getCapabilityPath(c); } log.debug("the capabilty {} belongs to resource {} ", name, component.getUniqueId()); ToscaCapability toscaCapability = new ToscaCapability(); @@ -238,7 +287,7 @@ public class CapabiltyRequirementConvertor { List occurences = new ArrayList<>(); occurences.add(Integer.valueOf(c.getMinOccurrences())); - if (c.getMaxOccurrences().equals(CapabilityData.MAX_OCCURRENCES)) { + if (c.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { occurences.add(c.getMaxOccurrences()); } else { occurences.add(Integer.valueOf(c.getMaxOccurrences())); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java index c8aa188e30..3c0c80666c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java @@ -20,64 +20,97 @@ package org.openecomp.sdc.be.tosca; +import java.io.File; import java.io.IOException; -import org.apache.commons.codec.binary.Base64; -import java.util.Collection; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; +import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.ByteArrayOutputStream; +import org.apache.commons.lang.WordUtils; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.ImmutableTriple; import org.apache.commons.lang3.tuple.Triple; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; -import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperation; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo; +import org.openecomp.sdc.be.components.impl.ImportUtils; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; +import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Operation; +import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.be.model.operations.impl.ServiceOperation; +import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation; import org.openecomp.sdc.be.resources.data.ESArtifactData; +import org.openecomp.sdc.be.resources.data.ESSdcSchemaFilesData; import org.openecomp.sdc.be.tosca.model.ToscaTemplate; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.util.GeneralUtility; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - +import org.openecomp.sdc.generator.data.AdditionalParams; import org.openecomp.sdc.generator.data.Artifact; import org.openecomp.sdc.generator.data.ArtifactType; import org.openecomp.sdc.generator.data.GenerationData; import org.openecomp.sdc.generator.impl.ArtifactGenerationServiceImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + import com.google.gson.Gson; import fj.data.Either; + /** * @author tg851x * */ @org.springframework.stereotype.Component("csar-utils") public class CsarUtils { - private static Logger log = LoggerFactory.getLogger(ToscaExportHandler.class.getName()); + private static Logger log = LoggerFactory.getLogger(CsarUtils.class.getName()); + @Autowired + private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao; @Autowired private ArtifactCassandraDao artifactCassandraDao; @Autowired @@ -87,45 +120,68 @@ public class CsarUtils { @Autowired private ArtifactsBusinessLogic artifactsBusinessLogic; @Autowired - protected ServiceOperation serviceOperation; + protected ToscaOperationFacade toscaOperationFacade; + @javax.annotation.Resource private ServiceBusinessLogic serviceBusinessLogic; private Gson gson = new Gson(); - private static final String DEFINITIONS_PATH = "Definitions/"; - private static final String ARTIFACTS_PATH = "Artifacts/"; + public static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel(); + public static final String SDC_VERSION = ExternalConfiguration.getAppVersion(); + + public static final Pattern UUID_NORMATIVE_NEW_VERSION = Pattern.compile("^\\d{1,}.0"); + public static final String ARTIFACTS_PATH = "Artifacts/"; + public static final String RESOURCES_PATH = "Resources/"; + public static final String INFORMATIONAL_ARTIFACTS = "Informational/"; + public static final String DEPLOYMENT_ARTIFACTS = "Deployment/"; + + public static final String DEFINITIONS_PATH = "Definitions/"; + private static final String CSAR_META_VERSION = "1.0"; + private static final String CSAR_META_PATH_FILE_NAME = "csar.meta"; private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta"; private static final String TOSCA_META_VERSION = "1.0"; private static final String CSAR_VERSION = "1.1"; + public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS_PATH + ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "([\\w\\_\\-\\.\\s]+)(/)([\\w\\_\\-\\.\\s]+)(/)([\\w\\_\\-\\.\\s\\/]+)"; + + public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS_PATH + + // Artifact Group (i.e Deployment/Informational) + "([\\w\\_\\-\\.\\s]+)(/)" + + // Artifact Type + "([\\w\\_\\-\\.\\s]+)(/)" + + // Artifact File Name + "([\\w\\_\\-\\.\\s]+)"; + public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar"; + /** * * @param component * @param getFromCS * @param isInCertificationRequest - * @param shouldLock - * @param inTransaction * @return */ - public Either createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean shouldLock, boolean inTransaction) { - return createCsar(component, getFromCS, isInCertificationRequest, false, shouldLock, inTransaction); + public Either createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) { + return createCsar(component, getFromCS, isInCertificationRequest, false); } - private Either createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator, boolean shouldLock, boolean inTransaction) { - final String CREATED_BY = component.getCreatorFullName(); + private Either createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) { + final String createdBy = component.getCreatorFullName(); String fileName; Map toscaArtifacts = component.getToscaArtifacts(); ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); fileName = artifactDefinition.getArtifactName(); - String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, CREATED_BY, fileName); - + String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel(); + String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel); + byte[] csarBlock0Byte = csarBlock0.getBytes(); + + final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName); byte[] toscaBlock0Byte = toscaBlock0.getBytes(); - Either generateCsarZipResponse = generateCsarZip(toscaBlock0Byte, component, getFromCS, isInCertificationRequest, mockGenerator, shouldLock, inTransaction); + Either generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest, mockGenerator); if (generateCsarZipResponse.isRight()) { return Either.right(generateCsarZipResponse.right().value()); @@ -134,64 +190,50 @@ public class CsarUtils { return Either.left(generateCsarZipResponse.left().value()); } - private Either generateCsarZip(byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator, boolean shouldLock, boolean inTransaction) { - - ZipOutputStream zip = null; - ByteArrayOutputStream out = null; - try { - out = new ByteArrayOutputStream(); - zip = new ZipOutputStream(out); - + private Either generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) { + try ( + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ZipOutputStream zip = new ZipOutputStream(out); + ){ + zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME)); + zip.write(csarBlock0Byte); zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME)); zip.write(toscaBlock0Byte); - Either populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest, mockGenerator, shouldLock, inTransaction); + Either populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest, mockGenerator); if (populateZip.isRight()) { log.debug("Failed to populate CSAR zip file {}", populateZip.right().value()); return Either.right(populateZip.right().value()); } - zip = populateZip.left().value(); zip.finish(); byte[] byteArray = out.toByteArray(); return Either.left(byteArray); } catch (IOException e) { - log.debug("createCsar failed IOexception", e); + log.debug("Failed with IOexception to create CSAR zip for component {}", component.getUniqueId(), e); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); return Either.right(responseFormat); - } finally { - try { - if (zip != null) { - zip.close(); - } - if (out != null) { - out.close(); - } - } catch (Exception e) { - log.error("Failed to close resources ", e); - } } } - private Either populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator, boolean shouldLock, boolean inTransaction) { + private Either populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator) throws IOException { LifecycleStateEnum lifecycleState = component.getLifecycleState(); - String componentYaml = null; - Either exportComponent = null; - byte[] mainYaml = null; - // + String componentYaml; + Either exportComponent; + byte[] mainYaml; + // List> dependencies = null; List> generatorInputs = new LinkedList<>(); - String fileName; Map toscaArtifacts = component.getToscaArtifacts(); ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - fileName = artifactDefinition.getArtifactName(); + String fileName = artifactDefinition.getArtifactName(); if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { - String esId = artifactDefinition.getEsId(); - Either fromCassandra = getFromCassandra(esId); + String cassandraId = artifactDefinition.getEsId(); + Either fromCassandra = getFromCassandra(cassandraId); if (fromCassandra.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(fromCassandra.right().value()); return Either.right(responseFormat); @@ -212,147 +254,214 @@ public class CsarUtils { dependencies = exportResult.getDependencies(); } - try { - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName)); - zip.write(mainYaml); + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName)); + zip.write(mainYaml); + //US798487 - Abstraction of complex types + if (!ToscaUtils.isAtomicType(component)){ + log.debug("Component {} is complex - generating abstract type for it..", component.getName()); + writeComponentInterface(component, zip, fileName); + } - generatorInputs.add(new ImmutablePair(component, mainYaml)); + generatorInputs.add(new ImmutablePair(component, mainYaml)); - if (dependencies == null) { - Either dependenciesRes = toscaExportUtils.getDependencies(component); - if (dependenciesRes.isRight()) { - log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(), dependenciesRes.right().value()); - ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError); + if (dependencies == null) { + Either dependenciesRes = toscaExportUtils.getDependencies(component); + if (dependenciesRes.isRight()) { + log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(), + dependenciesRes.right().value()); + ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError); + return Either.right(responseFormat); + } + dependencies = dependenciesRes.left().value().getDependencies(); + } + + //UID + Map> innerComponentsCache = new HashMap<>(); + + if (dependencies != null && !dependencies.isEmpty()) { + for (Triple d : dependencies) { + String cassandraId = d.getMiddle(); + Component childComponent = d.getRight(); + Either entryData = getEntryData(cassandraId, childComponent); + + if (entryData.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); return Either.right(responseFormat); } - dependencies = dependenciesRes.left().value().getDependencies(); - } - if (dependencies != null && !dependencies.isEmpty()) { - for (Triple d : dependencies) { - String esId = d.getMiddle(); - Component childComponent = d.getRight(); - fileName = d.getLeft(); - Either entryData = getEntryData(esId, childComponent); - - if (entryData.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); - return Either.right(responseFormat); - } + //fill innerComponentsCache + fileName = d.getLeft(); + innerComponentsCache.put(childComponent.getUniqueId(), + new ImmutableTriple(cassandraId, fileName, childComponent)); + insertInnerComponentsToCache(innerComponentsCache, childComponent); + byte[] content = entryData.left().value(); - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName)); - zip.write(content); - generatorInputs.add(new ImmutablePair(childComponent, content)); } - } - - List aiiArtifactList = new LinkedList<>(); - // Artifact Generation - if (component.getComponentType() == ComponentTypeEnum.SERVICE && (lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { - Either, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component, zip, mockGenerator, shouldLock, inTransaction, generatorInputs); + + //add inner components to CSAR + innerComponentsCache.forEach((childUid, innerComponentTriple) -> { + Component innerComponent = innerComponentTriple.getRight(); + String icFileName = innerComponentTriple.getMiddle(); + + try { + //add component to zip + Either entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent); + byte[] content = entryData.left().value(); + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName)); + zip.write(content); + + } catch (IOException e) { - if (handleAAIArtifacts.isLeft()) { - aiiArtifactList = handleAAIArtifacts.left().value(); - } else { - log.debug("AAI Artifacts handling failed"); - return Either.right(handleAAIArtifacts.right().value()); - } - - if (isInCertificationRequest) { - Either handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel(component, aiiArtifactList, shouldLock, inTransaction); - - if (handleAllAAIArtifactsInDataModel.isRight()) { - log.debug("AAI Artifacts handling (create, update, delete) failed"); - return Either.right(handleAllAAIArtifactsInDataModel.right().value()); } - } + //add component interface to zip + if(!ToscaUtils.isAtomicType(innerComponent)) { + writeComponentInterface(innerComponent, zip, icFileName); + } + }); + } + + /*Either latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra(); + + if(latestSchemaFilesFromCassandra.isRight()){ + return null; + }*/ + + //TODO Tal G this is quick solution until Cassandra US is alligned + Either addSchemaFilesFromConfig = addSchemaFilesFromConfig(zip); + + if(addSchemaFilesFromConfig.isRight()){ + return addSchemaFilesFromConfig; + } + + // Artifact Generation + if (component.getComponentType() == ComponentTypeEnum.SERVICE + && isInCertificationRequest) { + + List aiiArtifactList; + + Either, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component, mockGenerator, generatorInputs); + + if (handleAAIArtifacts.isLeft()) { + aiiArtifactList = handleAAIArtifacts.left().value(); + } else { + log.debug("AAI Artifacts handling failed"); + return Either.right(handleAAIArtifacts.right().value()); } - // Collecting All Deployment Artifacts - Either collectAndWriteToScarDeploymentArtifacts = collectAndWriteToScarDeploymentArtifacts(zip, component, aiiArtifactList); + if (isInCertificationRequest) { + Either handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel( + component, aiiArtifactList, false, true); - if (collectAndWriteToScarDeploymentArtifacts.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + if (handleAllAAIArtifactsInDataModel.isRight()) { + log.debug("AAI Artifacts handling (create, update, delete) failed"); + return Either.right(handleAllAAIArtifactsInDataModel.right().value()); + } } - } catch (IOException e) { - log.debug("Failed to create CSAR zip for component {}", component.getUniqueId(), e); - } - - return Either.left(zip); - } - private Either collectAndWriteToScarDeploymentArtifacts(ZipOutputStream zip, Component component, List aiiArtifactList) throws IOException { - - Collection deploymentArtifactsToAdd = null; - Collection allArtifactsToAdd = new LinkedList<>(); + } - if (component.getComponentType() == ComponentTypeEnum.SERVICE) { - Either getServiceResponse = serviceOperation.getService(component.getUniqueId()); + Either collectedComponentCsarDefinition = collectComponentCsarDefinition(component); - if (getServiceResponse.isLeft()) { - Service service = getServiceResponse.left().value(); + if (collectedComponentCsarDefinition.isRight()) { + return Either.right(collectedComponentCsarDefinition.right().value()); + } + + return writeAllFilesToScar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest); + } - if (!aiiArtifactList.isEmpty()) { - deploymentArtifactsToAdd = service.getDeploymentArtifacts().values().stream().filter(e -> e.getGenerated() == null || !e.getGenerated()).collect(Collectors.toList()); - allArtifactsToAdd.addAll(aiiArtifactList); - allArtifactsToAdd.addAll(deploymentArtifactsToAdd); - } else { - allArtifactsToAdd.addAll(service.getDeploymentArtifacts().values()); - } + private Either addSchemaFilesFromConfig(ZipOutputStream zip) throws ZipException, IOException { + final String pathAndFile = "config/SDC.zip"; + + File file = new File(pathAndFile); + if(!file.exists()){ + log.debug("SDC.zip schema files archive not found"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + try(ZipFile zipFile = new ZipFile(new File(pathAndFile));){ + Enumeration entries = zipFile.entries(); + + while(entries.hasMoreElements()){ + ZipEntry nextElement = entries.nextElement(); + InputStream inputStream = zipFile.getInputStream(nextElement); + byte[] byteArray = IOUtils.toByteArray(inputStream); + + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + nextElement.getName())); + zip.write(byteArray); } + zipFile.close(); + }catch (Exception e) { + log.debug("Error in writing SDC.zip schema files to CSAR"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } + + return Either.left(zip); + } - if (!allArtifactsToAdd.isEmpty()) { - - for (ArtifactDefinition deploymentArtifactDefinition : allArtifactsToAdd) { - String artifactFileName = deploymentArtifactDefinition.getArtifactName(); - byte[] payloadData = deploymentArtifactDefinition.getPayloadData(); - - if (payloadData == null) { - String esId = deploymentArtifactDefinition.getEsId(); - if (esId != null) { - Either fromCassandra = getFromCassandra(esId); - - if (fromCassandra.isRight()) { - return Either.right(fromCassandra.right().value()); - } - payloadData = fromCassandra.left().value(); - } else { - log.debug("Artifact {} payload not supplied in ArtifactDefinition and not found in DB", artifactFileName); - continue; + private void insertInnerComponentsToCache(Map> componentCache, + Component childComponent) { + + List instances = childComponent.getComponentInstances(); + + if(instances != null) { + instances.forEach(ci -> { + ImmutableTriple componentRecord = componentCache.get(ci.getComponentUid()); + if (componentRecord == null) { + // all resource must be only once! + Either resource = toscaOperationFacade.getToscaElement(ci.getComponentUid()); + if (resource.isRight()) { + log.debug("Failed to fetch resource with id {} for instance {}"); + } + Component componentRI = resource.left().value(); + + Map childToscaArtifacts = componentRI.getToscaArtifacts(); + ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + if (childArtifactDefinition != null) { + //add to cache + componentCache.put(ci.getComponentUid(), + new ImmutableTriple(childArtifactDefinition.getEsId(), + childArtifactDefinition.getArtifactName(), componentRI)); } - } - - byte[] decodedPayload = null; - if (Base64.isBase64(payloadData)) { - // decodedPayload = Base64.getDecoder().decode(payloadData); - decodedPayload = Base64.decodeBase64(payloadData); - } else { - decodedPayload = payloadData; + //if not atomic - insert inner components as well + if(!ToscaUtils.isAtomicType(componentRI)) { + insertInnerComponentsToCache(componentCache, componentRI); + } } - - zip.putNextEntry(new ZipEntry(ARTIFACTS_PATH + artifactFileName)); - zip.write(decodedPayload); - } + }); } - + } + + private Either writeComponentInterface(Component component, ZipOutputStream zip, String fileName) { + try { + Either componentInterface = toscaExportUtils.exportComponentInterface(component); + ToscaRepresentation componentInterfaceYaml = componentInterface.left().value(); + String mainYaml = componentInterfaceYaml.getMainYaml(); + String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName); + + zip.putNextEntry(new ZipEntry(interfaceFileName)); + zip.write(mainYaml.getBytes()); + + } catch (Exception e) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return Either.left(zip); } - - private Either, ResponseFormat> handleAAIArtifacts(Component component, ZipOutputStream zip, boolean mockGenerator, boolean shouldLock, boolean inTransaction, List> generatorInputs) { + + private Either, ResponseFormat> handleAAIArtifacts(Component component, boolean mockGenerator, List> generatorInputs) { ComponentTypeEnum componentType = component.getComponentType(); - List generatedArtifacts = null; - List aaiArtifacts = null; + List generatedArtifacts; + List aaiArtifacts = new LinkedList<>(); if (componentType == ComponentTypeEnum.SERVICE && !generatorInputs.isEmpty()) { List convertedGeneratorInputs = convertToGeneratorArtifactsInput(generatorInputs); - Either, ResponseFormat> generatorResponse; + Either, String> generatorResponse; if (mockGenerator) { generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.OTHER, component); @@ -361,7 +470,7 @@ public class CsarUtils { } if (generatorResponse.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.toString()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.right().value()); return Either.right(responseFormat); } @@ -376,8 +485,8 @@ public class CsarUtils { private Either handleAllAAIArtifactsInDataModel(Component component, List artifactsFromAAI, boolean shouldLock, boolean inTransaction) { - Either handleAAIArtifactsResponse = null; - User lastComponentUpdater = null; + Either handleAAIArtifactsResponse; + User lastComponentUpdater; List aaiArtifatcsToCreate = getAAIArtifatcsForCreate(artifactsFromAAI, component); List aaiArtifatcsToDelete = getAAIArtifatcsForDelete(artifactsFromAAI, component); @@ -393,19 +502,21 @@ public class CsarUtils { lastComponentUpdater = validateUserExists.left().value(); - handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, ArtifactOperation.Delete, lastComponentUpdater, shouldLock, inTransaction); + handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Delete), lastComponentUpdater, shouldLock, + inTransaction); if (handleAAIArtifactsResponse.isRight()) { return handleAAIArtifactsResponse; } - handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, ArtifactOperation.Create, lastComponentUpdater, shouldLock, inTransaction); + handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), lastComponentUpdater, shouldLock, + inTransaction); if (handleAAIArtifactsResponse.isRight()) { return handleAAIArtifactsResponse; } - return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, ArtifactOperation.Update, lastComponentUpdater, shouldLock, inTransaction); + return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), lastComponentUpdater, shouldLock, inTransaction); } private List getAAIArtifatcsForUpdate(List artifactsFromAAI, Component component) { @@ -413,10 +524,10 @@ public class CsarUtils { Set componetDeploymentArtifactLables = component.getDeploymentArtifacts().keySet(); Set componetInformationalArtifactLables = component.getArtifacts().keySet(); - List artifactsAaiUpdate = artifactsFromAAI.stream().filter(e -> (componetDeploymentArtifactLables.contains(e.getArtifactLabel()) || componetInformationalArtifactLables.contains(e.getArtifactLabel()))) - .filter(e -> checkAaiForUpdate(component, e)).collect(Collectors.toList()); - - return artifactsAaiUpdate; + return artifactsFromAAI.stream() + .filter(e -> componetDeploymentArtifactLables.contains(e.getArtifactLabel()) || componetInformationalArtifactLables.contains(e.getArtifactLabel())) + .filter(e -> checkAaiForUpdate(component, e)) + .collect(Collectors.toList()); } private boolean checkAaiForUpdate(Component component, ArtifactDefinition artifactDefinition) { @@ -446,21 +557,27 @@ public class CsarUtils { private List getAAIArtifatcsForDelete(List artifactsFromAAI, Component component) { - Set aaiLabels = artifactsFromAAI.stream().map(e -> e.getArtifactLabel()).collect(Collectors.toSet()); + Set aaiLabels = artifactsFromAAI.stream() + .map(ArtifactDefinition::getArtifactLabel) + .collect(Collectors.toSet()); - List artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream(). + List artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream() // Filter Out Artifacts that are not contained in artifacts returned // from AAI API - filter(e -> !aaiLabels.contains(e.getArtifactLabel())).collect(Collectors.toList()); + .filter(e -> !aaiLabels.contains(e.getArtifactLabel())) + .collect(Collectors.toList()); - List artifactsForDeleteInformational = component.getArtifacts().values().stream(). + List artifactsForDeleteInformational = component.getArtifacts().values().stream() // Filter Out Artifacts that are not contained in artifacts returned // from AAI API - filter(e -> !aaiLabels.contains(e.getArtifactLabel())).collect(Collectors.toList()); + .filter(e -> !aaiLabels.contains(e.getArtifactLabel())) + .collect(Collectors.toList()); artifactsForDeleteDeployment.addAll(artifactsForDeleteInformational); - return artifactsForDeleteDeployment.stream().filter(e -> (e.getGenerated() != null && e.getGenerated().equals(Boolean.TRUE)) || (e.getGenerated() == null && e.getArtifactLabel().toLowerCase().startsWith("aai"))).collect(Collectors.toList()); + return artifactsForDeleteDeployment.stream() + .filter(e -> (e.getGenerated() != null && e.getGenerated().equals(Boolean.TRUE)) || (e.getGenerated() == null && e.getArtifactLabel().toLowerCase().startsWith("aai"))) + .collect(Collectors.toList()); } private List getAAIArtifatcsForCreate(List artifactsFromAAI, Component component) { @@ -470,10 +587,12 @@ public class CsarUtils { // If the artifact label does not exist in the service - // store the artifact (generate uuid and version, "generated" flag is TRUE) - return artifactsFromAAI.stream().filter(e -> !componentDeploymentLabels.contains(e.getArtifactLabel()) && !componentInfoLabels.contains(e.getArtifactLabel())).collect(Collectors.toList()); + return artifactsFromAAI.stream() + .filter(e -> !componentDeploymentLabels.contains(e.getArtifactLabel()) && !componentInfoLabels.contains(e.getArtifactLabel())) + .collect(Collectors.toList()); } - private Either handleAAIArtifactsInDataModelByOperationType(Component component, List generatedArtifactsDefinitions, ArtifactOperation operationType, User user, boolean shouldLock, + private Either handleAAIArtifactsInDataModelByOperationType(Component component, List generatedArtifactsDefinitions, ArtifactOperationInfo operationType, User user, boolean shouldLock, boolean inTransaction) { String componentUniqueId = component.getUniqueId(); @@ -484,7 +603,7 @@ public class CsarUtils { String dataMD5 = GeneralUtility.calculateMD5ByString(data); String artifactUniqueId = null; - if (operationType.equals(ArtifactOperation.Update) || operationType.equals(ArtifactOperation.Delete)) { + if ((operationType.getArtifactOperationEnum() == ArtifactOperationEnum.Update) || (operationType.getArtifactOperationEnum() == ArtifactOperationEnum.Delete)) { String artifactLabel = artDef.getArtifactLabel(); ArtifactDefinition artifactDefinition = component.getDeploymentArtifacts().get(artifactLabel); if (artifactDefinition != null) { @@ -496,7 +615,7 @@ public class CsarUtils { null, null, user, component, shouldLock, inTransaction); if (validateAndHandleArtifact.isRight()) { - if (ArtifactOperation.Create == operationType || ArtifactOperation.Update == operationType) { + if (ArtifactOperationEnum.Create == operationType.getArtifactOperationEnum() || ArtifactOperationEnum.Update == operationType.getArtifactOperationEnum()) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, componentType.getValue(), component.getName(), validateAndHandleArtifact.right().value().toString()); Either.right(responseFormat); @@ -522,7 +641,7 @@ public class CsarUtils { // Normalizing the artifact label to match those stored in DB String normalizeArtifactLabel = ValidationUtils.normalizeArtifactLabel(artifact.getLabel()); newEntry.setArtifactLabel(normalizeArtifactLabel); - newEntry.setPayload(artifact.getPayload()); + newEntry.setPayload(Base64.decodeBase64(artifact.getPayload())); newEntry.setArtifactChecksum(artifact.getChecksum()); // Flag that set to true in case that the artifact is generated by AI&I generator newEntry.setGenerated(Boolean.TRUE); @@ -551,7 +670,6 @@ public class CsarUtils { byte[] right = triple.getRight(); // The md5 calculated on the uncoded data String md5Hex = DigestUtils.md5Hex(right); - // byte[] payload = Base64.getEncoder().encode(right); byte[] payload = Base64.encodeBase64(right); String artifactVersion = artifactDefinition.getArtifactVersion(); @@ -567,9 +685,9 @@ public class CsarUtils { return listOfArtifactsInput; } - private Either getEntryData(String esId, Component childComponent) { + private Either getEntryData(String cassandraId, Component childComponent) { byte[] content; - if (esId == null || esId.isEmpty()) { + if (cassandraId == null || cassandraId.isEmpty()) { Either exportRes = toscaExportUtils.exportComponent(childComponent); if (exportRes.isRight()) { log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), exportRes.right().value()); @@ -577,7 +695,7 @@ public class CsarUtils { } content = exportRes.left().value().getMainYaml().getBytes(); } else { - Either fromCassandra = getFromCassandra(esId); + Either fromCassandra = getFromCassandra(cassandraId); if (fromCassandra.isRight()) { return Either.right(fromCassandra.right().value()); } else { @@ -586,13 +704,36 @@ public class CsarUtils { } return Either.left(content); } - - private Either getFromCassandra(String esId) { - Either artifactResponse = artifactCassandraDao.getArtifact(esId); + + private Either getLatestSchemaFilesFromCassandra() { + Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION); + matcher.find(); + final String VERSION_FIRST_THREE_OCTATES = matcher.group(0); + Either, ActionStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(VERSION_FIRST_THREE_OCTATES, CONFORMANCE_LEVEL); + + if(specificSchemaFiles.isRight()){ + log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", VERSION_FIRST_THREE_OCTATES, CONFORMANCE_LEVEL); + return Either.right(specificSchemaFiles.right().value()); + } + + List listOfSchemas = specificSchemaFiles.left().value(); + + if(listOfSchemas.isEmpty()){ + log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", VERSION_FIRST_THREE_OCTATES, CONFORMANCE_LEVEL); + return Either.right(ActionStatus.GENERAL_ERROR); + } + + ESSdcSchemaFilesData schemaFile = listOfSchemas.iterator().next(); + + return Either.left(schemaFile.getPayloadAsArray()); + } + + private Either getFromCassandra(String cassandraId) { + Either artifactResponse = artifactCassandraDao.getArtifact(cassandraId); if (artifactResponse.isRight()) { log.debug("In createCsar fetching of artifact from CS failed"); - log.debug("Failed to fetch from Cassandra by id {} error {} ", esId, artifactResponse.right().value()); + log.debug("Failed to fetch from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value()); StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value()); ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); @@ -603,14 +744,20 @@ public class CsarUtils { } } - - private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) { - final String BLOCK_0_TEMPLATE = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: Definitions/%s\n"; - String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, csarVersion, createdBy, entryDef); + + private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) { + final String BLOCK_0_TEMPLATE = + "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n"; + String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel); return readyBlock; } + + private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) { + final String block0template = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: Definitions/%s\n\nName: csar.meta\nContent-Type: text/plain\n"; + return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef); + } - private Either, ResponseFormat> artifactGenerator(List artifactList, ArtifactType type, Component component) { + private Either, String> artifactGenerator(List artifactList, ArtifactType type, Component component) { ArtifactGenerationServiceImpl artifactGenerationServiceImpl = new ArtifactGenerationServiceImpl(); ArtifactTypes artifactTypes = new ArtifactTypes(); @@ -627,23 +774,739 @@ public class CsarUtils { artifactTypes.setArtifactTypes(artifactTypesList); String configJson = gson.toJson(artifactTypes); - GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson); + Map additionalParams = new HashMap<>(); + String version; + + if (UUID_NORMATIVE_NEW_VERSION.matcher(component.getVersion()).matches() ) { + version = component.getVersion(); + } else { + String[] versionParts = component.getVersion().split(LifecycleOperation.VERSION_DELIMETER_REGEXP); + Integer majorVersion = Integer.parseInt(versionParts[0]); + + version = (majorVersion + 1) + LifecycleOperation.VERSION_DELIMETER + "0"; + } + + additionalParams.put(AdditionalParams.ServiceVersion.getName(), version); + GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson, additionalParams); Map> errorData = generatedArtifacts.getErrorData(); if (!errorData.isEmpty()) { Set keySet = errorData.keySet(); + StringBuilder error = new StringBuilder(); for (String key : keySet) { List errorList = errorData.get(key); log.debug("The Artifact Generator Failed - {} with following: {}", key, errorList); + error.append(key + errorList); } - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), errorData.toString()); - return Either.right(responseFormat); + return Either.right(error.toString()); } return Either.left(generatedArtifacts.getResultData()); } + /** + * Extracts artifacts of VFCs from CSAR + * + * @param csar + * @return Map of > the contains Lists of artifacts according vfcToscaNamespace + */ + public static Map> extractVfcsArtifactsFromCsar(Map csar) { + + Map> artifacts = new HashMap<>(); + if (csar != null) { + log.debug("************* Going to extract VFCs artifacts from Csar. "); + Map>> collectedWarningMessages = new HashMap<>(); + csar.entrySet().stream() + // filter CSAR entry by node type artifact path + .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches()) + // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path + .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts)); + // add counter suffix to artifact labels + handleWarningMessages(collectedWarningMessages); + + } + return artifacts; + } + + /** + * Print warnings to log + * + * @param collectedWarningMessages + */ + public static void handleWarningMessages(Map>> collectedWarningMessages) { + collectedWarningMessages.entrySet().stream() + // for each vfc + .forEach(e -> e.getValue().stream() + // add each warning message to log + .forEach(args -> log.warn(e.getKey(), args.toArray()))); + + } + + private static void addExtractedVfcArtifact(ImmutablePair extractedVfcArtifact, Map> artifacts) { + if (extractedVfcArtifact != null) { + List currArtifactsList; + String vfcToscaNamespace = extractedVfcArtifact.getKey(); + if (artifacts.containsKey(vfcToscaNamespace)) { + currArtifactsList = artifacts.get(vfcToscaNamespace); + } else { + currArtifactsList = new ArrayList<>(); + artifacts.put(vfcToscaNamespace, currArtifactsList); + } + currArtifactsList.add(extractedVfcArtifact.getValue()); + } + } + + private static ImmutablePair extractVfcArtifact(Entry entry, Map>> collectedWarningMessages) { + ArtifactDefinition artifact; + String[] parsedCsarArtifactPath = entry.getKey().split("/"); + Either eitherArtifactGroupType = detectArtifactGroupType(parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages); + if (eitherArtifactGroupType.isLeft()) { + artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath, eitherArtifactGroupType.left().value()); + } else { + return null; + } + return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact); + } + + private static Either detectArtifactGroupType(String groupType, Map>> collectedWarningMessages) { + Either result; + try { + ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase()); + if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) { + String warningMessage = "Warning - unrecognized artifact group type {} was received."; + List messageArguments = new ArrayList<>(); + messageArguments.add(groupType); + if (!collectedWarningMessages.containsKey(warningMessage)) { + Set> messageArgumentLists = new HashSet<>(); + messageArgumentLists.add(messageArguments); + collectedWarningMessages.put(warningMessage, messageArgumentLists); + } else { + collectedWarningMessages.get(warningMessage).add(messageArguments); + } + + result = Either.right(false); + } else { + + result = Either.left(artifactGroupType); + } + } catch (Exception e) { + log.debug("detectArtifactGroupType failed with exception", e); + result = Either.right(false); + } + return result; + } + + private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry entry, Map>> collectedWarningMessages, String[] parsedCsarArtifactPath, ArtifactGroupTypeEnum artifactGroupType) { + ArtifactDefinition artifact; + artifact = new ArtifactDefinition(); + artifact.setArtifactGroupType(artifactGroupType); + artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages)); + artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1])); + artifact.setPayloadData(Base64.encodeBase64String(entry.getValue())); + artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName()); + artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName())); + artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR); + artifact.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(entry.getValue())); + return artifact; + } + + public static final class NonMetaArtifactInfo { + private final String path; + private final String artifactName; + private final String displayName; + private final String artifactLabel; + private final ArtifactTypeEnum artifactType; + private final ArtifactGroupTypeEnum artifactGroupType; + private String payloadData; + private String artifactChecksum; + private String artifactUniqueId; + + public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType, ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId) { + super(); + this.path = path; + this.artifactName = ValidationUtils.normalizeFileName(artifactName); + this.artifactType = artifactType; + this.artifactGroupType = artifactGroupType; + final int pointIndex = artifactName.lastIndexOf('.'); + if (pointIndex > 0) { + displayName = artifactName.substring(0, pointIndex); + } else { + displayName = artifactName; + } + this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName); + if (payloadData != null) { + this.payloadData = Base64.encodeBase64String(payloadData); + this.artifactChecksum = GeneralUtility.calculateMD5ByByteArray(payloadData); + } + this.artifactUniqueId = artifactUniqueId; + } + + public String getPath() { + return path; + } + + public String getArtifactName() { + return artifactName; + } + + public ArtifactTypeEnum getArtifactType() { + return artifactType; + } + + public String getDisplayName() { + return displayName; + } + + public ArtifactGroupTypeEnum getArtifactGroupType() { + return artifactGroupType; + } + + public String getArtifactLabel() { + return artifactLabel; + } + + public String getPayloadData() { + return payloadData; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public String getArtifactUniqueId() { + return artifactUniqueId; + } + + public void setArtifactUniqueId(String artifactUniqueId) { + this.artifactUniqueId = artifactUniqueId; + } + + } + + /** + * This method checks the artifact GroupType & Artifact Type.
+ * if there is any problem warning messages are added to collectedWarningMessages + * + * @param artifactPath + * @param collectedWarningMessages + * @return + */ + public static Either validateNonMetaArtifact(String artifactPath, byte[] payloadData, Map>> collectedWarningMessages) { + Either ret; + try { + String[] parsedArtifactPath = artifactPath.split("/"); + // Validate Artifact Group Type + Either eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1], collectedWarningMessages); + if (eitherGroupType.isLeft()) { + final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value(); + + // Validate Artifact Type + String artifactType = parsedArtifactPath[2]; + artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages); + + String artifactFileNameType = parsedArtifactPath[3]; + ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null)); + + } else { + ret = Either.right(eitherGroupType.right().value()); + } + } catch (Exception e) { + log.debug("detectArtifactGroupType failed with exception", e); + ret = Either.right(false); + } + return ret; + + } + + private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map>> collectedWarningMessages) { + String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized."; + return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName); + } + + private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map>> collectedWarningMessages) { + String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized."; + return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages); + } + + private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String warningMessage, Map>> collectedWarningMessages, String... arguments) { + + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName); + Map resourceValidTypeArtifacts = null; + + if(artifactGroupType != null){ + switch (artifactGroupType) { + case INFORMATIONAL: + resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() + .getResourceInformationalArtifacts(); + break; + case DEPLOYMENT: + resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() + .getResourceDeploymentArtifacts(); + break; + default: + break; + } + } + + Set validArtifactTypes = null; + if(resourceValidTypeArtifacts != null){ + validArtifactTypes = resourceValidTypeArtifacts.keySet(); + } + + if (validArtifactTypes == null || artifactType == null || !validArtifactTypes.contains(artifactType.getType())) { + List messageArguments = new ArrayList<>(); + messageArguments.add(receivedTypeName); + messageArguments.addAll(Arrays.asList(arguments)); + if (!collectedWarningMessages.containsKey(warningMessage)) { + Set> messageArgumentLists = new HashSet<>(); + messageArgumentLists.add(messageArguments); + collectedWarningMessages.put(warningMessage, messageArgumentLists); + } else { + collectedWarningMessages.get(warningMessage).add(messageArguments); + } + } + + return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType(); + } + + private Either writeAllFilesToScar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{ + ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts(); + + Either writeComponentArtifactsToSpecifiedtPath = writeComponentArtifactsToSpecifiedtPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest); + + if(writeComponentArtifactsToSpecifiedtPath.isRight()){ + return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); + } + + ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); + writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest); + + if(writeComponentArtifactsToSpecifiedtPath.isRight()){ + return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); + } + + Map componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts(); + Set keySet = componentInstancesArtifacts.keySet(); + + String currentPath = ARTIFACTS_PATH + RESOURCES_PATH; + for (String keyAssetName : keySet) { + ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName); + String pathWithAssetName = currentPath + keyAssetName + "/"; + writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest); + + if(writeComponentArtifactsToSpecifiedtPath.isRight()){ + return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); + } + } + + return Either.left(zipstream); + } + + private Either writeComponentArtifactsToSpecifiedtPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream, + String currentPath, boolean isInCertificationRequest) throws IOException { + Map componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); + //Keys are defined: + // folder name: _v. + //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0" + Set componentTypeArtifactsKeys = componentTypeArtifacts.keySet(); + for (String keyAssetName : componentTypeArtifactsKeys) { + ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName); + ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts(); + String pathWithAssetName = currentPath + keyAssetName + "/"; + Either writeArtifactsInfoToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest); + + if(writeArtifactsInfoToSpecifiedtPath.isRight()){ + return writeArtifactsInfoToSpecifiedtPath; + } + } + + return Either.left(zipstream); + } + + private Either writeArtifactsInfoToSpecifiedtPath(Component mainComponent, ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest) throws IOException { + Map>> artifactsInfo = currArtifactsInfo + .getArtifactsInfo(); + Set groupTypeEnumKeySet = artifactsInfo.keySet(); + + for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) { + String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + "/"; + + Map> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum); + Set artifactTypeEnumKeySet = artifactTypesMap.keySet(); + + for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) { + List artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum); + String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + "/"; + + Either writeArtifactDefinition = writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest); + + if(writeArtifactDefinition.isRight()){ + return writeArtifactDefinition; + } + } + } + + return Either.left(zip); + } + + private Either writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List artifactDefinitionList, + String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException { + + ComponentTypeEnum componentType = mainComponent.getComponentType(); + String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType(); + + for (ArtifactDefinition artifactDefinition : artifactDefinitionList) { + if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE + && artifactDefinition.getArtifactType().equals(heatEnvType)){ + continue; + } + + String esId = artifactDefinition.getEsId(); + byte[] payloadData = artifactDefinition.getPayloadData(); + String artifactFileName = artifactDefinition.getArtifactName(); + + if (payloadData == null) { + Either fromCassandra = getFromCassandra(esId); + + if (fromCassandra.isRight()) { + log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value()); + continue; + } + payloadData = fromCassandra.left().value(); + } + zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName)); + zip.write(payloadData); + } + + return Either.left(zip); + } + + /************************************ Artifacts Structure ******************************************************************/ + /** + * The artifacts Definition saved by their structure + */ + private class ArtifactsInfo { + //Key is the type of artifacts(Informational/Deployment) + //Value is a map between an artifact type and a list of all artifacts of this type + private Map>> artifactsInfoField; + + public ArtifactsInfo() { + this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class); + } + + public Map>> getArtifactsInfo() { + return artifactsInfoField; + } + + public List getFlatArtifactsListByType(ArtifactTypeEnum artifactType){ + List artifacts = new ArrayList<>(); + for (List artifactsByType:artifactsInfoField.get(artifactType).values()){ + artifacts.addAll(artifactsByType); + } + return artifacts; + } + + public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,Map> artifactsDefinition){ + artifactsInfoField.put(artifactGroup, artifactsDefinition); + } + + public boolean isEmpty() { + return artifactsInfoField.isEmpty(); + } + + } + + /** + * The artifacts of the component and of all its composed instances + * + */ + private class ComponentTypeArtifacts { + private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders) + private Map componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder) + + public ComponentTypeArtifacts() { + componentArtifacts = new ArtifactsInfo(); + componentInstancesArtifacts = new HashMap<>(); + } + + public ArtifactsInfo getComponentArtifacts() { + return componentArtifacts; + } + public void setComponentArtifacts(ArtifactsInfo artifactsInfo) { + this.componentArtifacts = artifactsInfo; + } + public Map getComponentInstancesArtifacts() { + return componentInstancesArtifacts; + } + public void setComponentInstancesArtifacts(Map componentInstancesArtifacts) { + this.componentInstancesArtifacts = componentInstancesArtifacts; + } + + public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) { + componentInstancesArtifacts.put(normalizedName, artifactsInfo); + } + + } + + private class ComponentArtifacts { + //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component) + private ComponentTypeArtifacts mainTypeAndCIArtifacts; + //artifacts of all component types mapped by their tosca name + private Map componentTypeArtifacts; + + public ComponentArtifacts(){ + mainTypeAndCIArtifacts = new ComponentTypeArtifacts(); + componentTypeArtifacts = new HashMap<>(); + } + + public ComponentTypeArtifacts getMainTypeAndCIArtifacts() { + return mainTypeAndCIArtifacts; + } + + public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { + this.mainTypeAndCIArtifacts = componentInstanceArtifacts; + } + + public Map getComponentTypeArtifacts() { + return componentTypeArtifacts; + } + + public void setComponentTypeArtifacts(Map componentTypeArtifacts) { + this.componentTypeArtifacts = componentTypeArtifacts; + } + } + + private class CsarDefinition { + private ComponentArtifacts componentArtifacts; + + // add list of tosca artifacts and meta describes CSAR zip root + + public CsarDefinition(ComponentArtifacts componentArtifacts) { + this.componentArtifacts = componentArtifacts; + } + + public ComponentArtifacts getComponentArtifacts() { + return componentArtifacts; + } + } + + /************************************ Artifacts Structure END******************************************************************/ + + private Either collectComponentCsarDefinition(Component component){ + ComponentArtifacts componentArtifacts = new ComponentArtifacts(); + Component updatedComponent = component; + + //get service to receive the AII artifacts uploaded to the service + if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) { + Either getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId()); + + if(getServiceResponse.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value()); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + + updatedComponent = getServiceResponse.left().value(); + } + + //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder + ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts(); + ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent); + componentInstanceArtifacts.setComponentArtifacts(artifactsInfo); + componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts); + + Map resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version) + //get the component instances + List componentInstances = updatedComponent.getComponentInstances(); + if (componentInstances!=null){ + for (ComponentInstance componentInstance:componentInstances){ + //call recursive to find artifacts for all the path + Either collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( + updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts); + if (collectComponentInstanceArtifacts.isRight()){ + return Either.right(collectComponentInstanceArtifacts.right().value()); + } + } + } + + if(log.isDebugEnabled()){ + printResult(componentArtifacts,updatedComponent.getName()); + } + + return Either.left(new CsarDefinition(componentArtifacts)); + } + + private void printResult(ComponentArtifacts componentArtifacts, String name) { + StringBuilder result = new StringBuilder(); + result.append("Artifacts of main component " + name + "\n"); + ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); + printArtifacts(componentInstanceArtifacts); + result.append("Type Artifacts\n"); + for (Map.Entry typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){ + result.append("Folder " + typeArtifacts.getKey() + "\n"); + result.append(printArtifacts(typeArtifacts.getValue())); + } + + if(log.isDebugEnabled()){ + log.debug(result.toString()); + } + } + + private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { + StringBuilder result = new StringBuilder(); + ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts(); + Map>> componetArtifacts = artifactsInfo.getArtifactsInfo(); + printArtifacts(componetArtifacts); + result = result.append("Resources\n"); + for (Map.Entry resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){ + result.append("Folder" + resourceInstance.getKey() + "\n"); + result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo())); + } + + return result.toString(); + } + + private String printArtifacts(Map>> componetArtifacts) { + StringBuilder result = new StringBuilder(); + for (Map.Entry>> artifactGroup:componetArtifacts.entrySet()){ + result.append(" " + artifactGroup.getKey().getType()); + for (Map.Entry> groupArtifacts:artifactGroup.getValue().entrySet()){ + result.append(" " + groupArtifacts.getKey().getType()); + for (ArtifactDefinition artifact:groupArtifacts.getValue()){ + result.append(" " + artifact.getArtifactDisplayName()); + } + } + } + + return result.toString(); + } + + private ComponentTypeArtifacts collectComponentTypeArtifacts(Map resourcesArtifacts, ComponentInstance componentInstance, + Resource fetchedComponent) { + String toscaComponentName = componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion(); + + ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName); + //if there are no artifacts for this component type we need to fetch and build them + if (componentArtifactsInfo==null){ + ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent); + componentArtifactsInfo = new ComponentTypeArtifacts(); + if (!componentArtifacts.isEmpty()){ + componentArtifactsInfo.setComponentArtifacts(componentArtifacts); + resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo); + } + } + return componentArtifactsInfo; + } + + private Either collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance, + Map resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) { + //1. get the component instance component + String componentUid = componentInstance.getComponentUid(); + Either resource = toscaOperationFacade.getToscaElement(componentUid); + if (resource.isRight()) { + log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION, + parentComponent.getComponentType().getValue(), parentComponent.getUUID(), + componentInstance.getOriginType().getComponentType().getValue(), componentUid)); + } + Resource fetchedComponent = resource.left().value(); + + //2. fill the artifacts for the current component parent type + ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts, componentInstance, fetchedComponent); + + //3. find the artifacts specific to the instance + Map> componentInstanceSpecificInformationalArtifacts = + getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(), + componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL); + Map> componentInstanceSpecificDeploymentArtifacts = + getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(), + componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT); + + //4. add the instances artifacts to the component type + ArtifactsInfo artifactsInfo = new ArtifactsInfo(); + if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){ + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts); + } + if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){ + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts); + } + if (!artifactsInfo.isEmpty()){ + instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo); + } + + //5. do the same for all the component instances + List componentInstances = fetchedComponent.getComponentInstances(); + if (componentInstances!=null){ + for (ComponentInstance childComponentInstance:componentInstances){ + Either collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( + fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts); + if (collectComponentInstanceArtifacts.isRight()){ + return collectComponentInstanceArtifacts; + } + } + } + + return Either.left(true); + } + + private Map> getComponentInstanceSpecificArtifacts(Map componentArtifacts, + Map>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) { + Map> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance + + Map> artifactsByTypeOfComponentInstance = new EnumMap<>(ArtifactTypeEnum.class); + if (componentArtifacts!=null){ + for (ArtifactDefinition artifact:componentArtifacts.values()){ + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); + List parentArtifactsByType = null; + if (parentArtifacts!=null){ + parentArtifactsByType = parentArtifacts.get(artifactType); + } + //the artifact is of instance + if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){ + List typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType); + if (typeArtifacts == null){ + typeArtifacts = new ArrayList<>(); + artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts); + } + typeArtifacts.add(artifact); + } + } + } + + return artifactsByTypeOfComponentInstance; + } + + private ArtifactsInfo collectComponentArtifacts(Component component) { + Map informationalArtifacts = component.getArtifacts(); + Map> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts); + Map deploymentArtifacts = component.getDeploymentArtifacts(); + Map> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts); + ArtifactsInfo artifactsInfo = new ArtifactsInfo(); + if (!informationalArtifactsByType.isEmpty()){ + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType); + } + if (!deploymentArtifactsByType.isEmpty() ){ + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType); + } + + return artifactsInfo; + } + + private Map> collectGroupArtifacts(Map componentArtifacts) { + Map> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class); + for (ArtifactDefinition artifact:componentArtifacts.values()){ + if (artifact.getArtifactUUID()!=null){ + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); + List typeArtifacts = artifactsByType.get(artifactType); + if (typeArtifacts==null){ + typeArtifacts = new ArrayList<>(); + artifactsByType.put(artifactType, typeArtifacts); + } + typeArtifacts.add(artifact); + } + } + return artifactsByType; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java index 544b85361d..af3b73dc97 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java @@ -71,11 +71,10 @@ public class PropertyConvertor { Map properties = new HashMap<>(); // take only the properties of this resource - props.stream().filter(p -> component.getUniqueId().equals(p.getParentUniqueId())).forEach(property -> { + props.stream().filter(p -> p.getOwnerId() == null || p.getOwnerId().equals(component.getUniqueId())).forEach(property -> { ToscaProperty prop = convertProperty(dataTypes, property, false); properties.put(property.getName(), prop); - }); if (!properties.isEmpty()) { toscaNodeType.setProperties(properties); @@ -172,7 +171,7 @@ public class PropertyConvertor { if (innerConverter != null) { convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes); } else { - convertedValue = mapConverterInst.convertDataTypeToToscaMap(innerType, dataTypes, innerConverter, isScalar, jsonElement); + convertedValue = mapConverterInst.convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement); } } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java index 1bf940ffc0..072861ba3a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java @@ -25,36 +25,44 @@ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; -import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.function.Supplier; import java.util.stream.Collectors; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.apache.commons.lang3.tuple.Triple; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupInstance; import org.openecomp.sdc.be.model.GroupProperty; import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.operations.api.IResourceOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter; import org.openecomp.sdc.be.tosca.model.IToscaMetadata; import org.openecomp.sdc.be.tosca.model.SubstitutionMapping; import org.openecomp.sdc.be.tosca.model.ToscaCapability; @@ -67,7 +75,6 @@ import org.openecomp.sdc.be.tosca.model.ToscaTemplate; import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement; import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate; import org.openecomp.sdc.be.tosca.model.VfModuleToscaMetadata; -import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -94,31 +101,56 @@ public class ToscaExportHandler { private ApplicationDataTypeCache dataTypeCache; @Autowired - private IResourceOperation resourceOperation; + private ToscaOperationFacade toscaOperationFacade; private CapabiltyRequirementConvertor capabiltyRequirementConvertor = CapabiltyRequirementConvertor.getInstance(); private PropertyConvertor propertyConvertor = PropertyConvertor.getInstance(); + private static Logger log = LoggerFactory.getLogger(ToscaExportHandler.class.getName()); public static final String TOSCA_VERSION = "tosca_simple_yaml_1_0"; public static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service."; public static final String IMPORTS_FILE_KEY = "file"; public static final String TOSCA_TEMPLATE_NAME = "-template.yml"; + public static final String TOSCA_INTERFACE_NAME = "-interface.yml"; public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate"; public static final String VF_MODULE_TYPE_KEY = "vf_module_type"; public static final String VF_MODULE_DESC_KEY = "vf_module_description"; public static final String VOLUME_GROUP_KEY = "volume_group"; public static final String VF_MODULE_TYPE_BASE = "Base"; public static final String VF_MODULE_TYPE_EXPANSION = "Expansion"; - + public static final List>> DEFAULT_IMPORTS = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultImports(); + + + public Either exportComponent(Component component) { Either toscaTemplateRes = convertToToscaTemplate(component); if (toscaTemplateRes.isRight()) { return Either.right(toscaTemplateRes.right().value()); } + + ToscaTemplate toscaTemplate = toscaTemplateRes.left().value(); + ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate); + return Either.left(toscaRepresentation); + } + public Either exportComponentInterface(Component component) { + ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION); + toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS)); + Map nodeTypes = new HashMap<>(); + Either toscaTemplateRes = convertInterfaceNodeType(component, toscaTemplate, nodeTypes); + if (toscaTemplateRes.isRight()) { + return Either.right(toscaTemplateRes.right().value()); + } + + toscaTemplate = toscaTemplateRes.left().value(); + ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate); + return Either.left(toscaRepresentation); + } + + public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) { CustomRepresenter representer = new CustomRepresenter(); DumperOptions options = new DumperOptions(); options.setAllowReadOnlyProperties(false); @@ -127,7 +159,6 @@ public class ToscaExportHandler { options.setDefaultFlowStyle(FlowStyle.FLOW); options.setCanonical(false); - ToscaTemplate toscaTemplate = toscaTemplateRes.left().value(); representer.addClassTag(toscaTemplate.getClass(), Tag.MAP); representer.setPropertyUtils(new UnsortedPropertyUtils()); @@ -143,13 +174,14 @@ public class ToscaExportHandler { ToscaRepresentation toscaRepresentation = new ToscaRepresentation(); toscaRepresentation.setMainYaml(sb.toString()); toscaRepresentation.setDependencies(toscaTemplate.getDependencies()); - - return Either.left(toscaRepresentation); + + return toscaRepresentation; } - + public Either getDependencies(Component component) { ToscaTemplate toscaTemplate = new ToscaTemplate(null); - Either>, ToscaError> fillImports = fillImports(component, toscaTemplate); + Either>, ToscaError> fillImports = fillImports(component, + toscaTemplate); if (fillImports.isRight()) { return Either.right(fillImports.right().value()); } @@ -157,17 +189,17 @@ public class ToscaExportHandler { } private Either convertToToscaTemplate(Component component) { - log.debug("start tosca export for {}", component.getUniqueId()); + log.trace("start tosca export for {}", component.getUniqueId()); ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION); - toscaTemplate.setMetadata(convertMetadata(component, false)); - - Map node_types = new HashMap<>(); - if (ToscaUtils.isNodeType(component)) { - log.debug("convert component as node type"); - return convertNodeType(component, toscaTemplate, node_types); + toscaTemplate.setMetadata(convertMetadata(component)); + toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS)); + Map nodeTypes = new HashMap<>(); + if (ToscaUtils.isAtomicType(component)) { + log.trace("convert component as node type"); + return convertNodeType(component, toscaTemplate, nodeTypes); } else { - log.debug("convert component as topology template"); + log.trace("convert component as topology template"); return convertToscaTemplate(component, toscaTemplate); } @@ -175,7 +207,8 @@ public class ToscaExportHandler { private Either convertToscaTemplate(Component component, ToscaTemplate toscaNode) { - Either>, ToscaError> importsRes = fillImports(component, toscaNode); + Either>, ToscaError> importsRes = fillImports(component, + toscaNode); if (importsRes.isRight()) { return Either.right(importsRes.right().value()); } @@ -189,47 +222,50 @@ public class ToscaExportHandler { } Map dataTypes = dataTypesEither.left().value(); - ToscaTopolgyTemplate topology_template = new ToscaTopolgyTemplate(); + ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); - Either inputs = fillInputs(component, topology_template, dataTypes); + Either inputs = fillInputs(component, topologyTemplate, dataTypes); if (inputs.isRight()) { return Either.right(inputs.right().value()); } - topology_template = inputs.left().value(); + topologyTemplate = inputs.left().value(); List componentInstances = component.getComponentInstances(); - Map> componentInstancesProperties = component.getComponentInstancesProperties(); + Map> componentInstancesProperties = component + .getComponentInstancesProperties(); List groups = component.getGroups(); if (componentInstances != null && !componentInstances.isEmpty()) { - Either, ToscaError> node_templates = convertNodeTemplates(component, componentInstances, componentInstancesProperties, componentCache, dataTypes); - if (node_templates.isRight()) { - return Either.right(node_templates.right().value()); + Either, ToscaError> nodeTemplates = convertNodeTemplates(component, + componentInstances, componentInstancesProperties, componentCache, dataTypes, topologyTemplate); + if (nodeTemplates.isRight()) { + return Either.right(nodeTemplates.right().value()); } log.debug("node templates converted"); - topology_template.setNode_templates(node_templates.left().value()); + topologyTemplate.setNode_templates(nodeTemplates.left().value()); } + Map groupsMap = null; if (groups != null && !groups.isEmpty()) { - Map groupsMap = new HashMap(); + groupsMap = new HashMap(); for (GroupDefinition group : groups) { - ToscaGroupTemplate toscaGroup = convertGroup(group, component); + ToscaGroupTemplate toscaGroup = convertGroup(group); groupsMap.put(group.getName(), toscaGroup); } - topology_template.setGroups(groupsMap); log.debug("groups converted"); - + topologyTemplate.addGroups(groupsMap); } - SubstitutionMapping substitutionMapping = new SubstitutionMapping(); String toscaResourceName = null; switch (component.getComponentType()) { case RESOURCE: - toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName(); + toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition() + .getMetadataDataDefinition()).getToscaResourceName(); break; case SERVICE: - toscaResourceName = SERVICE_NODE_TYPE_PREFIX + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); + toscaResourceName = SERVICE_NODE_TYPE_PREFIX + + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); break; default: log.debug("Not supported component type {}", component.getComponentType()); @@ -237,25 +273,27 @@ public class ToscaExportHandler { } substitutionMapping.setNode_type(toscaResourceName); - Either capabilities = convertCapabilities(component, substitutionMapping, dataTypes); + Either capabilities = convertCapabilities(component, substitutionMapping, + dataTypes); if (capabilities.isRight()) { return Either.right(capabilities.right().value()); } substitutionMapping = capabilities.left().value(); - Either requirements = capabiltyRequirementConvertor.convertRequirements(component, substitutionMapping); + Either requirements = capabiltyRequirementConvertor.convertSubstitutionMappingRequirements(component, substitutionMapping); if (requirements.isRight()) { return Either.right(requirements.right().value()); } substitutionMapping = requirements.left().value(); - topology_template.setSubstitution_mappings(substitutionMapping); + topologyTemplate.setSubstitution_mappings(substitutionMapping); - toscaNode.setTopology_template(topology_template); + toscaNode.setTopology_template(topologyTemplate); return Either.left(toscaNode); } - private Either fillInputs(Component component, ToscaTopolgyTemplate topology_template, Map dataTypes) { + private Either fillInputs(Component component, + ToscaTopolgyTemplate topologyTemplate, Map dataTypes) { if (log.isDebugEnabled()) log.debug("fillInputs for component {}", component.getUniqueId()); List inputDef = component.getInputs(); @@ -266,14 +304,19 @@ public class ToscaExportHandler { ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false); inputs.put(i.getName(), property); }); - if (inputs != null && !inputs.isEmpty()) { - topology_template.setInputs(inputs); + if (!inputs.isEmpty()) { + topologyTemplate.setInputs(inputs); } } - return Either.left(topology_template); + return Either.left(topologyTemplate); + } + + private ToscaMetadata convertMetadata(Component component) { + return convertMetadata(component, false, null); } - private ToscaMetadata convertMetadata(Component component, boolean isInstance) { + private ToscaMetadata convertMetadata(Component component, boolean isInstance, + ComponentInstance componentInstance) { ToscaMetadata toscaMetadata = new ToscaMetadata(); toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); toscaMetadata.setInvariantUUID(component.getInvariantUUID()); @@ -286,6 +329,7 @@ public class ToscaExportHandler { if (isInstance) { toscaMetadata.setVersion(component.getVersion()); + toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID()); } switch (component.getComponentType()) { case RESOURCE: @@ -300,8 +344,10 @@ public class ToscaExportHandler { case SERVICE: toscaMetadata.setType(component.getComponentType().getValue()); if (!isInstance) { - toscaMetadata.setServiceEcompNaming(false); - toscaMetadata.setServiceHoming(false); + // DE268546 + toscaMetadata.setServiceEcompNaming(((Service)component).isEcompGeneratedNaming()); + toscaMetadata.setEcompGeneratedNaming(((Service)component).isEcompGeneratedNaming()); + toscaMetadata.setNamingPolicy(((Service)component).getNamingPolicy()); } break; default: @@ -310,38 +356,59 @@ public class ToscaExportHandler { return toscaMetadata; } - private Either>, ToscaError> fillImports(Component component, ToscaTemplate toscaTemplate) { + private Either>, ToscaError> fillImports(Component component, + ToscaTemplate toscaTemplate) { Map componentCache = new HashMap<>(); - if (!ToscaUtils.isNodeType(component)) { + + if (!ToscaUtils.isAtomicType(component)) { List componentInstances = component.getComponentInstances(); if (componentInstances != null && !componentInstances.isEmpty()) { - List>> imports = new LinkedList>>(); + + List>> additionalImports = + toscaTemplate.getImports() == null ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports()); + List> dependecies = new ArrayList<>(); + Map toscaArtifacts = component.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + + Map> importsListMember = new HashMap<>(); + Map interfaceFiles = new HashMap<>(); + interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName())); + StringBuilder keyNameBuilder = new StringBuilder(); + keyNameBuilder.append(component.getComponentType().toString().toLowerCase()); + keyNameBuilder.append("-"); + keyNameBuilder.append(component.getName()); + keyNameBuilder.append("-interface"); + importsListMember.put(keyNameBuilder.toString(), interfaceFiles); + additionalImports.add(importsListMember); + componentInstances.forEach(ci -> { - createDependency(componentCache, imports, dependecies, ci); + createDependency(componentCache, additionalImports, dependecies, ci); }); - toscaTemplate.setImports(imports); toscaTemplate.setDependencies(dependecies); + toscaTemplate.setImports(additionalImports); } } else { log.debug("currently imports supported for VF and service only"); - } + } return Either.left(new ImmutablePair>(toscaTemplate, componentCache)); } - private void createDependency(Map componentCache, List>> imports, List> dependecies, ComponentInstance ci) { + private void createDependency(Map componentCache, List>> imports, + List> dependecies, ComponentInstance ci) { Map files = new HashMap<>(); Map> importsListMember = new HashMap<>(); + StringBuilder keyNameBuilder; Component componentRI = componentCache.get(ci.getComponentUid()); if (componentRI == null) { // all resource must be only once! - Either resource = resourceOperation.getResource(ci.getComponentUid(), true); + Either resource = toscaOperationFacade.getToscaFullElement(ci.getComponentUid()); if (resource.isRight()) { log.debug("Failed to fetch resource with id {} for instance {}"); } - Resource fetchedComponent = resource.left().value(); + Component fetchedComponent = resource.left().value(); componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent); componentRI = fetchedComponent; @@ -350,16 +417,34 @@ public class ToscaExportHandler { if (artifactDefinition != null) { String artifactName = artifactDefinition.getArtifactName(); files.put(IMPORTS_FILE_KEY, artifactName); - importsListMember.put(ci.getComponentName(), files); - dependecies.add(new ImmutableTriple(artifactName, artifactDefinition.getEsId(), fetchedComponent)); + keyNameBuilder = new StringBuilder(); + keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase()); + keyNameBuilder.append("-"); + keyNameBuilder.append(ci.getComponentName()); + importsListMember.put(keyNameBuilder.toString(), files); + imports.add(importsListMember); + dependecies.add(new ImmutableTriple(artifactName, + artifactDefinition.getEsId(), fetchedComponent)); + + if(!ToscaUtils.isAtomicType(componentRI)) { + importsListMember = new HashMap<>(); + Map interfaceFiles = new HashMap<>(); + interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName)); + keyNameBuilder.append("-interface"); + importsListMember.put(keyNameBuilder.toString(), interfaceFiles); + imports.add(importsListMember); + } } } - if (!importsListMember.isEmpty()) { - imports.add(importsListMember); - } } - private Either convertNodeType(Component component, ToscaTemplate toscaNode, Map node_types) { + public static String getInterfaceFilename(String artifactName) { + String interfaceFileName = artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME; + return interfaceFileName; + } + + private Either convertNodeType(Component component, ToscaTemplate toscaNode, + Map nodeTypes) { log.debug("start convert node type for {}", component.getUniqueId()); ToscaNodeType toscaNodeType = createNodeType(component); @@ -370,13 +455,51 @@ public class ToscaExportHandler { } Map dataTypes = dataTypesEither.left().value(); - Either properties = propertyConvertor.convertProperties(component, toscaNodeType, dataTypes); + Either properties = propertyConvertor.convertProperties(component, toscaNodeType, + dataTypes); if (properties.isRight()) { return Either.right(properties.right().value()); } toscaNodeType = properties.left().value(); log.debug("Properties converted for {}", component.getUniqueId()); + //Extracted to method for code reuse + return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes); + } + + private Either convertInterfaceNodeType(Component component, ToscaTemplate toscaNode, + Map nodeTypes) { + log.debug("start convert node type for {}", component.getUniqueId()); + ToscaNodeType toscaNodeType = createNodeType(component); + + Either, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + if (dataTypesEither.isRight()) { + log.debug("Failed to fetch all data types :", dataTypesEither.right().value()); + return Either.right(ToscaError.GENERAL_ERROR); + } + + Map dataTypes = dataTypesEither.left().value(); + + List inputDef = component.getInputs(); + Map inputs = new HashMap<>(); + + if (inputDef != null) { + inputDef.forEach(i -> { + ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false); + inputs.put(i.getName(), property); + }); + if (!inputs.isEmpty()) { + toscaNodeType.setProperties(inputs); + } + } + + //Extracted to method for code reuse + return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes); + } + + private Either convertReqCapAndTypeName(Component component, ToscaTemplate toscaNode, + Map nodeTypes, ToscaNodeType toscaNodeType, + Map dataTypes) { Either capabilities = convertCapabilities(component, toscaNodeType, dataTypes); if (capabilities.isRight()) { return Either.right(capabilities.right().value()); @@ -384,150 +507,323 @@ public class ToscaExportHandler { toscaNodeType = capabilities.left().value(); log.debug("Capabilities converted for {}", component.getUniqueId()); - Either requirements = capabiltyRequirementConvertor.convertRequirements(component, toscaNodeType); + Either requirements = capabiltyRequirementConvertor.convertRequirements(component, + toscaNodeType); if (requirements.isRight()) { return Either.right(requirements.right().value()); } toscaNodeType = requirements.left().value(); log.debug("Requirements converted for {}", component.getUniqueId()); - String toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName(); - node_types.put(toscaResourceName, toscaNodeType); - toscaNode.setNode_types(node_types); + + String toscaResourceName; + switch (component.getComponentType()) { + case RESOURCE: + toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition() + .getMetadataDataDefinition()).getToscaResourceName(); + break; + case SERVICE: + toscaResourceName = SERVICE_NODE_TYPE_PREFIX + + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); + break; + default: + log.debug("Not supported component type {}", component.getComponentType()); + return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); + } + + nodeTypes.put(toscaResourceName, toscaNodeType); + toscaNode.setNode_types(nodeTypes); log.debug("finish convert node type for {}", component.getUniqueId()); return Either.left(toscaNode); } - private Either, ToscaError> convertNodeTemplates(Component component, List componentInstances, Map> componentInstancesProperties, - Map componentCache, Map dataTypes) { - log.debug("start convert topology template for {} for type {}", component.getUniqueId(), component.getComponentType()); - Map node_templates = new HashMap<>(); + private Either, ToscaError> convertNodeTemplates(Component component, + List componentInstances, + Map> componentInstancesProperties, + Map componentCache, Map dataTypes, + ToscaTopolgyTemplate topologyTemplate) { + Either, ToscaError> convertNodeTemplatesRes = null; + log.debug("start convert topology template for {} for type {}", component.getUniqueId(), + component.getComponentType()); + Map nodeTemplates = new HashMap<>(); + Map> componentInstancesInputs = component.getComponentInstancesInputs(); + + Map groupsMap = null; for (ComponentInstance componentInstance : componentInstances) { ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate(); nodeTemplate.setType(componentInstance.getToscaComponentName()); - Either requirements = convertComponentInstanceRequirements(component, componentInstance, component.getComponentInstancesRelations(), nodeTemplate); + Either requirements = convertComponentInstanceRequirements(component, + componentInstance, component.getComponentInstancesRelations(), nodeTemplate); if (requirements.isRight()) { - return Either.right(requirements.right().value()); + convertNodeTemplatesRes = Either.right(requirements.right().value()); + break; } - log.debug("Component instance Requirements converted for instance {}", componentInstance.getUniqueId()); + String instanceUniqueId = componentInstance.getUniqueId(); + log.debug("Component instance Requirements converted for instance {}", instanceUniqueId); nodeTemplate = requirements.left().value(); Component componentOfInstance = componentCache.get(componentInstance.getComponentUid()); - nodeTemplate.setMetadata(convertMetadata(componentOfInstance, true)); + nodeTemplate.setMetadata(convertMetadata(componentOfInstance, true, componentInstance)); - Either capabilties = capabiltyRequirementConvertor.convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate); + Either capabilties = capabiltyRequirementConvertor + .convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate); if (capabilties.isRight()) { - return Either.right(requirements.right().value()); + convertNodeTemplatesRes = Either.right(requirements.right().value()); + break; } - log.debug("Component instance Capabilties converted for instance {}", componentInstance.getUniqueId()); + log.debug("Component instance Capabilties converted for instance {}", instanceUniqueId); nodeTemplate = capabilties.left().value(); + Map props = new HashMap<>(); - if (componentInstancesProperties.containsKey(componentInstance.getUniqueId())) { - Map props = null; - List propList = componentInstancesProperties.get(componentInstance.getUniqueId()); - List collect = propList.stream().filter(e -> e.getValueUniqueUid() != null && !e.getValueUniqueUid().isEmpty()).collect(Collectors.toList()); - if (collect != null && !collect.isEmpty()) { - props = new HashMap(); - for (ComponentInstanceProperty prop : collect) { - Object convertedValue = convertInstanceProperty(dataTypes, componentInstance, prop); - props.put(prop.getName(), convertedValue); - } + if (componentOfInstance.getComponentType() == ComponentTypeEnum.RESOURCE) { + // Adds the properties of parent component to map + addPropertiesOfParentComponent(dataTypes, componentInstance, componentOfInstance, props); + } + + if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) { + addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, componentInstance, + instanceUniqueId, props); + } + + if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) { + addComponentInstanceInputs(dataTypes, componentInstancesInputs, componentInstance, instanceUniqueId, + props); + } + if (props != null && !props.isEmpty()) { + nodeTemplate.setProperties(props); + } + + List groupInstances = componentInstance.getGroupInstances(); + if (groupInstances != null) { + if (groupsMap == null) { + groupsMap = new HashMap<>(); } - if (props != null && !props.isEmpty()) { - nodeTemplate.setProperties(props); + for (GroupInstance groupInst : groupInstances) { + ToscaGroupTemplate toscaGroup = convertGroupInstance(groupInst); + String keyName = groupInst.getGroupName(); + + groupsMap.put(keyName, toscaGroup); } } - node_templates.put(componentInstance.getName(), nodeTemplate); + + nodeTemplates.put(componentInstance.getName(), nodeTemplate); + } + if (groupsMap != null) { + log.debug("instance groups added"); + topologyTemplate.addGroups(groupsMap); + } + + if (convertNodeTemplatesRes == null) { + convertNodeTemplatesRes = Either.left(nodeTemplates); + } + log.debug("finish convert topology template for {} for type {}", component.getUniqueId(), + component.getComponentType()); + return convertNodeTemplatesRes; + } + + private void addComponentInstanceInputs(Map dataTypes, + Map> componentInstancesInputs, ComponentInstance componentInstance, + String instanceUniqueId, Map props) { + + List instanceInputsList = componentInstancesInputs.get(instanceUniqueId); + if (instanceInputsList != null) { + instanceInputsList.forEach(input -> { + Supplier supplier = () -> input.getValue(); + convertAndAddValue(dataTypes, componentInstance, props, input, supplier); + }); + } + } + + private void addPropertiesOfComponentInstance( + Map> componentInstancesProperties, + Map dataTypes, ComponentInstance componentInstance, String instanceUniqueId, + Map props) { + + if (!MapUtils.isEmpty(componentInstancesProperties)) { + componentInstancesProperties.get(instanceUniqueId).stream() + // Filters out properties with empty ValueUniqueUid + .filter(e -> e.getValue() != null && !e.getValue().isEmpty() ) + // Collects filtered properties to List + .collect(Collectors.toList()).stream() + // Converts and adds each value to property map + .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop, + () -> prop.getValue())); + } + } + + private void addPropertiesOfParentComponent(Map dataTypes, + ComponentInstance componentInstance, Component componentOfInstance, Map props) { + + List componentProperties = ((Resource) componentOfInstance).getProperties(); + if (!CollectionUtils.isEmpty(componentProperties)) { + componentProperties.stream() + // Filters out properties with empty default values + .filter(prop -> !StringUtils.isEmpty(prop.getDefaultValue())) + // Collects filtered properties to List + .collect(Collectors.toList()).stream() + // Converts and adds each value to property map + .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop, + () -> prop.getDefaultValue())); + } + } + + /** + * @param dataTypes + * @param componentInstance + * @param props + * @param prop + * @param supplier + */ + private void convertAndAddValue(Map dataTypes, ComponentInstance componentInstance, + Map props, PropertyDefinition prop, Supplier supplier) { + Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier); + if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) { + props.put(prop.getName(), convertedValue); } - log.debug("finish convert topology template for {} for type {}", component.getUniqueId(), component.getComponentType()); - return Either.left(node_templates); } - private Object convertInstanceProperty(Map dataTypes, ComponentInstance componentInstance, ComponentInstanceProperty prop) { - log.debug("Convert property {} for instance {}", prop.getName(), componentInstance.getUniqueId()); - String propertyType = prop.getType(); + private Object convertValue(Map dataTypes, + ComponentInstance componentInstance, T input, Supplier supplier) { + log.debug("Convert property or input value {} for instance {}", input.getName(), + componentInstance.getUniqueId()); + String propertyType = input.getType(); String innerType = null; - if (prop.getSchema() != null && prop.getSchema().getProperty() != null) { - innerType = prop.getSchema().getProperty().getType(); + if (input.getSchema() != null && input.getSchema().getProperty() != null) { + innerType = input.getSchema().getProperty().getType(); } - Object convertedValue = propertyConvertor.convertToToscaObject(propertyType, prop.getValue(), innerType, dataTypes); - return convertedValue; + return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType, dataTypes); } - private ToscaGroupTemplate convertGroup(GroupDefinition group, Component component) { + private ToscaGroupTemplate convertGroup(GroupDefinition group) { ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate(); Map members = group.getMembers(); - toscaGroup.setType(group.getType()); if (members != null) toscaGroup.setMembers(new ArrayList(members.keySet())); - boolean isVfModule = group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE) ? true : false; + Supplier supplGroupType = () -> group.getType(); + Supplier supplDescription = () -> group.getDescription(); + Supplier> supplProperties = () -> group.convertToGroupProperties(); + Supplier supplgroupName = () -> group.getName(); + Supplier supplInvariantUUID = () -> group.getInvariantUUID(); + Supplier supplGroupUUID = () -> group.getGroupUUID(); + Supplier supplVersion = () -> group.getVersion(); + + IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName, + supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType); + toscaGroup.setMetadata(toscaMetadata); + return toscaGroup; + } + + private ToscaGroupTemplate convertGroupInstance(GroupInstance groupInstance) { + ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate(); + + Supplier supplGroupType = () -> groupInstance.getType(); + Supplier supplDescription = () -> groupInstance.getDescription(); + Supplier> supplProperties = () -> groupInstance.convertToGroupInstancesProperties(); + Supplier supplgroupName = () -> groupInstance.getGroupName(); + Supplier supplInvariantUUID = () -> groupInstance.getInvariantUUID(); + Supplier supplGroupUUID = () -> groupInstance.getGroupUUID(); + Supplier supplVersion = () -> groupInstance.getVersion(); + + IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName, + supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType); + + toscaMetadata.setCustomizationUUID(groupInstance.getCustomizationUUID()); + toscaGroup.setMetadata(toscaMetadata); + return toscaGroup; + } + + private IToscaMetadata fillGroup(ToscaGroupTemplate toscaGroup, Supplier> props, + Supplier description, Supplier groupName, Supplier invariantUUID, + Supplier groupUUID, Supplier version, Supplier groupType) { + boolean isVfModule = groupType.get().equals(Constants.DEFAULT_GROUP_VF_MODULE) ? true : false; + toscaGroup.setType(groupType.get()); + IToscaMetadata toscaMetadata; if (!isVfModule) { toscaMetadata = new ToscaMetadata(); } else { toscaMetadata = new VfModuleToscaMetadata(); - Map properties = new HashMap<>(); - for (GroupProperty gp : group.getProperties()) { + Map properties = fillGroupProperties(props.get()); + + properties.put(VF_MODULE_DESC_KEY, description.get()); + toscaGroup.setProperties(properties); + } + toscaMetadata.setName(groupName.get()); + toscaMetadata.setInvariantUUID(invariantUUID.get()); + toscaMetadata.setUUID(groupUUID.get()); + toscaMetadata.setVersion(version.get()); + return toscaMetadata; + } + + private Map fillGroupProperties(List groupProps) { + Map properties = new HashMap<>(); + if(groupProps != null){ + for (GroupProperty gp : groupProps) { if (gp.getName().equals(Constants.IS_BASE)) { Boolean isBase = Boolean.parseBoolean(gp.getValue()); String type = isBase ? VF_MODULE_TYPE_BASE : VF_MODULE_TYPE_EXPANSION; properties.put(VF_MODULE_TYPE_KEY, type); - break; - } - } - properties.put(VF_MODULE_DESC_KEY, group.getDescription()); - boolean isVolume = false; - List artifactsList = group.getArtifacts(); - if (artifactsList != null && !artifactsList.isEmpty()) { - - for (String artifactId : artifactsList) { - Map deploymentArtifacts = component.getDeploymentArtifacts(); - Optional findFirst = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(artifactId)).findFirst(); - if (findFirst.isPresent()) { - ArtifactDefinition artifactDefinition = findFirst.get(); - if (artifactDefinition.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) { - isVolume = true; - break; + } else { + Object value = null; + String type = gp.getType(); + + switch (type) { + case "integer": + if (gp.getValue() != null) { + value = Integer.valueOf(gp.getValue()); } + break; + case "boolean": + if (gp.getValue() != null) { + value = Boolean.valueOf(gp.getValue()); + } + break; + + default: + value = gp.getValue(); + break; } + properties.put(gp.getName(), value); } } - properties.put(VOLUME_GROUP_KEY, isVolume); - toscaGroup.setProperties(properties); } - toscaMetadata.setName(group.getName()); - toscaMetadata.setInvariantUUID(group.getInvariantUUID()); - toscaMetadata.setUUID(group.getGroupUUID()); - toscaMetadata.setVersion(group.getVersion()); - toscaGroup.setMetadata(toscaMetadata); - return toscaGroup; + return properties; } private ToscaNodeType createNodeType(Component component) { ToscaNodeType toscaNodeType = new ToscaNodeType(); - if (ToscaUtils.isNodeType(component) && ((Resource) component).getDerivedFrom() != null) { - toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0)); + if (ToscaUtils.isAtomicType(component)){ + if (((Resource) component).getDerivedFrom() != null){ + toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0)); + } + toscaNodeType.setDescription(component.getDescription()); // or name?? + } else { + String derivedFrom = null != component.getDerivedFromGenericType()? component.getDerivedFromGenericType() : "tosca.nodes.Root"; + toscaNodeType.setDerived_from(derivedFrom); } - toscaNodeType.setDescription(component.getDescription()); // or name?? return toscaNodeType; } - - private Either convertComponentInstanceRequirements(Component component, ComponentInstance componentInstance, List relations, ToscaNodeTemplate nodeTypeTemplate) { + + private Either convertComponentInstanceRequirements(Component component, + ComponentInstance componentInstance, List relations, + ToscaNodeTemplate nodeTypeTemplate) { List instancesList = component.getComponentInstances(); List> toscaRequirements = new ArrayList<>(); Map> reqMap = componentInstance.getRequirements(); relations.stream().filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).forEach(req -> { - ComponentInstance toComponentInstance = instancesList.stream().filter(i -> req.getToNode().equals(i.getUniqueId())).findFirst().orElse(null); + ComponentInstance toComponentInstance = instancesList.stream() + .filter(i -> req.getToNode().equals(i.getUniqueId())).findFirst().orElse(null); if (toComponentInstance == null) { - log.debug("Faild to create relation between node {} to node {}", componentInstance.getName(), req.getToNode()); + log.debug("Faild to create relation between node {} to node {}", componentInstance.getName(), + req.getToNode()); return; } @@ -535,12 +831,14 @@ public class ToscaExportHandler { ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement(); toscaRequirement.setRelationship(reqAndRelationshopPair.getRelationship().getType()); toscaRequirement.setNode(toComponentInstance.getName()); - Optional findAny = reqMap.values().stream().flatMap(e -> e.stream()).filter(e -> e.getName().equals(reqAndRelationshopPair.getRequirement())).findAny(); + Optional findAny = reqMap.values().stream().flatMap(e -> e.stream()) + .filter(e -> e.getName().equals(reqAndRelationshopPair.getRequirement())).findAny(); if (findAny.isPresent()) { RequirementDefinition regDefinition = findAny.get(); toscaRequirement.setCapability(regDefinition.getCapability()); } else { - log.debug("Faild to find relation between node {} to node {}", componentInstance.getName(), req.getToNode()); + log.debug("Faild to find relation between node {} to node {}", componentInstance.getName(), + req.getToNode()); return; } Map reqmap = new HashMap(); @@ -557,7 +855,8 @@ public class ToscaExportHandler { } private Either convertCapabilities(Component component, SubstitutionMapping substitutionMapping, Map dataTypes) { - Map toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component, dataTypes); + Map toscaCapabilities = capabiltyRequirementConvertor.convertSubstitutionMappingCapabilities(component, dataTypes); + if (!toscaCapabilities.isEmpty()) { substitutionMapping.setCapabilities(toscaCapabilities); } @@ -566,8 +865,10 @@ public class ToscaExportHandler { return Either.left(substitutionMapping); } - private Either convertCapabilities(Component component, ToscaNodeType nodeType, Map dataTypes) { - Map toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component, dataTypes); + private Either convertCapabilities(Component component, ToscaNodeType nodeType, + Map dataTypes) { + Map toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component, + dataTypes); if (!toscaCapabilities.isEmpty()) { nodeType.setCapabilities(toscaCapabilities); } @@ -586,7 +887,8 @@ public class ToscaExportHandler { } @Override - protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) { + protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, + Tag customTag) { if (propertyValue == null) { return null; } else { @@ -596,7 +898,8 @@ public class ToscaExportHandler { } NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); - return property.getName().equals("_defaultp_") ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode; + return property.getName().equals("_defaultp_") + ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode; } } @@ -619,10 +922,10 @@ public class ToscaExportHandler { private static class UnsortedPropertyUtils extends PropertyUtils { @Override - protected Set createPropertySet(Class type, BeanAccess bAccess) throws IntrospectionException { + protected Set createPropertySet(Class type, BeanAccess bAccess) + throws IntrospectionException { Collection fields = getPropertiesMap(type, BeanAccess.FIELD).values(); - Set result = new LinkedHashSet(fields); - return result; + return new LinkedHashSet(fields); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java index db03ad2307..dce3b3bbc0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java @@ -34,11 +34,11 @@ import org.openecomp.sdc.be.model.Component; public class ToscaUtils { - public static boolean isNodeType(Component component) { + public static boolean isAtomicType(Component component) { ComponentTypeEnum componentType = component.getComponentType(); if (ComponentTypeEnum.RESOURCE.equals(componentType)) { ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); - if (ResourceTypeEnum.CP.equals(resourceType) || ResourceTypeEnum.VL.equals(resourceType) || ResourceTypeEnum.VFC.equals(resourceType)) { + if (ResourceTypeEnum.CP == resourceType || ResourceTypeEnum.VL == resourceType || ResourceTypeEnum.VFC == resourceType || ResourceTypeEnum.VFCMT == resourceType || ResourceTypeEnum.ABSTRACT == resourceType) { return true; } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java index 46f4fd032e..70b05b8158 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java @@ -29,5 +29,6 @@ public interface IToscaMetadata { public void setUUID(String uUID); public void setVersion(String version); - + + public void setCustomizationUUID(String customizationUUID); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java index 0fd9daef7d..5dc8ddee2a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java @@ -24,9 +24,8 @@ import java.util.Map; public class SubstitutionMapping { private String node_type; - - private Map capabilities; - private Map requirements; + private Map capabilities; + private Map requirements; public SubstitutionMapping() { super(); @@ -41,20 +40,19 @@ public class SubstitutionMapping { this.node_type = node_type; } - public Map getCapabilities() { + public Map getCapabilities() { return capabilities; } - public void setCapabilities(Map capabilities) { + public void setCapabilities(Map capabilities) { this.capabilities = capabilities; } - public Map getRequirements() { + public Map getRequirements() { return requirements; } - public void setRequirements(Map requirements) { + public void setRequirements(Map requirements) { this.requirements = requirements; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java index 38cd002726..6573313dbb 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java @@ -23,6 +23,7 @@ package org.openecomp.sdc.be.tosca.model; public class ToscaMetadata implements IToscaMetadata { private String invariantUUID; private String UUID; + private String customizationUUID; private String version; private String name; private String description; @@ -32,7 +33,8 @@ public class ToscaMetadata implements IToscaMetadata { private String resourceVendor; private String resourceVendorRelease; private Boolean serviceEcompNaming; - private Boolean serviceHoming; + private Boolean ecompGeneratedNaming; + private String namingPolicy; public String getName() { return name; @@ -109,20 +111,28 @@ public class ToscaMetadata implements IToscaMetadata { this.resourceVendorRelease = resourceVendorRelease; } - public Boolean isServiceEcompNaming() { - return serviceEcompNaming; + public Boolean isEcompGeneratedNaming() { + return ecompGeneratedNaming; } - public void setServiceEcompNaming(Boolean serviceEcompNaming) { - this.serviceEcompNaming = serviceEcompNaming; + public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) { + this.ecompGeneratedNaming = ecompGeneratedNaming; + } + + public String isNamingPolicy() { + return namingPolicy; + } + + public void setNamingPolicy(String namingPolicy) { + this.namingPolicy = namingPolicy; } - public Boolean isServiceHoming() { - return serviceHoming; + public Boolean getServiceEcompNaming() { + return serviceEcompNaming; } - public void setServiceHoming(Boolean serviceHoming) { - this.serviceHoming = serviceHoming; + public void setServiceEcompNaming(Boolean serviceEcompNaming) { + this.serviceEcompNaming = serviceEcompNaming; } public String getVersion() { @@ -134,4 +144,12 @@ public class ToscaMetadata implements IToscaMetadata { this.version = version; } + public String getCustomizationUUID() { + return customizationUUID; + } + + public void setCustomizationUUID(String customizationUUID) { + this.customizationUUID = customizationUUID; + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java index 6804bf6968..df285c6ad9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java @@ -20,6 +20,7 @@ package org.openecomp.sdc.be.tosca.model; +import java.util.HashMap; import java.util.Map; public class ToscaTopolgyTemplate { @@ -40,8 +41,11 @@ public class ToscaTopolgyTemplate { return groups; } - public void setGroups(Map groups) { - this.groups = groups; + public void addGroups(Map groups) { + if ( this.groups == null ){ + this.groups = new HashMap<>(); + } + this.groups.putAll(groups); } public SubstitutionMapping getSubstitution_mappings() { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java index 5f978227ef..26ce118a1a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java @@ -26,6 +26,7 @@ public class VfModuleToscaMetadata implements IToscaMetadata { private String vfModuleModelInvariantUUID; private String vfModuleModelUUID; private String vfModuleModelVersion; + private String vfModuleModelCustomizationUUID; @Override public void setName(String name) { @@ -63,4 +64,12 @@ public class VfModuleToscaMetadata implements IToscaMetadata { return vfModuleModelVersion; } + public String getVfModuleModelCustomizationUUID() { + return vfModuleModelCustomizationUUID; + } + + public void setCustomizationUUID(String customizationUUID) { + this.vfModuleModelCustomizationUUID = customizationUUID; + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java index 5cfa4a12da..54ba9bf571 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java @@ -31,6 +31,11 @@ import org.openecomp.sdc.exception.ResponseFormat; import fj.data.Either; +/** + * + * @author tg851x + * + */ public interface IUserBusinessLogic { public Either getUser(String userId, boolean inTransaction); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java index 8e736d4c0e..796b3a78c0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java @@ -40,8 +40,7 @@ public class UserAdminValidator { private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; - //private static final String USER_ID_PATTERN = "[mM]{1}[0-9]{5}|[a-zA-Z]{2}[0-9]{4}|[a-zA-Z]{2}[0-9]{4}|[a-zA-Z]{2}[0-9]{3}[a-zA-Z]{1}"; - private static final String USER_ID_PATTERN = "^[\\s\\w_.-]{1,50}$"; + private static final String USER_ID_PATTERN = "\\w{1,25}"; private UserAdminValidator() { emailPat = Pattern.compile(EMAIL_PATTERN); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java index 8a910fc566..c90cc6118f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java @@ -90,7 +90,7 @@ public class UserBusinessLogic implements IUserBusinessLogic { Either eitherCreator = getUser(modifierUserId, false); if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - log.debug("createUser method - user is not listed. userId={}", modifier.getUserId()); + log.debug("createUser method - user is not listed. userId = {}", modifier.getUserId()); responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); return Either.right(responseFormat); @@ -98,7 +98,7 @@ public class UserBusinessLogic implements IUserBusinessLogic { modifier = eitherCreator.left().value(); if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) { - log.debug("createUser method - user is not admin={}", modifier.getUserId()); + log.debug("createUser method - user is not admin = {}", modifier.getUserId()); responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); return Either.right(responseFormat); @@ -120,7 +120,7 @@ public class UserBusinessLogic implements IUserBusinessLogic { // isUserAlreadyExist = true; if (userFromDb.getStatus() == UserStatusEnum.ACTIVE) { responseFormat = componentsUtils.getResponseFormatByUserId(ActionStatus.USER_ALREADY_EXIST, newUser.getUserId()); - log.debug("createUser method - user already exist with id: {}", modifier.getUserId(), userFromDb.getUserId()); + log.debug("createUser method - user with id {} already exist with id: {}", modifier.getUserId(), userFromDb.getUserId()); handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); return Either.right(responseFormat); } @@ -130,7 +130,7 @@ public class UserBusinessLogic implements IUserBusinessLogic { // validate Email if (newUser.getEmail() != null && !userAdminValidator.validateEmail(newUser.getEmail())) { - log.debug("createUser method - user has invalid email={}", modifier.getUserId()); + log.debug("createUser method - user has invalid email = {}", modifier.getUserId()); responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_EMAIL_ADDRESS, newUser.getEmail()); handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); return Either.right(responseFormat); @@ -141,7 +141,7 @@ public class UserBusinessLogic implements IUserBusinessLogic { newUser.setRole(Role.DESIGNER.name()); } else { if (!userAdminValidator.validateRole(newUser.getRole())) { - log.debug("createUser method - user has invalid role={}", modifier.getUserId()); + log.debug("createUser method - user has invalid role = {}", modifier.getUserId()); responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, newUser.getRole()); handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); return Either.right(responseFormat); @@ -168,8 +168,9 @@ public class UserBusinessLogic implements IUserBusinessLogic { addOrUpdateUserReq = userAdminOperation.updateUserData(newUser); } else { // user not exist - create new user + if (newUser.getUserId() != null && !userAdminValidator.validateUserId(newUser.getUserId())) { - log.debug("createUser method - user has invalid userId={}", modifier.getUserId()); + log.debug("createUser method - user has invalid userId = {}", modifier.getUserId()); responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_USER_ID, newUser.getUserId()); handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); return Either.right(responseFormat); @@ -204,7 +205,7 @@ public class UserBusinessLogic implements IUserBusinessLogic { Either eitherCreator = getUser(modifierUserId, false); if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - log.debug("updateUserRole method - user is not listed. userId={}", modifier.getUserId()); + log.debug("updateUserRole method - user is not listed. userId = {}", modifier.getUserId()); responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); return Either.right(responseFormat); @@ -212,14 +213,14 @@ public class UserBusinessLogic implements IUserBusinessLogic { modifier = eitherCreator.left().value(); if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) { - log.debug("updateUserRole method - user is not admin. userId={}", modifier.getUserId()); + log.debug("updateUserRole method - user is not admin. userId = {}", modifier.getUserId()); responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); return Either.right(responseFormat); } if (modifier.getUserId().equals(userIdToUpdate)) { - log.debug("updateUserRole method - admin role can only be updated by other admin. userId={}", modifier.getUserId()); + log.debug("updateUserRole method - admin role can only be updated by other admin. userId = {}", modifier.getUserId()); responseFormat = componentsUtils.getResponseFormat(ActionStatus.UPDATE_USER_ADMIN_CONFLICT); handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); return Either.right(responseFormat); @@ -227,14 +228,14 @@ public class UserBusinessLogic implements IUserBusinessLogic { Either userToUpdateReq = getUser(userIdToUpdate, false); if (userToUpdateReq.isRight() || userToUpdateReq.left().value() == null) { - log.debug("updateUserRole method - user not found. userId={}", modifier.getUserId()); + log.debug("updateUserRole method - user not found. userId = {}", modifier.getUserId()); responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userIdToUpdate); handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); return Either.right(responseFormat); } if (!userAdminValidator.validateRole(userRole)) { - log.debug("updateUserRole method - user has invalid role={}", modifier.getUserId()); + log.debug("updateUserRole method - user has invalid role = {}", modifier.getUserId()); responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, userRole); handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); return Either.right(responseFormat); @@ -267,7 +268,7 @@ public class UserBusinessLogic implements IUserBusinessLogic { Either updateUserReq = userAdminOperation.updateUserData(newUser); if (updateUserReq.isRight() || updateUserReq.left().value() == null) { - log.debug("updateUser method - failed to update user data. userId={}", modifier.getUserId()); + log.debug("updateUser method - failed to update user data. userId = {}", modifier.getUserId()); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateUserReq.right().value()))); } @@ -374,7 +375,7 @@ public class UserBusinessLogic implements IUserBusinessLogic { Either eitherCreator = getUser(userId, false); if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - log.debug("deActivateUser method - user is not listed. userId={}", modifier.getUserId()); + log.debug("deActivateUser method - user is not listed. userId = {}", modifier.getUserId()); responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); return Either.right(responseFormat); @@ -383,14 +384,14 @@ public class UserBusinessLogic implements IUserBusinessLogic { modifier = eitherCreator.left().value(); if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) { - log.debug("deActivateUser method - user is not admin. userId={}", modifier.getUserId()); + log.debug("deActivateUser method - user is not admin. userId = {}", modifier.getUserId()); responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); return Either.right(responseFormat); } if (modifier.getUserId().equals(userUniuqeIdToDeactive)) { - log.debug("deActivateUser deActivateUser - admin can only be deactivate by other admin. userId={}", modifier.getUserId()); + log.debug("deActivateUser deActivateUser - admin can only be deactivate by other admin. userId = {}", modifier.getUserId()); responseFormat = componentsUtils.getResponseFormat(ActionStatus.DELETE_USER_ADMIN_CONFLICT); handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); return Either.right(responseFormat); @@ -706,7 +707,7 @@ public class UserBusinessLogic implements IUserBusinessLogic { log.debug("Functional menu fetched is {}", functionalMenu); } catch (UebException e) { - log.debug("Failed to fetch 'functional menu' of user {} from ecomp portal(via UEB). {}", userId, e); + log.debug("Failed to fetch 'functional menu' of user {} from ecomp portal(via UEB)", userId, e); BeEcompErrorManager.getInstance().logInternalFlowError("FetchFunctionalMenu", "Failed to fetch 'functional menu'", ErrorSeverity.ERROR); } return functionalMenu; diff --git a/catalog-be/src/main/resources/application-context.xml b/catalog-be/src/main/resources/application-context.xml index da0a49f6e2..702c63ea81 100644 --- a/catalog-be/src/main/resources/application-context.xml +++ b/catalog-be/src/main/resources/application-context.xml @@ -28,6 +28,8 @@ org.openecomp.sdc.be.dao.cassandra, org.openecomp.sdc.be.switchover.detector, org.openecomp.sdc.be.tosca, + org.openecomp.sdc.be.model.jsontitan.operations, + org.openecomp.sdc.be.dao.jsongraph, org.openecomp.sdc.be.externalapi.servlet "> @@ -56,9 +58,9 @@ - - - + + + diff --git a/catalog-be/src/main/resources/config/Artifact-Generator.properties b/catalog-be/src/main/resources/config/Artifact-Generator.properties new file mode 100644 index 0000000000..1d7e5fa01a --- /dev/null +++ b/catalog-be/src/main/resources/config/Artifact-Generator.properties @@ -0,0 +1,264 @@ +#action widget details +AAI.model-version-id.action=fd7fb09e-d930-41b9-b83f-cfde9df48640 +AAI.model-invariant-id.action=af593b4b-490e-4665-ad74-2f6351c0a7ce +#action-data widget details +AAI.model-invariant-id.action-data=9551346c-7d8b-4daf-9926-b93e96e2344a +AAI.model-version-id.action-data=2f80c596-27e5-4ca9-b5bb-e03a7fd4c0fd +#allotted-resource widget details +AAI.model-invariant-id.allotted-resource=f6d6a23d-a1a9-48ff-8419-b6530da2d381 +AAI.model-version-id.allotted-resource=7ad0915f-25c0-4a70-b9bc-185a75f87564 +#availability-zone widget details +AAI.model-version-id.availability-zone=6c092fb1-21b2-456b-9e01-67fb4de1896e +AAI.model-invariant-id.availability-zone=61b88c01-d819-41c0-8e21-7fd7ba47148e +#az-and-dvs-switches widget details +AAI.model-version-id.az-and-dvs-switches=b2dea88d-78a0-49bf-95c9-5819df08e966 +AAI.model-invariant-id.az-and-dvs-switches=53dc00d4-e6d9-48ec-b6cc-3d3797e9b896 +#class-of-service widget details +AAI.model-version-id.class-of-service=d2fb27cc-15eb-4c4e-828e-71d41aaecc5b +AAI.model-invariant-id.class-of-service=18094b19-d16d-4822-8acf-e92c6aefa178 +#cloud-region widget details +AAI.model-version-id.cloud-region=2a160989-b202-47dd-874b-4a0f275998f7 +AAI.model-invariant-id.cloud-region=425b2158-e51d-4509-9945-dad4556474a3 +#complex widget details +AAI.model-invariant-id.complex=af91c2f7-35fc-43cf-a13d-443f385b2353 +AAI.model-version-id.complex=3a8ab1ee-9220-4fe8-b89c-9251d160ddc2 +#connector widget details +AAI.model-version-id.connector=22104c9f-29fd-462f-be07-96cd6b46dd33 +AAI.model-invariant-id.connector=4c01c948-7607-4d66-8a6c-99c2c2717936 +#constrained-element-set widget details +AAI.model-invariant-id.constrained-element-set=c0292b4f-ee97-40cc-8c2e-f967c48f5701 +AAI.model-version-id.constrained-element-set=01102126-9c04-4a89-945b-b131e61e95d7 +#ctag-assignment widget details +AAI.model-version-id.ctag-assignment=44e5cb1f-0938-41aa-b766-d4595109fe89 +AAI.model-invariant-id.ctag-assignment=fcb8d46b-b656-4ad6-8fa4-22cef74b443f +#ctag-pool widget details +AAI.model-invariant-id.ctag-pool=46c51d4e-d67e-4a9c-b1f5-49b1e9c6fcaa +AAI.model-version-id.ctag-pool=2056c41f-23b9-4de7-9f50-819adad37d76 +#customer widget details +AAI.model-invariant-id.customer=c1d4305f-cdbd-4bbe-9069-a2f4978fd89e +AAI.model-version-id.customer=d4df5c27-98a1-4812-a8aa-c17f055b7a3f +#cvlan-tag-entry widget details +AAI.model-version-id.cvlan-tag-entry=c3878ffb-8d85-4114-bee6-e4074a9db10b +AAI.model-invariant-id.cvlan-tag-entry=245cf4b0-7cc5-4eea-bbd9-753e939adcab +#dvs-switch widget details +AAI.model-invariant-id.dvs-switch=98fbb471-1f86-428e-bd8a-c8a25de6fa23 +AAI.model-version-id.dvs-switch=4cb44ae8-e3ab-452a-9f95-bcc8a44c55ea +#edge-prop-names widget details +AAI.model-invariant-id.edge-prop-names=7a08cad4-8759-46a5-8245-095d1ba57ac6 +AAI.model-version-id.edge-prop-names=f0442326-8201-4d0e-857c-74b4ddcbfc9f +#element-choice-set widget details +AAI.model-invariant-id.element-choice-set=9a011958-7165-47a3-b872-00951d1f09ae +AAI.model-version-id.element-choice-set=af27fbfd-598d-44da-aeae-0f9d3a5fcd6a +#entitlement widget details +AAI.model-version-id.entitlement=7e27ba2e-b7db-4e13-9fae-d142152ef98a +AAI.model-invariant-id.entitlement=ae75b5a0-d5e1-4f3a-b8fb-37626a753da3 +#flavor widget details +AAI.model-invariant-id.flavor=bace8d1c-a261-4041-9e37-823117415d0f +AAI.model-version-id.flavor=36200fb5-f251-4f5d-a520-7c5ad5c2cd4b +#generic-vnf widget details +AAI.model-version-id.generic-vnf=93a6166f-b3d5-4f06-b4ba-aed48d009ad9 +AAI.model-invariant-id.generic-vnf=acc6edd8-a8d4-4b93-afaa-0994068be14c +#group-assignment widget details +AAI.model-invariant-id.group-assignment=7cc05f25-7ba2-42b7-a237-c5662a1689e1 +AAI.model-version-id.group-assignment=fe578080-ce19-4604-8760-fc264fbb2565 +#image widget details +AAI.model-version-id.image=f6a038c2-820c-42ba-8c2b-375e24e8f932 +AAI.model-invariant-id.image=3f4c7204-739b-4bbb-87a7-8a6856439c90 +#include-node-filter widget details +AAI.model-invariant-id.include-node-filter=2a2d8ad2-af0a-4e1f-9982-0c899e7dc827 +AAI.model-version-id.include-node-filter=f05f804d-7057-4ffe-bdc5-39f2f0c9c9fd +#instance-group widget details +AAI.model-version-id.instance-group=8e6ee9dc-9017-444a-83b3-219edb018128 +AAI.model-invariant-id.instance-group=3bf1e610-45f7-4ad6-b833-ca4c5ee6a3fd +#inventory-item widget details +AAI.model-invariant-id.inventory-item=cd57d844-9017-4078-aa19-926935a3d77c +AAI.model-version-id.inventory-item=69957f4a-2155-4b95-8d72-d6dd9b88b27b +#inventory-item-data widget details +AAI.model-version-id.inventory-item-data=0e54bb87-bd6e-4a2b-ad1c-6d935b87ae51 +AAI.model-invariant-id.inventory-item-data=87a383ae-cf03-432e-a9de-04e6a622d0fd +#ipsec-configuration widget details +AAI.model-invariant-id.ipsec-configuration=aca4c310-cb45-42bd-9f88-73e40ba7b962 +AAI.model-version-id.ipsec-configuration=d949fd10-36bf-408a-ac7a-cad5004d2e0d +#key-data widget details +AAI.model-version-id.key-data=c23ea04d-1a3b-453d-bc49-a6c783a5e92b +AAI.model-invariant-id.key-data=f5faa464-c2f2-4cc3-89d2-a90452dc3a07 +#l3-interface-ipv4-address-list widget details +AAI.model-version-id.l3-interface-ipv4-address-list=41e76b6f-1e06-4fd4-82cd-81c50fc4574b +AAI.model-invariant-id.l3-interface-ipv4-address-list=aad85df2-09be-40fa-b867-16415e4e10e2 +#l3-interface-ipv6-address-list widget details +AAI.model-invariant-id.l3-interface-ipv6-address-list=82966045-43ee-4982-8307-7e9610866140 +AAI.model-version-id.l3-interface-ipv6-address-list=d040621d-541a-477b-bb1b-a2b61b14e295 +#l3-network widget details +AAI.model-version-id.l3-network=9111f20f-e680-4001-b83f-19a2fc23bfc1 +AAI.model-invariant-id.l3-network=3d560d81-57d0-438b-a2a1-5334dba0651a +#lag-interface widget details +AAI.model-version-id.lag-interface=ce95f7c3-b61b-4758-ae9e-7e943b1c103d +AAI.model-invariant-id.lag-interface=e0ee9bde-c1fc-4651-a95d-8e0597bf7d70 +#lag-link widget details +AAI.model-version-id.lag-link=d29a087a-af59-4053-a3f8-0f95a92faa75 +AAI.model-invariant-id.lag-link=86ffe6e5-4d0e-4cec-80b5-5c38aa3eff98 +#license widget details +AAI.model-invariant-id.license=b9a9b337-1f86-42d3-b9f9-f987a089507c +AAI.model-version-id.license=6889274b-a1dc-40ab-9090-93677e13e2e6 +#license-key-resource widget details +AAI.model-invariant-id.license-key-resource=9022ebfe-b54f-4911-a6b2-8c3f5ec189b7 +AAI.model-version-id.license-key-resource=24b25f8c-b8bd-4c62-9421-87c12667aac9 +#l-interface widget details +AAI.model-version-id.l-interface=a32613fd-18b9-459e-aab8-fffb3912966a +AAI.model-invariant-id.l-interface=cea0a982-8d55-4093-921e-418fbccf7060 +#logical-link widget details +AAI.model-version-id.logical-link=a1481a38-f8ba-4ae4-bdf1-06c2c6af4c54 +AAI.model-invariant-id.logical-link=fe012535-2c31-4a39-a739-612374c638a0 +#metadatum widget details +AAI.model-invariant-id.metadatum=86dbb63a-265e-4614-993f-6771c30b56a5 +AAI.model-version-id.metadatum=6bae950e-8939-41d3-a6a7-251b03e4c1fc +#model widget details +AAI.model-invariant-id.model=06d1418a-5faa-452d-a94b-a2829df5f67b +AAI.model-version-id.model=1f51c05c-b164-4c27-9c03-5cbb239fd6be +#model-constraint widget details +AAI.model-invariant-id.model-constraint=c28966f3-e758-4483-b37b-a90b05d3dd33 +AAI.model-version-id.model-constraint=ad70dd19-f156-4fb5-a865-97b5563b0d37 +#model-element widget details +AAI.model-invariant-id.model-element=2076e726-3577-477a-a300-7fa65cd4df11 +AAI.model-version-id.model-element=753e813a-ba9e-4a1d-ab34-b2f6dc6eec0c +#multicast-configuration widget details +AAI.model-invariant-id.multicast-configuration=ea78c9e3-514d-4a0a-9162-13837fa54c35 +AAI.model-version-id.multicast-configuration=666a06ee-4b57-46df-bacf-908da8f10c3f +#named-query widget details +AAI.model-version-id.named-query=5c3b7c33-afa3-4be5-8da7-1a5ac6f99896 +AAI.model-invariant-id.named-query=80b712fd-0ad3-4180-a99c-8c995cf1cc32 +#named-query-element widget details +AAI.model-version-id.named-query-element=204c641a-3494-48c8-979a-86856f5fd32a +AAI.model-invariant-id.named-query-element=3c504d40-b847-424c-9d25-4fb7e0a3e994 +#network-policy widget details +AAI.model-invariant-id.network-policy=6aa05779-94d7-4d8b-9bee-59ef2ab0c246 +AAI.model-version-id.network-policy=a0ccd9dc-7062-4940-9bcc-e91dd28af510 +#network-profile widget details +AAI.model-version-id.network-profile=01f45471-4240-498c-a9e1-235dc0b8b4a6 +AAI.model-invariant-id.network-profile=2734b44a-b8a2-40f6-957d-6256589e5d00 +#newvce widget details +AAI.model-version-id.newvce=7c79e11f-a408-4593-aa86-ba948a1236af +AAI.model-invariant-id.newvce=4b05ec9c-c55d-4987-83ff-e08d6ddb694f +#oam-network widget details +AAI.model-invariant-id.oam-network=2851cf01-9c40-4064-87d4-6184a6fcff35 +AAI.model-version-id.oam-network=f4fb34f3-fd6e-4a8f-a3fb-4ab61a343b79 +#physical-link widget details +AAI.model-invariant-id.physical-link=c822d81f-822f-4304-9623-1025b53da568 +AAI.model-version-id.physical-link=9c523936-95b4-4d7f-9f53-6bdfe0cf2c05 +#p-interface widget details +AAI.model-invariant-id.p-interface=94043c37-4e73-439c-a790-0fdd697924cd +AAI.model-version-id.p-interface=d2cdb2d0-fc1f-4a57-a89e-591b1c4e3754 +#pnf widget details +AAI.model-version-id.pnf=e9f1fa7d-c839-418a-9601-03dc0d2ad687 +AAI.model-invariant-id.pnf=862b25a1-262a-4961-bdaa-cdc55d69785a +#port-group widget details +AAI.model-version-id.port-group=03e8bb6b-b48a-46ae-b5d4-e5af577e6844 +AAI.model-invariant-id.port-group=8ce940fb-55d7-4230-9e7f-a56cc2741f77 +#property-constraint widget details +AAI.model-version-id.property-constraint=81706bbd-981e-4362-ae20-995cbcb2d995 +AAI.model-invariant-id.property-constraint=f4a863c3-6886-470a-a6ae-05723837ea45 +#pserver widget details +AAI.model-invariant-id.pserver=6d932c8f-463b-4e76-83fb-87acfbaa2e2d +AAI.model-version-id.pserver=72f0d495-bc27-4653-9e1a-eef76bd34bc9 +#related-lookup widget details +AAI.model-invariant-id.related-lookup=468f6f5b-2996-41bb-b2a3-7cf9613ebb9b +AAI.model-version-id.related-lookup=0988bab5-bf4f-4938-a419-ab249867d12a +#reserved-prop-names widget details +AAI.model-invariant-id.reserved-prop-names=0c3e0ba3-618c-498d-9127-c8d42b00170f +AAI.model-version-id.reserved-prop-names=ac49d26d-9163-430e-934a-13b738a04f5c +#result-data widget details +AAI.model-version-id.result-data=4e9b50aa-5227-4f6f-b489-62e6bbc03c79 +AAI.model-invariant-id.result-data=ff656f23-6185-406f-9006-4b26834f3e1c +#route-table-reference widget details +AAI.model-version-id.route-table-reference=fed7e326-03a7-45ff-a3f2-471470d268c4 +AAI.model-invariant-id.route-table-reference=a8614b63-2636-4c4f-98df-fd448c4241db +#routing-instance widget details +AAI.model-invariant-id.routing-instance=1c2ded4f-8b01-4193-829c-966847dfec3e +AAI.model-version-id.routing-instance=3ccbcbc7-d19e-44d5-a52f-7e18aa8d69fa +#secondary-filter widget details +AAI.model-version-id.secondary-filter=1380619d-dd1a-4cec-b755-c6407833e065 +AAI.model-invariant-id.secondary-filter=738ff299-6290-4c00-8998-bd0e96a07b93 +#segmentation-assignment widget details +AAI.model-invariant-id.segmentation-assignment=6e814aee-46e1-4583-a9d4-0049bfd2b59b +AAI.model-version-id.segmentation-assignment=c5171ae0-44fb-4c04-b482-d56702241a44 +#service widget details +AAI.model-version-id.service=ecce2c42-3957-4ae0-9442-54bc6afe27b6 +AAI.model-invariant-id.service=07a3a60b-1b6c-4367-8173-8014386f89e3 +#service-capability widget details +AAI.model-invariant-id.service-capability=b1a7cc05-d19d-443b-a5d1-733e325c4232 +AAI.model-version-id.service-capability=f9cfec1b-18da-4bba-bd83-4b26cca115cd +#service-instance widget details +AAI.model-invariant-id.service-instance=82194af1-3c2c-485a-8f44-420e22a9eaa4 +AAI.model-version-id.service-instance=46b92144-923a-4d20-b85a-3cbd847668a9 +#service-subscription widget details +AAI.model-invariant-id.service-subscription=2e1a602a-acd8-4f78-94ff-618b802a303b +AAI.model-version-id.service-subscription=5e68299a-79f2-4bfb-8fbc-2bae877a2459 +#site-pair widget details +AAI.model-version-id.site-pair=7106bc02-6552-4fc3-8a56-4f3df9034531 +AAI.model-invariant-id.site-pair=db63f3e6-f8d1-484e-8d5e-191600b7914b +#site-pair-set widget details +AAI.model-invariant-id.site-pair-set=5d4dae3e-b402-4bfd-909e-ece12ff75d26 +AAI.model-version-id.site-pair-set=a5c6c1bc-dc38-468e-9459-bb08f87247df +#snapshot widget details +AAI.model-version-id.snapshot=962a7c8b-687f-4d32-a775-fe098e214bcd +AAI.model-invariant-id.snapshot=24de00ef-aead-4b52-995b-0adf8d4bd90d +#sriov-vf widget details +AAI.model-version-id.sriov-vf=1e8b331f-3d4a-4160-b7aa-f4d5a8916625 +AAI.model-invariant-id.sriov-vf=04b2935f-33c4-40a9-8af0-8b52690042dc +#start-node-filter widget details +AAI.model-version-id.start-node-filter=aad96fd3-e75f-42fc-9777-3450c36f1168 +AAI.model-invariant-id.start-node-filter=083093a3-e407-447a-ba5d-7583e4d23e1d +#subnet widget details +AAI.model-version-id.subnet=f902a6bc-6be4-4fe5-8458-a6ec0056b374 +AAI.model-invariant-id.subnet=1b2c9ba7-e449-4831-ba15-3073672f5ef2 +#tagged-inventory-item-list widget details +AAI.model-invariant-id.tagged-inventory-item-list=e78a7eaa-f65d-4919-9c2b-5b258c8c4d7e +AAI.model-version-id.tagged-inventory-item-list=c246f6e2-e3a1-4697-94c0-5672a7fbbf04 +#tenant widget details +AAI.model-invariant-id.tenant=97c26c99-6870-44c1-8a07-1d900d3f4ce6 +AAI.model-version-id.tenant=abcc54bc-bb74-49dc-9043-7f7171707545 +#tunnel-xconnect widget details +AAI.model-invariant-id.tunnel-xconnect=50b9e2fa-005c-4bbe-b651-3251dece4cd8 +AAI.model-version-id.tunnel-xconnect=e7cb4ca8-e1a5-4487-a716-4ae0bcd8aef5 +#update-node-key widget details +AAI.model-version-id.update-node-key=6004cfa6-eb6d-4062-971f-b1fde6b74aa0 +AAI.model-invariant-id.update-node-key=fe81c801-f65d-408a-b2b7-a729a18f8154 +#vce widget details +AAI.model-version-id.vce=b6cf54b5-ec45-43e1-be64-97b4e1513333 +AAI.model-invariant-id.vce=bab6dceb-e7e6-4301-a5e0-a7399b48d792 +#vf-module widget details +AAI.model-invariant-id.vf-module=ef86f9c5-2165-44f3-8fc3-96018b609ea5 +AAI.model-version-id.vf-module=c00563ae-812b-4e62-8330-7c4d0f47088a +#vig-server widget details +AAI.model-version-id.vig-server=8e8c22f1-fbdf-48ea-844c-8bdeb44e7b16 +AAI.model-invariant-id.vig-server=bed7c3b7-35d0-4cd9-abde-41b20e68b28e +#virtual-data-center widget details +AAI.model-invariant-id.virtual-data-center=5150abcf-0c5f-4593-9afe-a19c48fc4824 +AAI.model-version-id.virtual-data-center=6dd43ced-d789-47af-a759-d3abc14e3ac1 +#vlan widget details +AAI.model-version-id.vlan=257d88a5-a269-4c35-944f-aca04fbdb791 +AAI.model-invariant-id.vlan=d2b1eaf1-ae59-4116-9ee4-aa0179faa4f8 +#vnfc widget details +AAI.model-invariant-id.vnfc=96129eb9-f0de-4e05-8af2-73146473f766 +AAI.model-version-id.vnfc=5761e0a7-c6df-4d8a-9ebd-b8f445054dec +#vnf-image widget details +AAI.model-invariant-id.vnf-image=f9a628ff-7aa0-40e2-a93d-02d91c950982 +AAI.model-version-id.vnf-image=c4d3e747-ba4a-4b17-9896-94c6f18c19d3 +#volume widget details +AAI.model-version-id.volume=0fbe2e8f-4d91-4415-a772-88387049b38d +AAI.model-invariant-id.volume=ddd739b4-2b25-46c4-affc-41a32af5cc42 +#volume-group widget details +AAI.model-invariant-id.volume-group=fcec1b02-b2d0-4834-aef8-d71be04717dd +AAI.model-version-id.volume-group=99d44c90-1f61-4418-b9a6-56586bf38c79 +#vpe widget details +AAI.model-invariant-id.vpe=053ec3a7-5b72-492d-b54d-123805a9b967 +AAI.model-version-id.vpe=203817d3-829c-42d4-942d-2a935478e993 +#vpls-pe widget details +AAI.model-version-id.vpls-pe=b1566228-6785-4ce1-aea2-053736f80341 +AAI.model-invariant-id.vpls-pe=457ba89b-334c-4fbd-acc4-160ac0e0cdc0 +#vpn-binding widget details +AAI.model-invariant-id.vpn-binding=9e23b675-db2b-488b-b459-57aa9857baa0 +AAI.model-version-id.vpn-binding=21a146e5-9901-448c-9197-723076770119 +#vserver widget details +AAI.model-invariant-id.vserver=ff69d4e0-a8e8-4108-bdb0-dd63217e63c7 +AAI.model-version-id.vserver=8ecb2c5d-7176-4317-a255-26274edfdd53 \ No newline at end of file diff --git a/catalog-be/src/main/resources/config/SDC.zip b/catalog-be/src/main/resources/config/SDC.zip new file mode 100644 index 0000000000..dfb4be85fb Binary files /dev/null and b/catalog-be/src/main/resources/config/SDC.zip differ diff --git a/catalog-be/src/main/resources/config/configuration.yaml b/catalog-be/src/main/resources/config/configuration.yaml index b8e80dc17c..3801c8290c 100644 --- a/catalog-be/src/main/resources/config/configuration.yaml +++ b/catalog-be/src/main/resources/config/configuration.yaml @@ -5,10 +5,8 @@ identificationHeaderFields: - HTTP_IV_REMOTE_ADDRESS - HTTP_CSP_WSTYPE - - # catalog backend hostname -beFqdn: localhost +beFqdn: sdccatalog.att.com # catalog backend http port beHttpPort: 8080 @@ -24,32 +22,70 @@ beSslPort: 8443 version: 1.0 released: 2012-11-30 +toscaConformanceLevel: 3.0 +minToscaConformanceLevel: 3.0 titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties titanInMemoryGraph: false titanLockTimeout: 1800 + +# The interval to try and reconnect to titan DB when it is down during ASDC startup: titanReconnectIntervalInSeconds: 3 + +# The read timeout towards Titan DB when health check is invoked: titanHealthCheckReadTimeout: 1 + +# The interval to try and reconnect to Elasticsearch when it is down during ASDC startup: esReconnectIntervalInSeconds: 3 uebHealthCheckReconnectIntervalInSeconds: 15 uebHealthCheckReadTimeout: 4 + # Protocols protocols: - http - https +# Default imports +defaultImports: + - nodes: + file: nodes.yml + - datatypes: + file: data.yml + - capabilities: + file: capabilities.yml + - relationships: + file: relationships.yml + - groups: + file: groups.yml + - policies: + file: policies.yml + # Users users: tom: passwd bob: passwd - + neo4j: host: neo4jhost port: 7474 user: neo4j password: "12345" - + +cassandraConfig: + cassandraHosts: ['localhost'] + localDataCenter: + reconnectTimeout : 30000 + authenticate: false + username: koko + password: bobo + ssl: false + truststorePath : /path/path + truststorePassword : 123123 + keySpaces: + - { name: sdcaudit, replicationStrategy: SimpleStrategy, replicationInfo: ['1']} + - { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']} + - { name: sdccomponent, replicationStrategy: SimpleStrategy, replicationInfo: ['1']} #Application-specific settings of ES elasticSearch: @@ -67,7 +103,7 @@ elasticSearch: # Legal values for creationPeriod - year, month, day, hour, minute, none (meaning no time-based behaviour). # # If no creationPeriod is configured for indexPrefix, default behavour is creationPeriod: month. - + indicesTimeFrequency: - indexPrefix: auditingevents creationPeriod: month @@ -93,6 +129,9 @@ artifactTypes: - AAI_VF_MODULE_MODEL - AAI_VF_INSTANCE_MODEL - OTHER + - SNMP_POLL + - SNMP_TRAP + - GUIDE licenseTypes: - User @@ -105,7 +144,9 @@ resourceTypes: &allResourceTypes - CP - VL - VF - + - VFCMT + - Abstract + # validForResourceTypes usage # validForResourceTypes: # - VF @@ -123,13 +164,18 @@ deploymentResourceArtifacts: # displayName: "Network HEAT Template" # type: HEAT_NET # validForResourceTypes: *allResourceTypes - + deploymentResourceInstanceArtifacts: heatEnv: displayName: "HEAT ENV" type: HEAT_ENV description: "Auto-generated HEAT Environment deployment artifact" fileExtension: "env" + VfHeatEnv: + displayName: "VF HEAT ENV" + type: HEAT_ENV + description: "VF Auto-generated HEAT Environment deployment artifact" + fileExtension: "env" #tosca artifacts placeholders toscaArtifacts: @@ -161,7 +207,7 @@ informationalResourceArtifacts: testScripts: displayName: Test Scripts type: OTHER - cloudQuestionnaire: + CloudQuestionnaire: displayName: Cloud Questionnaire (completed) type: OTHER HEATTemplateFromVendor: @@ -170,7 +216,7 @@ informationalResourceArtifacts: resourceSecurityTemplate: displayName: Resource Security Template type: OTHER - + excludeServiceCategory: informationalServiceArtifacts: @@ -213,7 +259,7 @@ informationalServiceArtifacts: serviceSecurityTemplate: displayName: Service Security Template type: OTHER - + serviceApiArtifacts: configuration: displayName: Configuration @@ -234,7 +280,6 @@ serviceApiArtifacts: displayName: Testing type: OTHER - additionalInformationMaxNumberOfKeys: 50 systemMonitoring: @@ -281,19 +326,19 @@ resourceDeploymentArtifacts: - yaml - yml validForResourceTypes: *allResourceTypes - HEAT_NESTED: + HEAT_NET: acceptedTypes: - yaml - yml validForResourceTypes: *allResourceTypes - HEAT_ARTIFACT: - acceptedTypes: - validForResourceTypes: *allResourceTypes - HEAT_NET: + HEAT_NESTED: acceptedTypes: - yaml - yml validForResourceTypes: *allResourceTypes + HEAT_ARTIFACT: + acceptedTypes: + validForResourceTypes: *allResourceTypes YANG_XML: acceptedTypes: - xml @@ -318,37 +363,55 @@ resourceDeploymentArtifacts: acceptedTypes: - xml validForResourceTypes: *allResourceTypes - #APPC Artifatcs + LIFECYCLE_OPERATIONS: + acceptedTypes: + - yaml + - yml + validForResourceTypes: + - VF + - VFC + VES_EVENTS: + acceptedTypes: + - yaml + - yml + validForResourceTypes: *allResourceTypes + PERFORMANCE_COUNTER: + acceptedTypes: + - csv + validForResourceTypes: *allResourceTypes APPC_CONFIG: acceptedTypes: validForResourceTypes: - VF - #DCAE Artifacts DCAE_TOSCA: acceptedTypes: - yml - yaml validForResourceTypes: - VF + - VFCMT DCAE_JSON: acceptedTypes: - json validForResourceTypes: - VF + - VFCMT DCAE_POLICY: acceptedTypes: - emf validForResourceTypes: - VF + - VFCMT DCAE_DOC: acceptedTypes: validForResourceTypes: - - VF + - VF + - VFCMT DCAE_EVENT: acceptedTypes: validForResourceTypes: - VF -#AAI Artifacts + - VFCMT AAI_VF_MODEL: acceptedTypes: - xml @@ -362,6 +425,12 @@ resourceDeploymentArtifacts: OTHER: acceptedTypes: validForResourceTypes: *allResourceTypes + SNMP_POLL: + acceptedTypes: + validForResourceTypes: *allResourceTypes + SNMP_TRAP: + acceptedTypes: + validForResourceTypes: *allResourceTypes resourceInstanceDeploymentArtifacts: HEAT_ENV: @@ -370,7 +439,13 @@ resourceInstanceDeploymentArtifacts: VF_MODULES_METADATA: acceptedTypes: - json -#DCAE_VF Instance Artifacts + VES_EVENTS: + acceptedTypes: + - yaml + - yml + PERFORMANCE_COUNTER: + acceptedTypes: + - csv DCAE_INVENTORY_TOSCA: acceptedTypes: - yml @@ -387,15 +462,62 @@ resourceInstanceDeploymentArtifacts: acceptedTypes: DCAE_INVENTORY_EVENT: acceptedTypes: - - -resourceInformationalDeployedArtifacts: + SNMP_POLL: + acceptedTypes: + validForResourceTypes: *allResourceTypes + SNMP_TRAP: + acceptedTypes: + validForResourceTypes: *allResourceTypes + +resourceInformationalArtifacts: + CHEF: + acceptedTypes: + validForResourceTypes: *allResourceTypes + PUPPET: + acceptedTypes: + validForResourceTypes: *allResourceTypes + SHELL: + acceptedTypes: + validForResourceTypes: *allResourceTypes + YANG: + acceptedTypes: + validForResourceTypes: *allResourceTypes + YANG_XML: + acceptedTypes: + validForResourceTypes: *allResourceTypes + HEAT: + acceptedTypes: + validForResourceTypes: *allResourceTypes + BPEL: + acceptedTypes: + validForResourceTypes: *allResourceTypes + DG_XML: + acceptedTypes: + validForResourceTypes: *allResourceTypes + MURANO_PKG: + acceptedTypes: + validForResourceTypes: *allResourceTypes + OTHER: + acceptedTypes: + validForResourceTypes: *allResourceTypes + SNMP_POLL: + acceptedTypes: + validForResourceTypes: *allResourceTypes + SNMP_TRAP: + acceptedTypes: + validForResourceTypes: *allResourceTypes + GUIDE: + acceptedTypes: + validForResourceTypes: + - VF + - VFC +resourceInformationalDeployedArtifacts: requirementsToFulfillBeforeCert: capabilitiesToConsumeBeforeCert: - + unLoggedUrls: - /sdc2/rest/healthCheck @@ -407,54 +529,34 @@ cleanComponentsConfiguration: artifactsIndex: resources -cassandraConfig: - cassandraHosts: ['localhost'] - localDataCenter: - reconnectTimeout : 30000 - authenticate: false - username: koko - password: bobo - ssl: false - truststorePath : /path/path - truststorePassword : 123123 - keySpaces: - - { name: sdcaudit, replicationStrategy: SimpleStrategy, replicationInfo: ['1']} - - { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']} - - { name: sdccomponent, replicationStrategy: SimpleStrategy, replicationInfo: ['1']} - - +heatEnvArtifactHeader: "" +heatEnvArtifactFooter: "" + +onboarding: + protocol: http + host: localhost + port: 8080 + downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages" + switchoverDetector: - gBeFqdn: - gFeFqdn: - beVip: 1.2.3.4 - feVip: 1.2.3.4 + gBeFqdn: AIO-BE.ecomp.idns.cip.com + gFeFqdn: AIO-FE.ecomp.idns.cip.com + beVip: 0.0.0.0 + feVip: 0.0.0.0 beResolveAttempts: 3 feResolveAttempts: 3 enabled: false interval: 60 changePriorityUser: ecompasdc changePriorityPassword: ecompasdc123 - publishNetworkUrl: "http://localhost/crt/CipDomain.ECOMP-ASDC-DEVST/config/update_network?user=root" + publishNetworkUrl: "http://xxx.com/crt/CipDomain.ECOMP-ASDC-DEVST/config/update_network?user=root" publishNetworkBody: '{"note":"publish network"}' groups: - beSet: { changePriorityUrl: "http://localhost/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.cip?user=root", - changePriorityBody: '{"name":"AIO-BE.ecomp.idns.cip","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.cip","no_ad_redirection":false,"v4groups":{"failover_groups":["/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_mg_be","/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_bs_be"],"failover_policy":["FAILALL"]},"comment":"AIO BE G-fqdn","intended_app_proto":"DNS"}'} - feSet: { changePriorityUrl: "http://cora.web/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.cip?user=root", - changePriorityBody: '{"comment":"AIO G-fqdn","name":"AIO-FE.ecomp.idns.cip","v4groups":{"failover_groups":["/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_mg_fe","/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_bs_fe"],"failover_policy":["FAILALL"]},"no_ad_redirection":false,"intended_app_proto":"DNS","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.cip"}'} - - -heatEnvArtifactHeader: - "" -heatEnvArtifactFooter: - "" + beSet: { changePriorityUrl: "http://xxx.com/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.com?user=root", + changePriorityBody: '{"name":"AIO-BE.ecomp.idns.com","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.com","no_ad_redirection":false,"v4groups":{"failover_groups":["/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_mg_be","/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_bs_be"],"failover_policy":["FAILALL"]},"comment":"AIO BE G-fqdn","intended_app_proto":"DNS"}'} + feSet: { changePriorityUrl: "http://xxx.com/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.com?user=root", + changePriorityBody: '{"comment":"AIO G-fqdn","name":"AIO-FE.ecomp.idns.com","v4groups":{"failover_groups":["/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_mg_fe","/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_bs_fe"],"failover_policy":["FAILALL"]},"no_ad_redirection":false,"intended_app_proto":"DNS","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.com"}'} -onboarding: - protocol: http - host: localhost - port: 8080 - downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages" - #downloadCsarUri: "/onboardingci/onbrest/onboarding-api/v1.0/vendor-software-products/packages" - applicationL1Cache: datatypes: enabled: true @@ -474,5 +576,25 @@ applicationL2Cache: numberOfCacheWorkers: 4 toscaValidators: - stringMaxLength: 65536 -disableAudit: false \ No newline at end of file + stringMaxLength: 2500 + +disableAudit: false + +vfModuleProperties: + min_vf_module_instances: + forBaseModule: 1 + forNonBaseModule: 0 + max_vf_module_instances: + forBaseModule: 1 + forNonBaseModule: + initial_count: + forBaseModule: 1 + forNonBaseModule: 0 + vf_module_type: + forBaseModule: Base + forNonBaseModule: Expansion + +genericAssetNodeTypes: + VFC: org.openecomp.resource.abstract.nodes.VFC + VF : org.openecomp.resource.abstract.nodes.VF + Service: org.openecomp.resource.abstract.nodes.service diff --git a/catalog-be/src/main/resources/config/distribution-engine-configuration.yaml b/catalog-be/src/main/resources/config/distribution-engine-configuration.yaml index 8c56a26785..5d93601ea0 100644 --- a/catalog-be/src/main/resources/config/distribution-engine-configuration.yaml +++ b/catalog-be/src/main/resources/config/distribution-engine-configuration.yaml @@ -1,7 +1,7 @@ uebServers: - - uebsb91sfdc.it.att.com:3904 - - uebsb92sfdc.it.att.com:3904 - - uebsb93sfdc.it.att.com:3904 + - uebsb91sfdc.it.att.com + - uebsb92sfdc.it.att.com + - uebsb93sfdc.it.att.com # prev Kansas City Sandbox uebPublicKey: 8F3MDAtMSBwwpSMy uebPublicKey: sSJc5qiBnKy2qrlc diff --git a/catalog-be/src/main/resources/config/error-configuration.yaml b/catalog-be/src/main/resources/config/error-configuration.yaml index 0054ce2be9..ef7a885678 100644 --- a/catalog-be/src/main/resources/config/error-configuration.yaml +++ b/catalog-be/src/main/resources/config/error-configuration.yaml @@ -42,12 +42,13 @@ errors: message: "Error: Not authorized to use the API.", messageId: "POL5003" } +#---------POL5004------------------------------ + MISSING_USER_ID: { + code: 400 , + message: "Error: Missing 'USER_ID' HTTP header.", + messageId: "POL5004" + } #---------SVC4000----------------------------- - INVALID_CONTENT: { - code: 400, - message: "Error: Invalid content.", - messageId: "SVC4000" - }#---------SVC4000----------------------------- INVALID_CONTENT: { code: 400, message: "Error: Invalid content.", @@ -60,7 +61,7 @@ errors: messageId: "SVC4002" } #---------SVC4003------------------------------ -# %1 - Users's USER_ID +# %1 - Users's ID USER_NOT_FOUND: { code: 404, message: "Error: User '%1' was not found.", @@ -104,7 +105,7 @@ errors: # %1 - service/resource COMPONENT_MISSING_CONTACT: { code: 400, - message: "Error: Invalid Content. Missing %1 contact id.", + message: "Error: Invalid Content. Missing %1 contact.", messageId: "SVC4049" } #---------SVC4050----------------------------- @@ -207,14 +208,14 @@ errors: } #---------SVC4064------------------------------ -# %1 - Service/Resource +# %1 - Service/Resource/Property COMPONENT_INVALID_DESCRIPTION: { code: 400, message: "Error: Invalid Content. %1 description contains non-english characters.", messageId: "SVC4064" } #---------SVC4065------------------------------ -# %1 - Service/Resource +# %1 - Service/Resource/Property # %2 - max resource/service name length COMPONENT_DESCRIPTION_EXCEEDS_LIMIT: { code: 400, @@ -245,9 +246,9 @@ errors: #---------SVC4069------------------------------ # %1 - Service/Resource/Product - COMPONENT_INVALID_CONTACT_ID: { + COMPONENT_INVALID_CONTACT: { code: 400, - message: "Error: Invalid Content. %1 contact id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9", + message: "Error: Invalid Content. %1 Contact Id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9", messageId: "SVC4069" } #---------SVC4070------------------------------ @@ -283,7 +284,7 @@ errors: # %2 - resource/service # %3 - First name of last modifier # %4 - Last name of last modifier -# %5 - USER_ID of last modifier +# %5 - USER_ID of last modifier COMPONENT_IN_CHECKOUT_STATE: { code: 403, message: "Error: Requested '%1' %2 is locked for modification by %3 %4(%5).", @@ -511,7 +512,7 @@ errors: #-----------SVC4130--------------------------- INVALID_PROJECT_CODE: { code: 400, - message: "Error: Invalid Content. PROJECT_CODE number must be numeric from 5 up to 10 digits.", + message: "Error: Invalid Content. PROJECT_CODE must be from 3 up to 50 characters.", messageId: "SVC4130" } #-----------SVC4131--------------------------- @@ -1060,7 +1061,7 @@ errors: messageId: "SVC4567" } #---------SVC4567------------------------------ -# %1 - "User Name and userId" +# %1 - "User Name and UserId" # %2 -"checked-out"/"in-certification" CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS: { code: 409, @@ -1068,7 +1069,7 @@ errors: messageId: "SVC4567" } #---------SVC4568------------------------------ -# %1 - "User Name and userId" +# %1 - "User Name and UserId" # %2 -"checked-out"/"in-certification" CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS: { code: 409, @@ -1144,7 +1145,7 @@ errors: messageId: "SVC4580" } #---------SVC4581------------------------------ -# %1 - userId +# %1 - UserId INVALID_PRODUCT_CONTACT: { code: 400, message: "Error: Invalid content. User '%1' cannot be set as Product Contact.", @@ -1692,3 +1693,86 @@ errors: message: "Error: %1 %2 automatic generation of artifacts failed. Description: %3", messageId: "SVC4650" } +#---------SVC4651------------------------------ + PARENT_RESOURCE_DOES_NOT_EXTEND: { + code: 400, + message: "Error: Once resource is certified, derived_from can be changed only to a sibling", + messageId: "SVC4651" + } +#---------SVC4652------------------------------ +# %1 - resource/service + COMPONENT_INVALID_SUBCATEGORY: { + code: 400, + message: "Error: Invalid Content. Invalid %1 sub category.", + messageId: "SVC4652" + } +#---------SVC4653------------------------------ +# %1 - group instance uniqueId +# %2 - service uniqueId + GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE: { + code: 404, + message: "Error: Requested group instance %1 was not found on component %2.", + messageId: "SVC4653" + } +#---------SVC4654------------------------------ +# %1 - group property name +# %2 - valid min limit value +# %3 - valid max limit value + INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE: { + code: 400, + message: "Error: Value of %1 must be not higher than %2, and not lower than %3.", + messageId: "SVC4654" + } +#---------SVC4655------------------------------ +# %1 - group property name +# %2 - valid min limit value +# %3 - valid max limit value + INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE: { + code: 400, + message: "Error: Value of %1 must be between %2 and %3.", + messageId: "SVC4655" + } +#---------SVC4656------------------------------ +# %1 - group property name +# %2 - lower/higher +# %3 - valid max/min value + INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER: { + code: 400, + message: "Error: Value of %1 must be %2 or equals to %3.", + messageId: "SVC4656" + } +#---------SVC4657------------------------------ +# %1 - certificationRequest / startTesting + RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID: { + code: 400, + message: "Error - Lifecycle state %1 is not valid for resource of type VFCMT", + messageId: "SVC4657" + } +#---------SVC4658------------------------------ +# %1 – asset type [service / resource ] +# %2 – main asset uuid +# %3 – not found asset type [service / resource] +# %4 – not found asset name + ASSET_NOT_FOUND_DURING_CSAR_CREATION: { + code: 400, + message: "Error: CSAR packaging failed for %1 %2. %3 %4 was not found", + messageId: "SVC4658" + } +#---------SVC4659------------------------------ +# %1 – asset type [service / resource ] +# %2 – main asset uuid +# %3 – Artifact name +# %4 – Artifact uuid + ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION: { + code: 400, + message: " Error: CSAR packaging failed for %1 %2. Artifact %3 [%4] was not found", + messageId: "SVC4659" + } +#---------SVC4660------------------------------ +# %1 - assetType +# %2 - matching generic node type name + GENERIC_TYPE_NOT_FOUND: { + code: 404, + message: "Creation of %1 failed. Generic type %2 was not found", + messageId: "SVC4660" + } diff --git a/catalog-be/src/main/resources/config/logback.xml b/catalog-be/src/main/resources/config/logback.xml index 5d5e4c670d..8ba0a31944 100644 --- a/catalog-be/src/main/resources/config/logback.xml +++ b/catalog-be/src/main/resources/config/logback.xml @@ -9,7 +9,9 @@ + value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{BeginTimestamp}|%X{EndTimestamp}|%X{uuid}|%X{serviceInstanceID}|%thread|%X{ServerName}|%X{ServiceName}|${ECOMP-subcomponent-name}|%X{userId}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%level|%X{alarmSeverity}|%X{localAddr}|%X{ElapsedTime}|${beFqdn}|%X{remoteAddr}|%logger{35}|%X{timer}|ActivityType=<%M>, Desc=<%msg>%n" /> + + @@ -113,7 +115,8 @@ DENY - NEUTRAL + + ACCEPT @@ -132,6 +135,52 @@ + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/debug_by_package.log + + + + + + + TRANSACTION_MARKER + + NEUTRAL + DENY + + + + + + + e.level.toInt() <= DEBUG.toInt() + + + DENY + NEUTRAL + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/debug_by_package.log.%i + + 1 + 10 + + + + 20MB + + + ${asdc-debug-log-pattern} + + + @@ -143,6 +192,7 @@ AUDIT_MARKER + AUDIT DENY ACCEPT @@ -163,6 +213,38 @@ ${default-log-pattern} + + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/metrics.log + + + + + + METRICS + + DENY + ACCEPT + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/metrics.log.%i + + 1 + 10 + + + + 20MB + + + ${default-log-pattern} + + + + diff --git a/catalog-be/src/main/resources/config/titan.properties b/catalog-be/src/main/resources/config/titan.properties index 7eb57235c7..5411a44224 100644 --- a/catalog-be/src/main/resources/config/titan.properties +++ b/catalog-be/src/main/resources/config/titan.properties @@ -8,3 +8,4 @@ cache.db-cache-time = 180000 cache.db-cache-size = 0.5 cache.tx-cache-size = 500000 +storage.cassandra.keyspace=sdctitan diff --git a/catalog-be/src/main/resources/elasticsearch.yml b/catalog-be/src/main/resources/elasticsearch.yml index b4634c8213..71ccdbb8f5 100644 --- a/catalog-be/src/main/resources/elasticsearch.yml +++ b/catalog-be/src/main/resources/elasticsearch.yml @@ -1,17 +1,24 @@ -cluster.name: elasticsearch_1_5_2 - +cluster.name: elasticsearch + +discovery.zen.ping.multicast.enabled: false +discovery.zen.ping.unicast.enabled: true discovery.zen.ping.unicast.hosts: elasticsearch_host http.cors.enabled: true -#plugin.types: "DeleteByQueryPlugin" -#path.home: "/home/vagrant/catalog-be/config" + +path.home: "/home/vagrant/catalog-be/config" elasticSearch.transportclient: true transport.client.initial_nodes: - elasticsearch_host:9300 +#shield.user: asdc:Aa12345 +#shield.ssl.keystore.path: "/vagrant/install/resources/catalog-be/keystore/es-client.jks" +#shield.ssl.keystore.password: Aa123456 +#shield.transport.ssl: true + ##################### Elasticsearch Configuration Example ##################### # This file contains an overview of various configuration settings, @@ -157,7 +164,6 @@ index.number_of_replicas: 0 # Path to directory containing configuration (this file and logging.yml): # path.conf: /src/test/resources -#path.home: /src/test/resources # Path to directory where to store index data allocated for this node. # diff --git a/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.yml b/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.yml index d8d9f20d40..c94909101b 100644 --- a/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.yml +++ b/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.yml @@ -144,6 +144,8 @@ tosca.capabilities.Container.Docker: required: false tosca.capabilities.network.Linkable: derived_from: tosca.capabilities.Root +org.openecomp.capabilities.AllottedResource: + derived_from: tosca.capabilities.Root tosca.capabilities.nfv.Metric: derived_from: tosca.capabilities.Endpoint org.openecomp.capabilities.Metric: diff --git a/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.zip b/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.zip index add3a8ce1f..1742545f14 100644 Binary files a/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.zip and b/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/categories/categoryTypes.yml b/catalog-be/src/main/resources/import/tosca/categories/categoryTypes.yml index 9ddce45e4e..8914207b0f 100644 --- a/catalog-be/src/main/resources/import/tosca/categories/categoryTypes.yml +++ b/catalog-be/src/main/resources/import/tosca/categories/categoryTypes.yml @@ -28,8 +28,8 @@ resources: name: "LAN Connectors" icons: ['network','connector','port'] Infrastructure: - name: "Infrastructure" - icons: ['ucpe'] + name: "Infrastructure" + icons: ['ucpe'] NetworkLayer4: name: "Network L4+" subcategories: @@ -113,4 +113,31 @@ resources: icons: ['dcae_database'] Policy: name: "Policy" - icons: ['dcae_policy'] \ No newline at end of file + icons: ['dcae_policy'] + Template: + name: "Template" + subcategories: + MonitoringTemplate: + name: "Monitoring Template" + icons: ['monitoring_template'] + AllottedResource: + name: "Allotted Resource" + subcategories: + AllottedResource: + name: "Allotted Resource" + icons: ['allotted_resource'] + TunnelXConnect: + name: "Tunnel XConnect" + icons: ['tunnel_x_connect'] + IpMuxDemux: + name: "IP Mux Demux" + icons: ['ip_mux_demux'] + ServiceAdmin: + name: "Service Admin" + icons: ['service_admin'] + ContrailRoute: + name: "Contrail Route" + icons: ['contrail_route'] + SecurityZone: + name: "Security Zone" + icons: ['security_zone'] \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/categories/categoryTypes.zip b/catalog-be/src/main/resources/import/tosca/categories/categoryTypes.zip index c04a2faefc..7a0e6bcad7 100644 Binary files a/catalog-be/src/main/resources/import/tosca/categories/categoryTypes.zip and b/catalog-be/src/main/resources/import/tosca/categories/categoryTypes.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml index 1fdc3a2cd2..b4c442f3df 100644 --- a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml +++ b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml @@ -13,15 +13,15 @@ boolean: float: derived_from: tosca.datatypes.Root -json: - derived_from: tosca.datatypes.Root - list: derived_from: tosca.datatypes.Root map: derived_from: tosca.datatypes.Root +json: + derived_from: tosca.datatypes.Root + tosca.datatypes.Credential: derived_from: tosca.datatypes.Root properties: @@ -107,7 +107,7 @@ tosca.datatypes.network.PortSpec: constraints: - in_range: [ 1, 65535 ] - +###################new Data Types Onboarding Integration########################## org.openecomp.datatypes.heat.network.AddressPair: derived_from: tosca.datatypes.Root @@ -123,6 +123,7 @@ org.openecomp.datatypes.heat.network.AddressPair: description: IP address required: false status: SUPPORTED + org.openecomp.datatypes.heat.network.subnet.HostRoute: derived_from: tosca.datatypes.Root description: Host route info for the subnet @@ -309,6 +310,7 @@ org.openecomp.datatypes.heat.novaServer.network.PortExtraProperties: status: SUPPORTED entry_schema: type: string + org.openecomp.datatypes.heat.novaServer.network.AddressInfo: derived_from: tosca.datatypes.network.NetworkInfo description: Network addresses with corresponding port id @@ -318,6 +320,7 @@ org.openecomp.datatypes.heat.novaServer.network.AddressInfo: description: Port id required: false status: SUPPORTED + org.openecomp.datatypes.heat.neutron.port.FixedIps: derived_from: tosca.datatypes.Root description: subnet/ip_address @@ -332,6 +335,7 @@ org.openecomp.datatypes.heat.neutron.port.FixedIps: description: IP address desired in the subnet for this port required: false status: SUPPORTED + org.openecomp.datatypes.heat.FileInfo: derived_from: tosca.datatypes.Root description: Heat File Info @@ -352,6 +356,7 @@ org.openecomp.datatypes.heat.FileInfo: - env - volume - network + org.openecomp.datatypes.heat.contrail.network.rule.PortPairs: derived_from: tosca.datatypes.Root description: source and destination port pairs @@ -366,6 +371,7 @@ org.openecomp.datatypes.heat.contrail.network.rule.PortPairs: description: End port required: false status: SUPPORTED + org.openecomp.datatypes.heat.contrail.network.rule.Rule: derived_from: tosca.datatypes.Root description: policy rule @@ -413,6 +419,7 @@ org.openecomp.datatypes.heat.contrail.network.rule.Rule: description: Direction required: false status: SUPPORTED + org.openecomp.datatypes.heat.contrail.network.rule.RuleList: derived_from: tosca.datatypes.Root description: list of policy rules @@ -423,7 +430,8 @@ org.openecomp.datatypes.heat.contrail.network.rule.RuleList: required: false status: SUPPORTED entry_schema: - type: corg.openecomp.datatypes.heat.contrail.network.rule.Rule + type: org.openecomp.datatypes.heat.contrail.network.rule.Rule + org.openecomp.datatypes.heat.contrail.network.rule.VirtualNetwork: derived_from: tosca.datatypes.Root description: source and destination addresses @@ -507,6 +515,7 @@ org.openecomp.datatypes.heat.network.neutron.SecurityRules.Rule: - in_range: - 0 - 65535 + org.openecomp.datatypes.heat.substitution.SubstitutionFiltering: derived_from: tosca.datatypes.Root description: Substitution Filter @@ -542,6 +551,7 @@ org.openecomp.datatypes.heat.substitution.SubstitutionFiltering: required: false default: true status: SUPPORTED + org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.RefDataSequence: derived_from: tosca.datatypes.Root description: network policy refs data sequence @@ -556,6 +566,7 @@ org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.RefDataSequence: description: Network Policy ref data sequence Minor required: false status: SUPPORTED + org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.RefData: derived_from: tosca.datatypes.Root description: network policy refs data @@ -565,6 +576,7 @@ org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.RefData: description: Network Policy ref data sequence required: false status: SUPPORTED + org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.ref.data.IpamSubnet: derived_from: tosca.datatypes.Root description: Network Ipam Ref Data Subnet @@ -579,6 +591,7 @@ org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.ref.data.IpamSubnet description: Network ipam refs data ipam subnets ip prefix required: false status: SUPPORTED + org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.ref.data.IpamSubnetList: derived_from: tosca.datatypes.Root description: Network Ipam Ref Data Subnet List @@ -593,6 +606,7 @@ org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.ref.data.IpamSubnet description: Network ipam refs data ipam subnets addr from start required: false status: SUPPORTED + org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.IpamRefData: derived_from: tosca.datatypes.Root description: Network Ipam Ref Data @@ -604,6 +618,7 @@ org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.IpamRefData: status: SUPPORTED entry_schema: type: org.openecomp.datatypes.heat.contrailV2.virtual.network.rule.ref.data.IpamSubnetList + org.openecomp.datatypes.heat.contrailV2.network.rule.SrcVirtualNetwork: derived_from: tosca.datatypes.Root description: source addresses @@ -613,6 +628,7 @@ org.openecomp.datatypes.heat.contrailV2.network.rule.SrcVirtualNetwork: description: Source addresses Virtual network required: false status: SUPPORTED + org.openecomp.datatypes.heat.contrailV2.network.rule.DstVirtualNetwork: derived_from: tosca.datatypes.Root description: destination addresses @@ -622,6 +638,7 @@ org.openecomp.datatypes.heat.contrailV2.network.rule.DstVirtualNetwork: description: Destination addresses Virtual network required: false status: SUPPORTED + org.openecomp.datatypes.heat.contrailV2.network.rule.DstPortPairs: derived_from: tosca.datatypes.Root description: destination port pairs @@ -636,6 +653,7 @@ org.openecomp.datatypes.heat.contrailV2.network.rule.DstPortPairs: description: End port required: false status: SUPPORTED + org.openecomp.datatypes.heat.contrailV2.network.rule.SrcPortPairs: derived_from: tosca.datatypes.Root description: source port pairs @@ -650,6 +668,7 @@ org.openecomp.datatypes.heat.contrailV2.network.rule.SrcPortPairs: description: End port required: false status: SUPPORTED + org.openecomp.datatypes.heat.contrailV2.network.rule.ActionList: derived_from: tosca.datatypes.Root description: Action List @@ -666,22 +685,7 @@ org.openecomp.datatypes.heat.contrailV2.network.rule.ActionList: status: SUPPORTED entry_schema: type: string -org.openecomp.datatypes.heat.contrailV2.network.rule.ActionList: - derived_from: tosca.datatypes.Root - description: Action List - properties: - network_policy_entries_policy_rule_action_list_simple_action: - type: string - description: Simple Action - required: false - status: SUPPORTED - network_policy_entries_policy_rule_action_list_apply_service: - type: list - description: Apply Service - required: false - status: SUPPORTED - entry_schema: - type: string + org.openecomp.datatypes.heat.contrailV2.network.rule.Rule: derived_from: tosca.datatypes.Root description: policy rule @@ -729,6 +733,7 @@ org.openecomp.datatypes.heat.contrailV2.network.rule.Rule: description: Action list required: false status: SUPPORTED + org.openecomp.datatypes.heat.contrailV2.network.rule.RuleList: derived_from: tosca.datatypes.Root description: list of policy rules @@ -740,6 +745,7 @@ org.openecomp.datatypes.heat.contrailV2.network.rule.RuleList: status: SUPPORTED entry_schema: type: org.openecomp.datatypes.heat.contrailV2.network.rule.Rule + org.openecomp.datatypes.heat.network.contrail.port.StaticRoute: derived_from: tosca.datatypes.Root description: static route @@ -759,6 +765,7 @@ org.openecomp.datatypes.heat.network.contrail.port.StaticRoute: description: Next hop type required: false status: SUPPORTED + org.openecomp.datatypes.heat.network.contrail.AddressPair: derived_from: tosca.datatypes.Root description: Address Pair @@ -782,6 +789,7 @@ org.openecomp.datatypes.heat.network.contrail.AddressPair: description: Mac address required: false status: SUPPORTED + org.openecomp.datatypes.heat.network.contrail.InterfaceData: derived_from: tosca.datatypes.Root description: Interface Data @@ -810,6 +818,7 @@ org.openecomp.datatypes.heat.network.contrail.InterfaceData: description: IP for this interface required: false status: SUPPORTED + org.openecomp.datatypes.heat.contrailV2.virtual.machine.interface.Properties: derived_from: tosca.datatypes.Root description: Virtual Machine Interface Properties. @@ -818,4 +827,360 @@ org.openecomp.datatypes.heat.contrailV2.virtual.machine.interface.Properties: type: string description: Service Interface Type. required: false - status: SUPPORTED \ No newline at end of file + status: SUPPORTED + +org.openecomp.datatypes.Root: + derived_from: tosca.datatypes.Root + description: > + The ECOMP root Data Type all other Data Types derive from + properties: + supplemental_data: + type: map + entry_schema: + description: > + A placeholder for missing properties that would be included in future ecomp model versions. + fromat : + type: string + +org.openecomp.datatypes.AssignmentRequirements: + derived_from: org.openecomp.datatypes.Root + properties: + is_required: + description: | + "true" indicates that assignment is required + type: boolean + default: false + required: true + count: + description: number of assignments required + type: integer + required: false + +org.openecomp.datatypes.network.SubnetAssignments: + derived_from: org.openecomp.datatypes.Root + properties: + ip_network_address_plan: + type: string + required: false + description: Reference to EIPAM, VLAN or other address plan ID used to assign subnets to this network + dhcp_enabled: + type: boolean + required: false + description: \"true\" indicates the network has 1 or more policies + ip_version: + type: integer + constraints: + - valid_values: [4,6] + required: true + description: The IP version of the subnet + cidr_mask: + type: integer + required: true + description: The default subnet CIDR mask + min_subnets_count: + type: integer + default: 1 + required: true + description: Quantity of subnets that must be initially assigned + +org.openecomp.datatypes.network.IPv4SubnetAssignments: + derived_from: org.openecomp.datatypes.network.SubnetAssignments + properties: + use_ipv4: + type: boolean + required: true + description: Indicates IPv4 subnet assignments + +org.openecomp.datatypes.network.IPv6SubnetAssignments: + derived_from: org.openecomp.datatypes.network.SubnetAssignments + properties: + use_ipv6: + type: boolean + required: true + description: Indicates IPv6 subnet assignments + +org.openecomp.datatypes.network.NetworkAssignments: + derived_from: org.openecomp.datatypes.Root + properties: + ecomp_generated_network_assignment: + type: boolean + required: true + default: false + description: > + \"true\" indicates that the network assignments will be auto-generated by ECOMP + \"false\" indicates operator-supplied Network assignments file upload is required (e.g. VID will present prompt to operator to upload operator-supplied Network assignments file). + is_shared_network: + type: boolean + required: true + description: \"true\" means this network is shared by multiple Openstack tenants + is_external_network: + type: boolean + required: true + default: false + description: > + \"true\" means this Contrail external network + ipv4_subnet_default_assignment: + type: org.openecomp.datatypes.network.IPv4SubnetAssignments + required: true + description: IPv4 defualt subnet assignments + ipv6_subnet_default_assignment: + type: org.openecomp.datatypes.network.IPv6SubnetAssignments + required: true + description: IPv6 defualt subnet assignments + +org.openecomp.datatypes.network.ProviderNetwork: + derived_from: org.openecomp.datatypes.Root + properties: + is_provider_network: + type: boolean + required: true + description: \"true\" indicates that this a Neutron provider type of network + physical_network_name: + type: string + required: false + constraints: + - valid_values: ["Physnet41", "Physnet42", "Physnet43", "Physnet44", "Physnet21", "Physnet22"] + description: > + Identifies the NUMA processor cluster to which this physical network interface belongs. + NUMA instance correlates to the first digit of the Physical Network Name suffix (e.g. \"01\" = NUMA 0, \"11\" = NUMA 1) + numa: + type: string + required: false + constraints: + - valid_values: ["NUMA 0", "NUMA 1"] + description: > + PNIC instance within the NUMA processor cluster + PNIC Instance correlates to the second digit of the Physical Network Name suffix (e.g. "01" = PNIC 1, "02" = "PNIC 2) + pnic_instance: + type: integer + required: false + description: PNIC instance within the NUMA processor cluster + +org.openecomp.datatypes.network.NetworkFlows: + derived_from: org.openecomp.datatypes.Root + properties: + is_network_policy: + type: boolean + required: false + default: false + description: \"true\" indicates the network has 1 or more policies + network_policy: + type: string + required: false + description: "Identifies the specific Cloud network policy that must be applied to this network (source: from Policy Manager)." + is_bound_to_vpn: + type: boolean + required: false + default: false + description: \"true\" indicates the network has 1 or more vpn bindings + vpn_binding: + type: string + required: false + description: "Identifies the specific VPN Binding entry in A&AI that must be applied when creating this network (source: A&AI)" + +org.openecomp.datatypes.network.VlanRequirements: + derived_from: org.openecomp.datatypes.Root + properties: + vlan_range_plan: + type: string + required: true + description: reference to a vlan range plan + vlan_type: + type: string + required: true + constraints: + - valid_values: ["c-tag", "s-tag"] + description: identifies the vlan type (e.g., c-tag) + vlan_count: + type: integer + required: true + description: identifies the number of vlan tags to assign to the CP from the plan + +org.openecomp.datatypes.network.IpRequirements: + derived_from: org.openecomp.datatypes.Root + properties: + ip_version: + type: integer + required: true + constraints: + - valid_values: + - 4 + - 6 + ip_count: + description: identifies the number of ip address to assign to the CP from the plan + type: integer + required: false + floating_ip_count: + type: integer + required: false + subnet_role: + type: string + required: false + assingment_method: + type: string + required: true + constraints: + - valid_values: + - fixed + - dhcp + dhcp_enabled: + type: boolean + required: false + ip_count_required: + description: identifies the number of ip address to assign to the CP from the plan + type: org.openecomp.datatypes.AssignmentRequirements + required: false + floating_ip_count_required: + type: org.openecomp.datatypes.AssignmentRequirements + required: false + +org.openecomp.datatypes.network.MacAssignments: + derived_from: org.openecomp.datatypes.Root + properties: + mac_range_plan: + type: string + required: true + description: reference to a MAC address range plan + mac_count: + type: integer + required: true + description: identifies the number of MAC addresses to assign to the CP from the plan + +org.openecomp.datatypes.EcompHoming: + derived_from: org.openecomp.datatypes.Root + properties: + ecomp_selected_instance_node_target: + type: boolean + required: true + default: false + description: > + \"true\" indicates that the target deployment node for this instance will be auto-selected by ECOMP + \"false\" indicates operator-supplied instance target deployment node required (e.g. VID will present a prompt to operator and collect the + operator-selected target node for the deployment of this Network instance). + homing_policy: + type: string + required: false + description: Referenc to a service level homing policy that ECOMP will use for instance deployment target node + instance_node_target: + type: string + required: false + description: Instance target deployment node + +org.openecomp.datatypes.EcompNaming: + derived_from: org.openecomp.datatypes.Root + properties: + ecomp_generated_naming: + type: boolean + required: true + default: true + description: > + \"true\" indicates that the name for the instance will be auto-generated by ECOMP. + \"false\" indicates operator-supplied name required (e.g. VID will present prompt to operator and collect the operator-supplied instance name). + naming_policy: + type: string + required: false + description: Referenc to naming policy that ECOMP will use when the name is auto-generated + +org.openecomp.datatypes.network.MacRequirements: + derived_from: org.openecomp.datatypes.Root + properties: + mac_range_plan: + description: reference to a MAC address range plan + type: string + required: false + mac_count: + description: identifies the number of MAC addresses to assign to the CP from the plan + type: integer + required: false + mac_count_required: + description: identifies the number of MAC addresses to assign to the CP from the plan + type: org.openecomp.datatypes.AssignmentRequirements + +org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPairIp: + derived_from: tosca.datatypes.Root + description: Virtual Machine Sub Interface Address Pair IP. + properties: + ip_prefix: + type: string + description: IP Prefix. + required: false + status: SUPPORTED + ip_prefix_len: + type: integer + description: IP Prefix Len. + required: false + status: SUPPORTED + +org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.MacAddress: + derived_from: tosca.datatypes.Root + description: Virtual Machine Sub Interface Mac Address. + properties: + mac_address: + type: list + description: Mac Addresses List. + required: false + status: SUPPORTED + entry_schema: + type: string + +org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.Properties: + derived_from: tosca.datatypes.Root + description: Virtual Machine Sub Interface VLAN Properties. + properties: + sub_interface_vlan_tag: + type: string + description: Sub Interface VLAN Tag. + required: false + status: SUPPORTED + +org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPair: + derived_from: tosca.datatypes.Root + description: Virtual Machine Sub Interface Address Pair. + properties: + address_mode: + type: string + description: Address Mode. + required: false + status: SUPPORTED + ip: + type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPairIp + description: IP. + required: false + status: SUPPORTED + mac: + type: string + description: Mac. + required: false + status: SUPPORTED + +org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPairs: + derived_from: tosca.datatypes.Root + description: Virtual Machine Sub Interface Address Pairs. + properties: + allowed_address_pair: + type: list + description: Addresses pair List. + required: false + status: SUPPORTED + entry_schema: + type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPair + +org.openecomp.datatypes.Naming: + derived_from: org.openecomp.datatypes.Root + properties: + ecomp_generated_naming: + description: | + "true" indicates that the name for the instance will be auto-generated by ECOMP. "false" indicates operator-supplied name required (e.g. VID will present prompt to operator and collect the operator-supplied instance name). + type: boolean + default: true + required: true + naming_policy: + description: Reference to naming policy that ECOMP will use when the name is auto-generated + type: string + required: false + instance_name: + description: indicates operator-supplied name required (e.g. VID will present prompt to operator and collect the operator-supplied instance name). + type: string + required: false + + diff --git a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip index 2249a8bd5c..4f3e269c69 100644 Binary files a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip and b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.yml b/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.yml index 1df2cbdd04..ce457e4add 100644 --- a/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.yml +++ b/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.yml @@ -22,6 +22,61 @@ org.openecomp.groups.VfModule: required: true default: false status: SUPPORTED + vf_module_label: + type: string + required: true + description: > + Alternate textual key used to reference this VF-Module model. + Must be unique within the VNF model + vf_module_description: + type: string + required: true + description: > + Description of the VF-modules contents and purpose + (e.g. "Front-End" or "Database Cluster") + min_vf_module_instances: + type: integer + required: true + description: The minimum instances of this VF-Module + max_vf_module_instances: + type: integer + required: false + description: The maximum instances of this VF-Module + initial_count: + type: integer + required: false + description: > + The initial count of instances of the VF-Module. The value must be in the + range between min_vfmodule_instances and max_vfmodule_instances. + If no value provided the initial count is the min_vfmodule_instances. + vf_module_type: + type: string + required: true + constraint: + - valid_values: ["Base", "Expansion"] + volume_group: + type: boolean + required: true + default: false + description: > + "true" indicates that this VF Module model requires attachment to a Volume + Group. + VID operator must select the Volume Group instance to attach to a VF-Module + at deployment time. + availability_zone_count: + type: integer + required: false + description: > + Quantity of Availability Zones needed for this VF-Module + (source: Extracted from VF-Module HEAT template) + vfc_list: + type: map + entry_schema: + description: : + type: string + required: false + description: > + Identifies the set of VM types and their count included in the VF-Module tosca.groups.Root: description: The TOSCA Group Type all other TOSCA Group Types derive from interfaces: diff --git a/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.zip b/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.zip index e386507c92..7acd7a6b45 100644 Binary files a/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.zip and b/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types.zip b/catalog-be/src/main/resources/import/tosca/heat-types.zip new file mode 100644 index 0000000000..ebb5afd09d Binary files /dev/null and b/catalog-be/src/main/resources/import/tosca/heat-types.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.json b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.json new file mode 100644 index 0000000000..b9423bc148 --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.json @@ -0,0 +1,21 @@ +{ + "payloadName": "Generic_Service.yml", + "contactId": "jh0003", + "name": "Generic_Service", + "description": "Represents a generic Service.", + "resourceIconPath": "defaulticon", + "resourceType": "ABSTRACT", + "categories": [ + { + "name": "Generic", + "subcategories": [ + { + "name": "Abstract" + } + ] + } +], + "tags": [ + "Generic_Service" + ] +} \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.yml b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.yml new file mode 100644 index 0000000000..902cf0c0c8 --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.yml @@ -0,0 +1,5 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.abstract.nodes.service: + derived_from: tosca.nodes.Root + \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.zip b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.zip new file mode 100644 index 0000000000..060dec1aa1 Binary files /dev/null and b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_Service/Generic_Service.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.json b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.json new file mode 100644 index 0000000000..87c22f5f9d --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.json @@ -0,0 +1,21 @@ +{ + "payloadName": "Generic_VF.yml", + "contactId": "jh0003", + "name": "Generic_VF", + "description": "Represents a generic VF.", + "resourceIconPath": "defaulticon", + "resourceType": "ABSTRACT", + "categories": [ + { + "name": "Generic", + "subcategories": [ + { + "name": "Abstract" + } + ] + } +], + "tags": [ + "Generic_VF" + ] +} \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.yml b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.yml new file mode 100644 index 0000000000..6618650ef3 --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.yml @@ -0,0 +1,27 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.abstract.nodes.VF: + derived_from: tosca.nodes.Root + properties: + nf_function: + type: string + nf_role: + type: string + nf_naming_code: + type: string + nf_type: + type: string + nf_naming: + type: org.openecomp.datatypes.Naming + Default: true + availability_zone_max_count: + type: integer + default: 1 + constraints: + - valid_values: [0,1,2] + min_instances: + type: integer + max_instances: + type: integer + + \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.zip b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.zip new file mode 100644 index 0000000000..d564813e2f Binary files /dev/null and b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.json b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.json new file mode 100644 index 0000000000..0145fbc14c --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.json @@ -0,0 +1,21 @@ +{ + "payloadName": "Generic_VFC.yml", + "contactId": "jh0003", + "name": "Generic_VFC", + "description": "Represents a generic VFC.", + "resourceIconPath": "defaulticon", + "resourceType": "ABSTRACT", + "categories": [ + { + "name": "Generic", + "subcategories": [ + { + "name": "Abstract" + } + ] + } +], + "tags": [ + "Generic_VFC" + ] +} \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.yml b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.yml new file mode 100644 index 0000000000..276ee03e63 --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.yml @@ -0,0 +1,50 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.abstract.nodes.VFC: + derived_from: org.openecomp.resource.abstract.nodes.AbstractSubstitute + properties: + nfc_function: + type: string + high_availablity: + type: string + description: high_availablity + required: false + status: SUPPORTED + vm_image_name: + type: string + description: Master image_name volume id + required: true + status: SUPPORTED + vm_flavor_name: + type: string + description: Master image_name volume id + required: true + status: SUPPORTED + nfc_naming_code: + type: string + description: nfc code for instance naming + required: false + status: SUPPORTED + vm_type_tag: + type: string + description: vm type based on naming Convention + required: false + status: SUPPORTED + nfc_naming: + type: org.openecomp.datatypes.Naming + description: vfc naming + min_instances: + type: integer + description: Minimum number of VFC Instances + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + max_instances: + type: integer + description: Maximum number of VFC Instances + required: false + status: SUPPORTED + constraints: + - greater_or_equal: 1 \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.zip b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.zip new file mode 100644 index 0000000000..f98f53333a Binary files /dev/null and b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VFC/Generic_VFC.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.yml b/catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.yml index 48db2b609a..7aa7edfe70 100644 --- a/catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.yml +++ b/catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.yml @@ -1,11 +1,4 @@ tosca_definitions_version: tosca_simple_yaml_1_0_0 -metadata: - template_name: AbstractSubstituteGlobalTypes - template_version: 1.0.0 -description: Abstract Substitute Global Types -imports: - common_definitions: - file: CommonGlobalTypesServiceTemplate.yaml node_types: org.openecomp.resource.abstract.nodes.AbstractSubstitute: derived_from: tosca.nodes.Root diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.zip b/catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.zip index 07e4941e6b..2c38ab43a1 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/abstractSubstitute/abstractSubstitute.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.yml b/catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.yml index 3bb227d1ec..87dfc313ae 100644 --- a/catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.yml +++ b/catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.yml @@ -1,78 +1,50 @@ tosca_definitions_version: tosca_simple_yaml_1_0_0 -metadata: - template_name: CinderVolumeGlobalTypes - template_version: 1.0.0 -description: Cinder Volume TOSCA Global Types -relationship_types: - org.openecomp.relationships.cinder.VolumeAttachesTo: - derived_from: tosca.relationships.AttachesTo - description: This type represents an attachment relationship for associating volume - properties: - volume_id: - type: string - description: The ID of the volume to be attached - required: true - status: SUPPORTED - location: - type: string - description: The location where the volume is exposed on the instance, mountpoint - required: false - status: SUPPORTED - instance_uuid: - type: string - description: The ID of the server to which the volume attaches - required: true - status: SUPPORTED - attributes: - show: - type: string - description: Detailed information about resource - status: SUPPORTED node_types: org.openecomp.resource.vfc.nodes.heat.cinder.Volume: - derived_from: tosca.nodes.BlockStorage + derived_from: org.openecomp.resource.vfc.nodes.volume properties: availability_zone: - type: string description: The availability zone in which the volume will be created - required: false + type: string status: SUPPORTED + required: false image: - type: string description: If specified, the name or ID of the image to create the volume from - required: false + type: string status: SUPPORTED + required: false metadata: - type: map description: Key/value pairs to associate with the volume - required: false + type: map status: SUPPORTED entry_schema: type: string + required: false volume_type: - type: string description: If specified, the type of volume to use, mapping to a specific backend - required: false + type: string status: SUPPORTED + required: false description: - type: string description: A description of the volume - required: false + type: string status: SUPPORTED + required: false device_type: - type: string description: Device type - required: false + type: string status: SUPPORTED + required: false constraints: - valid_values: - cdrom - disk disk_bus: + description: 'Bus of the device: hypervisor driver chooses a suitable default + if omitted' type: string - description: 'Bus of the device: hypervisor driver chooses a suitable default if omitted' - required: false status: SUPPORTED + required: false constraints: - valid_values: - ide @@ -81,97 +53,97 @@ node_types: - usb - virtio backup_id: - type: string description: If specified, the backup to create the volume from - required: false + type: string status: SUPPORTED + required: false source_volid: - type: string description: If specified, the volume to use as source - required: false + type: string status: SUPPORTED + required: false boot_index: - type: integer description: Integer used for ordering the boot disks - required: false + type: integer status: SUPPORTED + required: false size: - type: scalar-unit.size description: The requested storage size (default unit is MB) - required: false + type: scalar-unit.size status: SUPPORTED + required: false constraints: - greater_or_equal: 1 GB read_only: - type: boolean description: Enables or disables read-only access mode of volume - required: false + type: boolean status: SUPPORTED + required: false name: - type: string description: A name used to distinguish the volume - required: false + type: string status: SUPPORTED + required: false scheduler_hints: - type: map description: Arbitrary key-value pairs specified by the client to help the Cinder scheduler creating a volume - required: false + type: map status: SUPPORTED entry_schema: type: string + required: false swap_size: - type: scalar-unit.size description: The size of the swap, in MB - required: false + type: scalar-unit.size status: SUPPORTED + required: false delete_on_termination: - type: boolean description: Indicate whether the volume should be deleted when the server is terminated - required: false + type: boolean status: SUPPORTED + required: false multiattach: - type: boolean description: Whether allow the volume to be attached more than once - required: false + type: boolean status: SUPPORTED + required: false attributes: display_description: - type: string description: Description of the volume + type: string status: SUPPORTED attachments: - type: string description: The list of attachments of the volume + type: string status: SUPPORTED entry_schema: type: string encrypted: - type: boolean description: Boolean indicating if the volume is encrypted or not + type: boolean status: SUPPORTED show: - type: string description: Detailed information about resource + type: string status: SUPPORTED created_at: - type: timestamp description: The timestamp indicating volume creation + type: timestamp status: SUPPORTED display_name: - type: string description: Name of the volume + type: string status: SUPPORTED metadata_values: - type: map description: Key/value pairs associated with the volume in raw dict form + type: map status: SUPPORTED entry_schema: type: string bootable: - type: boolean description: Boolean indicating if the volume can be booted or not + type: boolean status: SUPPORTED status: - type: string description: The current status of the volume + type: string status: SUPPORTED diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.zip b/catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.zip index 88506743ac..8b9a455c54 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/cinderVolume/cinderVolume.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.yml index 5bdee932a3..a1f40c5529 100644 --- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.yml +++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.yml @@ -1,11 +1,4 @@ tosca_definitions_version: tosca_simple_yaml_1_0_0 -metadata: - template_name: ContrailAbstractSubstituteGlobalTypes - template_version: 1.0.0 -description: Contrail Abstract Substitute Global Types -imports: - common_definitions: - file: CommonGlobalTypesServiceTemplate.yaml node_types: org.openecomp.resource.abstract.nodes.contrail.AbstractSubstitute: derived_from: org.openecomp.resource.abstract.nodes.AbstractSubstitute diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.zip index 6a2094bb9a..11d99be2e3 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/contrailAbstractSubstitute/contrailAbstractSubstitute.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.yml index d6ad4f953c..c2ba70e2d1 100644 --- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.yml +++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.yml @@ -1,14 +1,7 @@ tosca_definitions_version: tosca_simple_yaml_1_0_0 -metadata: - template_name: ContrailComputeGlobalTypes - template_version: 1.0.0 -description: Contrail Compute TOSCA Global Types -imports: - common_definitions: - file: CommonGlobalTypesServiceTemplate.yaml node_types: org.openecomp.resource.vfc.nodes.heat.contrail.Compute: - derived_from: tosca.nodes.Compute + derived_from: org.openecomp.resource.vfc.nodes.Compute properties: flavor: type: string @@ -86,4 +79,4 @@ node_types: status: type: string description: status of the compute - status: SUPPORTED \ No newline at end of file + status: SUPPORTED diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.zip index c9e3c8a062..c0cc411e5d 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/contrailCompute/contrailCompute.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.yml index b9d61e7769..2f8228ac85 100644 --- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.yml +++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.yml @@ -1,11 +1,4 @@ tosca_definitions_version: tosca_simple_yaml_1_0_0 -metadata: - template_name: ContrailNetworkRuleGlobalType - template_version: 1.0.0 -description: Contrail Network Rule Global Types -imports: - common_definitions: - file: CommonGlobalTypesServiceTemplate.yaml node_types: org.openecomp.resource.vfc.rules.nodes.heat.network.contrail.NetworkRules: derived_from: tosca.nodes.Root diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.zip index b687616cd8..639164711f 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/contrailNetworkRules/contrailNetworkRules.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.yml index a3e43a2fd1..ce99511bbe 100644 --- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.yml +++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.yml @@ -1,14 +1,7 @@ tosca_definitions_version: tosca_simple_yaml_1_0_0 -metadata: - template_name: ContrailPortGlobalTypes - template_version: 1.0.0 -description: Contrail Port TOSCA Global Types -imports: - common_definitions: - file: CommonGlobalTypesServiceTemplate.yaml node_types: org.openecomp.resource.cp.nodes.heat.network.contrail.Port: - derived_from: tosca.nodes.network.Port + derived_from: org.openecomp.resource.cp.nodes.network.Port properties: static_routes: type: list diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.zip index f9e5c415ae..6040f3cb17 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/contrailPort/contrailPort.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.yml index ccc6d3a2ab..ad4369ce40 100644 --- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.yml +++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.yml @@ -1,11 +1,4 @@ tosca_definitions_version: tosca_simple_yaml_1_0_0 -metadata: - template_name: ContrailV2NetworkRuleGlobalType - template_version: 1.0.0 -description: Contrail V2 Network Rule Global Types -imports: - common_definitions: - file: CommonGlobalTypesServiceTemplate.yaml node_types: org.openecomp.resource.vfc.rules.nodes.heat.network.contrailV2.NetworkRules: derived_from: tosca.nodes.Root diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.zip index eac99b3b90..a8a84e7eff 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2NetworkRules/contrailV2NetworkRules.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.json b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.json new file mode 100644 index 0000000000..216c85cb68 --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.json @@ -0,0 +1,15 @@ +{ + "payloadName": "contrailV2VLANSubInterface.yml", + "contactId": "jh0003", + "name": "contrailV2VLANSubInterface", + "description": "VLAN sub-Interface is a logical port which must be binded to a port. Regular port may have 1…N VLAN Interfaces.It can connect to its own network (regardless of the network the parent port can connect)", + "resourceIconPath": "network", + "resourceType": "CP", + "categories": [{ + "name": "Generic", + "subcategories": [{ + "name": "Network Elements" + }] + }], + "tags": ["contrailV2VLANSubInterface"] +} \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.yml new file mode 100644 index 0000000000..20f7372274 --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.yml @@ -0,0 +1,70 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.cp.nodes.heat.network.contrailV2.VLANSubInterface: + derived_from: org.openecomp.resource.cp.nodes.network.SubInterface + properties: + virtual_machine_interface_refs: + description: List of virtual machine interface. + type: list + status: SUPPORTED + entry_schema: + type: string + required: false + name: + description: Virtual Machine Sub Interface VLAN name + type: string + status: SUPPORTED + required: false + virtual_network_refs: + description: List of virtual networks. + type: list + status: SUPPORTED + entry_schema: + type: string + required: false + virtual_machine_interface_properties: + description: virtual machine interface properties. + type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.Properties + status: SUPPORTED + required: false + virtual_machine_interface_allowed_address_pairs: + description: Virtual Machine Sub Interface allowed address pairs. + type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPairs + status: SUPPORTED + required: false + virtual_machine_interface_mac_addresses: + description: List of mac addresses. + type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.MacAddress + status: SUPPORTED + required: false + security_group_refs: + description: List of security groups. + type: list + status: SUPPORTED + entry_schema: + type: string + required: false + port_tuple_refs: + description: List of port tuples. + type: list + status: SUPPORTED + entry_schema: + type: string + required: false + attributes: + fq_name: + description: The FQ name of the Virtual Network. + type: string + status: SUPPORTED + show: + description: All attributes. + type: string + status: SUPPORTED + requirements: + - binding: + capability: tosca.capabilities.network.Bindable + node: org.openecomp.resource.cp.nodes.network.Port + relationship: tosca.relationships.network.BindsTo + occurrences: + - 1 + - 1 \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.zip new file mode 100644 index 0000000000..eadba5ef28 Binary files /dev/null and b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VLANSubInterface/contrailV2VLANSubInterface.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.yml index ba324cf51a..a2179079b1 100644 --- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.yml +++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.yml @@ -1,59 +1,65 @@ tosca_definitions_version: tosca_simple_yaml_1_0_0 -metadata: - template_name: ContrailV2VirtualMachineInterfaceGlobalType - template_version: 1.0.0 -description: Contrail Virtual Machine Interface TOSCA Global Types -imports: - common_definitions: - file: CommonGlobalTypesServiceTemplate.yaml node_types: org.openecomp.resource.cp.nodes.heat.contrailV2.VirtualMachineInterface: - derived_from: tosca.nodes.network.Port + derived_from: org.openecomp.resource.cp.nodes.network.Port properties: - virtual_machine_intefrace_mac_addresses: - type: list - description: List of mac addresses. - required: false - status: SUPPORTED - entry_schema: - type: string name: - type: string description: Virtual Machine Interface name - required: false + type: string status: SUPPORTED + required: false security_group_refs: - type: list description: List of security groups. - required: false + type: list status: SUPPORTED entry_schema: type: string + required: false virtual_network_refs: - type: list description: List of virtual networks. - required: false + type: list status: SUPPORTED entry_schema: type: string + required: false virtual_machine_interface_properties: - type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.interface.Properties description: virtual machine interface properties. - required: false + type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.interface.Properties status: SUPPORTED + required: false port_tuple_refs: - type: list description: List of port tuples. + type: list + status: SUPPORTED + entry_schema: + type: string required: false + virtual_machine_interface_mac_addresses: + description: List of mac addresses. + type: list status: SUPPORTED entry_schema: type: string + required: false + virtual_machine_interface_allowed_address_pairs: + description: Virtual Machine Interface allowed address pairs. + type: org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPairs + status: SUPPORTED + required: false attributes: fq_name: - type: string description: The FQ name of the Virtual Network. + type: string status: SUPPORTED show: - type: string description: All attributes. + type: string status: SUPPORTED + capabilities: + binding: + type: tosca.capabilities.network.Bindable + occurrences: + - 0 + - UNBOUNDED + valid_source_types: + - org.openecomp.resources.cp.nodes.heat.network.contrailV2.VLANSubInterface \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.zip index 4b48a6838d..60950b65cc 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualMachineInterface/contrailV2VirtualMachineInterface.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.yml index 1ff1402411..0fa7c94a63 100644 --- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.yml +++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.yml @@ -1,14 +1,7 @@ tosca_definitions_version: tosca_simple_yaml_1_0_0 -metadata: - template_name: ContrailV2VirtualNetworkGlobalType - template_version: 1.0.0 -description: Contrail V2 Virtual Network Global Types -imports: - common_definitions: - file: CommonGlobalTypesServiceTemplate.yaml node_types: org.openecomp.resource.vl.nodes.heat.network.contrailV2.VirtualNetwork: - derived_from: tosca.nodes.network.Network + derived_from: org.openecomp.resource.vl.nodes.network.Network properties: network_ipam_refs_data: type: list diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.zip index 637e78da25..43f499bdbb 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/contrailV2VirtualNetwork/contrailV2VirtualNetwork.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.yml b/catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.yml index a5424c3c83..c0d1f3dab2 100644 --- a/catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.yml +++ b/catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.yml @@ -1,14 +1,7 @@ tosca_definitions_version: tosca_simple_yaml_1_0_0 -metadata: - template_name: ContrailVirtualNetworkGlobalType - template_version: 1.0.0 -description: Contrail Virtual Network Global Types -imports: - common_definitions: - file: CommonGlobalTypesServiceTemplate.yaml node_types: org.openecomp.resource.vl.nodes.heat.network.contrail.VirtualNetwork: - derived_from: tosca.nodes.network.Network + derived_from: org.openecomp.resource.vl.nodes.network.Network properties: shared: type: string @@ -81,4 +74,4 @@ node_types: type: tosca.capabilities.Attachment occurrences: - 1 - - UNBOUNDED + - UNBOUNDED \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.zip b/catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.zip index 17b32db41a..56d38c5272 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/contrailVirtualNetwork/contrailVirtualNetwork.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.yml b/catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.yml index 21241369c7..79876881cd 100644 --- a/catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.yml +++ b/catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.yml @@ -1,5 +1,4 @@ tosca_definitions_version: tosca_simple_yaml_1_0_0 - node_types: org.openecomp.resource.vl.ELine: derived_from: org.openecomp.resource.vl.VL diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.zip b/catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.zip index 132c5eebc5..8ba7cbceac 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/eline/eline.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.json b/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.json new file mode 100644 index 0000000000..ca20a27318 --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.json @@ -0,0 +1,21 @@ +{ + "payloadName": "extCp.yml", + "contactId": "DS200P", + "name": "ExtCP", + "description": "The AT&T Connection Point base type all other CP derive from", + "resourceIconPath": "network", + "resourceType": "CP", + "categories": [ + { + "name": "Generic", + "subcategories": [ + { + "name": "Network Elements" + } + ] + } +], + "tags": [ + "ExtCP" + ] +} diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.yml b/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.yml new file mode 100644 index 0000000000..e73cafe100 --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.yml @@ -0,0 +1,53 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.cp.extCP: + derived_from: tosca.nodes.Root + description: The SDC Connection Point base type all other CP derive from + properties: + network_role: + type: string + required: true + description: identical to VL network_role + order: + type: integer + required: true + description: The order of the CP on the compute instance (e.g. eth2). + network_role_tag: + type: string + required: true + description: Must correlate to the set of defined “network-role” tag identifiers from the associated HEAT template + mac_requirements: + type: org.openecomp.datatypes.network.MacRequirements + required: false + description: identifies MAC address assignments to the CP + vlan_requirements: + type: list + entry_schema: + type: org.openecomp.datatypes.network.VlanRequirements + required: false + description: identifies vlan address assignments to the CP + ip_requirements: + type: list + entry_schema: + type: org.openecomp.datatypes.network.IpRequirements + required: true + description: identifies IP requirements to the CP + exCP_naming: + type: org.openecomp.datatypes.Naming + subnetpoolid: + type: string + requirements: + virtualLink: + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + virtualBinding: + capability: tosca.capabilities.network.Bindable + relationship: tosca.relationships.network.BindsTo + external_virtualLink: + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + node: org.openecomp.resource.vl.VL + capabilities: + internal_connectionPoint: + type: tosca.capabilities.Node + valid_source_type: [tosca.nodes.network.Port] \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.zip b/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.zip new file mode 100644 index 0000000000..a26c323819 Binary files /dev/null and b/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.json b/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.json new file mode 100644 index 0000000000..8b9ff798ad --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.json @@ -0,0 +1,21 @@ +{ + "payloadName": "extVl.yml", + "contactId": "DS200P", + "name": "ExtVL", + "description": "ECOMP generic virtual link (network) base type for all other service-level and global networks", + "resourceIconPath": "network", + "resourceType": "VL", + "categories": [ + { + "name": "Generic", + "subcategories": [ + { + "name": "Network Elements" + } + ] + } +], + "tags": [ + "ExtVL" + ] +} diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.yml b/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.yml new file mode 100644 index 0000000000..3973598acd --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.yml @@ -0,0 +1,50 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.extVL: + derived_from: tosca.nodes.Root + description: VF Tenant oam protected network + properties: + network_type: + type: string + required: true + description: ECOMP supported network types. + network_role: + type: string + required: ture + description: > + Unique label that defines the role that this network performs. + example: vce oam network, vnat sr-iov1 network + network_scope: + type: string + constraints: + valid_values: ["VF", "SERVICE", "GLOBAL"] + description: > + Uniquely identifies the network scope. Valid values for the network scope + includes: + VF - VF-level network. Intra-VF network which connects the VFCs (VMs) + inside the VF. + SERVICE - Service-level network. Intra-Service network which connects + the VFs within the service + GLOBAL - Global network which can be shared by multiple services + network_technology: + type: string + required: true + description: ECOMP supported network technology + exVL_naming: + type: org.openecomp.datatypes.Naming + required: true + network_homing: + type: org.openecomp.datatypes.EcompHoming + required: true + network_assignments: + type: org.openecomp.datatypes.network.NetworkAssignments + required: true + provider_network: + type: org.openecomp.datatypes.network.ProviderNetwork + required: true + network_flows: + type: org.openecomp.datatypes.network.NetworkFlows + required: false + capabilities: + virtual_linkable: + type: tosca.capabilities.network.Linkable \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.zip b/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.zip new file mode 100644 index 0000000000..80b1e1a1dd Binary files /dev/null and b/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.json b/catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.json new file mode 100644 index 0000000000..68ff39afaf --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.json @@ -0,0 +1,20 @@ +{ + "payloadName": "globalCompute.yml", + "contactId": "jh0003", + "name": "GlobalCompute", + "description": "Represents a global virtual machine with monitoring capabilities.", + "resourceIconPath": "defaulticon", + "categories": [ + { + "name": "Generic", + "subcategories": [ + { + "name": "Abstract" + } + ] + } +], + "tags": [ + "GlobalCompute" + ] +} \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.yml b/catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.yml new file mode 100644 index 0000000000..4ac9950ee2 --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.yml @@ -0,0 +1,1300 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vfc.nodes.Compute: + derived_from: tosca.nodes.Compute + capabilities: + disk.ephemeral.size: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: GB + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.ephemeral.size + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Size of ephemeral disk + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: compute + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + instance: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: instance + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: instance + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Existence of instance + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: compute + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + memory: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: MB + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: memory + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Volume of RAM allocated to the instance + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: compute + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.iops: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: count/s + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.iops + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Average disk iops + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.device.read.requests: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: request + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.device.read.requests + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Number of read requests + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Cumulative + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + cpu.delta: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: ns + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: cpu.delta + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: CPU time used since previous datapoint + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Delta + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: compute + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.capacity: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.capacity + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: The amount of disk that the instance can see + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.device.read.bytes: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.device.read.bytes + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Volume of reads + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Cumulative + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.write.bytes: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.write.bytes + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Volume of writes + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Cumulative + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: compute + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.latency: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: ms + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.latency + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Average disk latency + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.device.read.bytes.rate: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B/s + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.device.read.bytes.rate + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Average rate of reads + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.usage: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.usage + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: The physical size in bytes of the image container on the host + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + cpu_util: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: '%' + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: cpu_util + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Average CPU utilization + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: compute + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.device.allocation: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.device.allocation + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: The amount of disk per device occupied by the instance on the host machine + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.write.requests.rate: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: request/s + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.write.requests.rate + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Average rate of write requests + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: compute + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.write.bytes.rate: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B/s + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.write.bytes.rate + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Average rate of writes + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: compute + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.device.latency: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: ms + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.device.latency + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Average disk latency per device + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + cpu: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: ns + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: cpu + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: CPU time used + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Cumulative + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: compute + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.device.write.requests: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: request + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.device.write.requests + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Number of write requests + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Cumulative + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.device.write.bytes: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.device.write.bytes + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Volume of writes + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Cumulative + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.read.requests: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: request + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.read.requests + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Number of read requests + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Cumulative + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: compute + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.root.size: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: GB + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.root.size + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Size of root disk + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: compute + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.device.write.bytes.rate: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B/s + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.device.write.bytes.rate + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Average rate of writes + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + vcpus: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: vcpu + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: vcpus + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Number of virtual CPUs allocated to the instance + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: compute + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.device.iops: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: count/s + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.device.iops + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Average disk iops per device + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.device.usage: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.device.usage + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: The physical size in bytes of the image container on the host per device + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.device.read.requests.rate: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: request/s + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.device.read.requests.rate + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Average rate of read requests + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.device.write.requests.rate: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: request/s + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.device.write.requests.rate + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Average rate of write requests + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.allocation: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.allocation + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: The amount of disk occupied by the instance on the host machine + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.read.bytes.rate: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B/s + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.read.bytes.rate + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Average rate of reads + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: compute + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.read.bytes: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.read.bytes + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Volume of reads + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Cumulative + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: compute + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + memory.usage: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: MB + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: memory.usage + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Volume of RAM used by the instance from the amount of its allocated memory + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: compute + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.device.capacity: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.device.capacity + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: The amount of disk per device that the instance can see + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: disk + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + memory.resident: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: MB + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: memory.resident + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Volume of RAM used by the instance on the physical machine + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: compute + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + disk.write.requests: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: request + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: disk.write.requests + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Number of write requests + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Cumulative + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: compute + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.zip b/catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.zip new file mode 100644 index 0000000000..23a471f246 Binary files /dev/null and b/catalog-be/src/main/resources/import/tosca/heat-types/globalCompute/globalCompute.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.json b/catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.json new file mode 100644 index 0000000000..d39ecdc4c0 --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.json @@ -0,0 +1,21 @@ +{ + "payloadName": "globalNetwork.yml", + "contactId": "jh0003", + "name": "GlobalNetwork", + "description": "Represents a simple , logical network service with monitoring capabilities.", + "resourceIconPath": "network", + "resourceType": "VL", + "categories": [ + { + "name": "Generic", + "subcategories": [ + { + "name": "Abstract" + } + ] + } +], + "tags": [ + "GlobalNetwork" + ] +} \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.yml b/catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.yml new file mode 100644 index 0000000000..6de2f2d422 --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.yml @@ -0,0 +1,14 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.nodes.network.Network: + derived_from: tosca.nodes.network.Network + properties: + vendor: + type: string + required: false + vl_name: + type: string + required: false + capabilities: + end_point: + type: tosca.capabilities.Endpoint \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.zip b/catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.zip new file mode 100644 index 0000000000..ddf8640b5b Binary files /dev/null and b/catalog-be/src/main/resources/import/tosca/heat-types/globalNetwork/globalNetwork.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.json b/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.json new file mode 100644 index 0000000000..f23b8a4e0b --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.json @@ -0,0 +1,15 @@ +{ + "payloadName": "globalPort.yml", + "contactId": "jh0003", + "name": "GlobalPort", + "description": "Represents a global logical port with monitoring capabilities.", + "resourceIconPath": "port", + "resourceType": "CP", + "categories": [{ + "name": "Generic", + "subcategories": [{ + "name": "Abstract" + }] + }], + "tags": ["GlobalPort"] +} \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.yml b/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.yml new file mode 100644 index 0000000000..89ee9f81f0 --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.yml @@ -0,0 +1,334 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.cp.nodes.network.Port: + derived_from: tosca.nodes.network.Port + properties: + network_role: + type: string + required: true + description: identical to VL network_role + order: + type: integer + required: true + description: The order of the CP on the compute instance (e.g. eth2). + network_role_tag: + description: Must correlate to the set of defined “network-role�? tag identifiers from the associated HEAT template + type: string + required: true + mac_requirements: + description: identifies MAC address assignments to the CP + type: org.openecomp.datatypes.network.MacRequirements + required: false + vlan_requirements: + description: identifies vlan address assignments to the CP + type: list + entry_schema: + type: org.openecomp.datatypes.network.VlanRequirements + required: false + ip_requirements: + description: identifies IP requirements to the CP + type: list + entry_schema: + type: org.openecomp.datatypes.network.IpRequirements + required: true + exCP_naming: + type: org.openecomp.datatypes.Naming + subnetpoolid: + type: string + capabilities: + network.incoming.packets.rate: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: packet/s + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: network.incoming.packets.rate + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Average rate of incoming packets + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: network + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + network.outgoing.bytes: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: network.outgoing.bytes + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Number of outgoing bytes + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Cumulative + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: network + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + network.outgoing.packets.rate: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: packet/s + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: network.outgoing.packets.rate + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Average rate of outgoing packets + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: network + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + network.outpoing.packets: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: packet + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: network.outpoing.packets + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Number of outgoing packets + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Cumulative + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: network + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + network.incoming.bytes.rate: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B/s + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: network.incoming.bytes.rate + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Average rate of incoming bytes + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: network + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + network.incoming.bytes: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: network.incoming.bytes + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Number of incoming bytes + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Cumulative + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: network + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + network.outgoing.bytes.rate: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: B/s + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: network.outgoing.bytes.rate + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Average rate of outgoing bytes + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Gauge + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: network + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED + network.incoming.packets: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + properties: + unit: + type: string + description: Unit of the metric value + required: true + default: packet + status: SUPPORTED + name: + type: string + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + default: network.incoming.packets + status: SUPPORTED + description: + type: string + description: Description of the metric + required: false + default: Number of incoming packets + status: SUPPORTED + type: + type: string + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + default: Cumulative + status: SUPPORTED + category: + type: string + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + default: network + status: SUPPORTED + occurrences: + - 1 + - UNBOUNDED diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.zip b/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.zip new file mode 100644 index 0000000000..8a23aa77c2 Binary files /dev/null and b/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.json b/catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.json new file mode 100644 index 0000000000..96fcb5824a --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.json @@ -0,0 +1,21 @@ +{ + "payloadName": "internalVl.yml", + "contactId": "jh0003", + "name": "InternalVL", + "description": "The AT&T internal (VF-level) Virtual Link", + "resourceIconPath": "network", + "resourceType": "VL", + "categories": [ + { + "name": "Network Connectivity", + "subcategories": [ + { + "name": "Virtual Links" + } + ] + } +], + "tags": [ + "InternalVL" + ] +} diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.yml b/catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.yml new file mode 100644 index 0000000000..a1b78ff9a0 --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.yml @@ -0,0 +1,6 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 + +node_types: + org.openecomp.resource.vl.internalVL: + derived_from: tosca.nodes.network.Network + description: The AT&T internal (VF-level) Virtual Link \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.zip b/catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.zip new file mode 100644 index 0000000000..2a96bc3d9f Binary files /dev/null and b/catalog-be/src/main/resources/import/tosca/heat-types/internalVl/internalVl.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.yml b/catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.yml index e80e2727c7..539e33991f 100644 --- a/catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.yml +++ b/catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.yml @@ -1,14 +1,7 @@ tosca_definitions_version: tosca_simple_yaml_1_0_0 -metadata: - template_name: NeutronNetGlobalTypes - template_version: 1.0.0 -description: Neutron Network TOSCA Global Types -imports: - common_definitions: - file: CommonGlobalTypesServiceTemplate.yaml node_types: org.openecomp.resource.vl.nodes.heat.network.neutron.Net: - derived_from: tosca.nodes.network.Network + derived_from: org.openecomp.resource.vl.nodes.network.Network properties: dhcp_agent_ids: type: list diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.zip b/catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.zip index 0cefe8a184..c8368a5923 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/neutronNet/neutronNet.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.yml b/catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.yml index 898615c6ce..34a74eb4c4 100644 --- a/catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.yml +++ b/catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.yml @@ -1,14 +1,7 @@ tosca_definitions_version: tosca_simple_yaml_1_0_0 -metadata: - template_name: NeutronPortGlobalTypes - template_version: 1.0.0 -description: Neutron Port TOSCA Global Types -imports: - common_definitions: - file: CommonGlobalTypesServiceTemplate.yaml node_types: org.openecomp.resource.cp.nodes.heat.network.neutron.Port: - derived_from: tosca.nodes.network.Port + derived_from: org.openecomp.resource.cp.nodes.network.Port properties: port_security_enabled: type: boolean @@ -134,3 +127,10 @@ node_types: occurrences: - 1 - UNBOUNDED + binding: + type: tosca.capabilities.network.Bindable + valid_source_types: + - org.openecomp.resource.cp.nodes.heat.network.contrailV2.VLANSubInterface + occurrences: + - 0 + - UNBOUNDED \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.zip b/catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.zip index f120afb16e..e33365a8ca 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/neutronPort/neutronPort.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.json b/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.json index 007106b61e..c7f9f0dda0 100644 --- a/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.json +++ b/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.json @@ -2,11 +2,7 @@ "payloadName": "novaServer.yml", "contactId": "jh0003", "name": "NovaServer", - "description": "Represents a real or virtual machine or server. Information specified on the Compute - node will be used to find the machine that fits the given requirements in the cloud - available machines. If no sizing information are specified the cloud provider default - machine will be used. It is strongly recommended to specify the required CPUs and memory - at least.", + "description": "Represents a real or virtual machine or server. Information specified on the Compute node will be used to find the machine that fits the given requirements in the cloud available machines. If no sizing information are specified the cloud provider default machine will be used. It is strongly recommended to specify the required CPUs and memory at least.", "resourceIconPath": "defaulticon", "categories": [ { diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.yml b/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.yml index 0ec79f5229..2271c9cd06 100644 --- a/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.yml +++ b/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.yml @@ -1,75 +1,7 @@ tosca_definitions_version: tosca_simple_yaml_1_0_0 -metadata: - template_name: NovaServerGlobalTypes - template_version: 1.0.0 -description: Nova Server TOSCA Global Types -imports: - common_definitions: - file: CommonGlobalTypesServiceTemplate.yaml -data_types: - org.openecomp.datatypes.heat.novaServer.network.PortExtraProperties: - derived_from: tosca.datatypes.Root - description: Nova server network expand properties for port - properties: - port_security_enabled: - type: boolean - description: Flag to enable/disable port security on the port - required: false - status: SUPPORTED - mac_address: - type: string - description: MAC address to give to this port - required: false - status: SUPPORTED - admin_state_up: - type: boolean - description: The administrative state of this port - required: false - default: true - status: SUPPORTED - qos_policy: - type: string - description: The name or ID of QoS policy to attach to this port - required: false - status: SUPPORTED - allowed_address_pairs: - type: list - description: Additional MAC/IP address pairs allowed to pass through the port - required: false - status: SUPPORTED - entry_schema: - type: org.openecomp.datatypes.heat.network.AddressPair - binding:vnic_type: - type: string - description: The vnic type to be bound on the neutron port - required: false - status: SUPPORTED - constraints: - - valid_values: - - macvtap - - direct - - normal - value_specs: - type: map - description: Extra parameters to include in the request - required: false - default: { - } - status: SUPPORTED - entry_schema: - type: string - org.openecomp.datatypes.heat.novaServer.network.AddressInfo: - derived_from: tosca.datatypes.network.NetworkInfo - description: Network addresses with corresponding port id - properties: - port_id: - type: string - description: Port id - required: false - status: SUPPORTED node_types: org.openecomp.resource.vfc.nodes.heat.nova.Server: - derived_from: tosca.nodes.Compute + derived_from: org.openecomp.resource.vfc.nodes.Compute properties: admin_pass: type: string @@ -246,4 +178,4 @@ node_types: console_urls: type: string description: URLs of servers consoles - status: SUPPORTED \ No newline at end of file + status: SUPPORTED diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.zip b/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.zip index aafefbc6b5..54274e78f5 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/novaServer/novaServer.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.yml b/catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.yml index 29e87e15fc..876b2f1388 100644 --- a/catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.yml +++ b/catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.yml @@ -1,11 +1,4 @@ tosca_definitions_version: tosca_simple_yaml_1_0_0 -metadata: - template_name: NeutronSecurityRulesGlobalTypes - template_version: 1.0.0 -description: Neutron Security Rules TOSCA Global Types -imports: - common_definitions: - file: CommonGlobalTypesServiceTemplate.yaml node_types: org.openecomp.resource.vfc.rules.nodes.heat.network.neutron.SecurityRules: derived_from: tosca.nodes.Root @@ -36,7 +29,7 @@ node_types: - port: capability: tosca.capabilities.Attachment node: org.openecomp.resource.cp.nodes.heat.network.neutron.Port - relationship: corg.openecomp.relationships.AttachesTo + relationship: org.openecomp.relationships.AttachesTo occurrences: - 0 - UNBOUNDED diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.zip b/catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.zip index b1524a2d8f..607fe0c930 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/securityRules/securityRules.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.json b/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.json new file mode 100644 index 0000000000..bc8391893a --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.json @@ -0,0 +1,15 @@ +{ + "payloadName": "subInterface.yml", + "contactId": "jh0003", + "name": "subInterface", + "description": "VLAN sub-Interface is a logical port which must be binded to a port. Regular port may have 1…N VLAN Interfaces.It can connect to its own network (regardless of the network the parent port can connect)", + "resourceIconPath": "network", + "resourceType": "CP", + "categories": [{ + "name": "Generic", + "subcategories": [{ + "name": "Network Elements" + }] + }], + "tags": ["subInterface"] +} \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.yml b/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.yml new file mode 100644 index 0000000000..2356f82995 --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.yml @@ -0,0 +1,4 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.cp.nodes.network.SubInterface: + derived_from: tosca.nodes.network.Port \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.zip b/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.zip new file mode 100644 index 0000000000..54fb2ffb80 Binary files /dev/null and b/catalog-be/src/main/resources/import/tosca/heat-types/subInterface/subInterface.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/vl/vl.zip b/catalog-be/src/main/resources/import/tosca/heat-types/vl/vl.zip index c1889a9803..554c88d925 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/vl/vl.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/vl/vl.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.json b/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.json new file mode 100644 index 0000000000..15293f74ca --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.json @@ -0,0 +1,20 @@ +{ + "payloadName": "volume.yml", + "contactId": "jh0003", + "name": "volume", + "description": "Represents storage that provides the ability to store data as objects (or BLOBs of data) without consideration for the underlying filesystem or devices.", + "resourceIconPath": "objectStorage", + "categories": [ + { + "name": "Generic", + "subcategories": [ + { + "name": "Infrastructure" + } + ] + } +], + "tags": [ + "volume" + ] +} \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.yml b/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.yml new file mode 100644 index 0000000000..9866979c2f --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.yml @@ -0,0 +1,7 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 + +description: Contrail Virtual Network Global Types + +node_types: + org.openecomp.resource.vfc.nodes.volume: + derived_from: tosca.nodes.BlockStorage \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.zip b/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.zip new file mode 100644 index 0000000000..c5847d41df Binary files /dev/null and b/catalog-be/src/main/resources/import/tosca/heat-types/volume/volume.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/normative-types/compute/compute.json b/catalog-be/src/main/resources/import/tosca/normative-types/compute/compute.json index 31bb27be16..5134ae4edd 100644 --- a/catalog-be/src/main/resources/import/tosca/normative-types/compute/compute.json +++ b/catalog-be/src/main/resources/import/tosca/normative-types/compute/compute.json @@ -2,11 +2,7 @@ "payloadName": "compute.yml", "contactId": "jh0003", "name": "Compute", - "description": "Represents a real or virtual machine or server. Information specified on the Compute - node will be used to find the machine that fits the given requirements in the cloud - available machines. If no sizing information are specified the cloud provider default - machine will be used. It is strongly recommended to specify the required CPUs and memory - at least.", + "description": "Represents a real or virtual machine or server. Information specified on the Compute node will be used to find the machine that fits the given requirements in the cloud available machines. If no sizing information are specified the cloud provider default machine will be used. It is strongly recommended to specify the required CPUs and memory at least.", "resourceIconPath": "compute", "categories": [ { diff --git a/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.zip b/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.zip index a6c38ef9de..5ed696e4a9 100644 Binary files a/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.zip and b/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/users/importUsers.yaml b/catalog-be/src/main/resources/import/tosca/users/importUsers.yaml index 368a2b06f3..45e931fec9 100644 --- a/catalog-be/src/main/resources/import/tosca/users/importUsers.yaml +++ b/catalog-be/src/main/resources/import/tosca/users/importUsers.yaml @@ -4,10 +4,10 @@ users: firstName: Jimmy lastName: Hendrix role: ADMIN - email: admin@att.com + email: admin@sdc.com jh0006: firstName: Jimmy lastName: Hendrix role: DESIGNER1 - email: admin@att.com + email: admin@sdc.com diff --git a/catalog-be/src/main/resources/portal.properties b/catalog-be/src/main/resources/portal.properties index 33ae0dac94..c67261f962 100644 --- a/catalog-be/src/main/resources/portal.properties +++ b/catalog-be/src/main/resources/portal.properties @@ -1,18 +1,18 @@ # Portal REST URL, ends "/auxapi" -ecomp_rest_url = https://localhost/ecompportal/auxapi +ecomp_rest_url = https://ecomp.homer.att.com/ecompportal/auxapi # Java implementation of interface portal.api.impl.class = org.openecomp.sdc.be.ecomp.EcompIntImpl # CSP-SSO URL -ecomp_redirect_url = https://localhost/ecomp_portal_ist/ecompportal/process_csp +ecomp_redirect_url = https://www.e-access.att.com/ecomp_portal_ist/ecompportal/process_csp # Cookie set by CSP-SSO csp_cookie_name = attESSec # CSP setting, most use PROD; DEV also recognized csp_gate_keeper_prod_key = PROD # Comma-separated list of UEB server names -ueb_url_list = +ueb_url_list = uebsb91kcdc.it.att.com,uebsb92kcdc.it.att.com,uebsb93kcdc.it.att.com # UEB topic where Portal listens ecomp_portal_inbox_name = ECOMP-PORTAL-INBOX-TEST # UEB key generated while on-boarding diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py index 07eacf8d61..f65aefacf1 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py @@ -21,22 +21,34 @@ import importCommon def importHeatTypes(beHost, bePort, adminUser, fileDir, updateversion): - heatTypes = [ "cinderVolume", -# "contrailVirtualNetwork", + heatTypes = [ "globalNetwork", + "globalPort", + "globalCompute", + "volume", + "cinderVolume", + "contrailVirtualNetwork", "neutronNet", "neutronPort", "novaServer", + "extVl", + "internalVl", + "extCp", "vl", "eline", "abstractSubstitute", -# "contrailNetworkRules", -# "contrailPort", -# "contrailV2NetworkRules", -# "contrailV2VirtualNetwork", - "securityRules" -# "contrailAbstractSubstitute", -# "contrailCompute", -# "contrailV2VirtualMachineInterface" + "Generic_VFC", + "Generic_VF", + "Generic_Service", + "contrailNetworkRules", + "contrailPort", + "contrailV2NetworkRules", + "contrailV2VirtualNetwork", + "securityRules", + "contrailAbstractSubstitute", + "contrailCompute", + "contrailV2VirtualMachineInterface", + "subInterface", + "contrailV2VLANSubInterface" ] responseCodes = [200, 201] diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes1.py b/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes1.py new file mode 100644 index 0000000000..b89a94cbb6 --- /dev/null +++ b/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes1.py @@ -0,0 +1,97 @@ +import pycurl +import sys, getopt +from StringIO import StringIO +import json +import copy +from importCommon import * +from importNormativeTypes import * +import importCommon + +################################################################################################################################################ +# # +# Import all users from a given file # +# # +# activation : # +# python importUsers.py [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # +# # +# shortest activation (be host = localhost, be port = 8080): # +# python importUsers.py [-f | --ifile= ] # +# # +################################################################################################################################################ + +def importHeatTypes1(beHost, bePort, adminUser, fileDir, updateversion): + + heatTypes = ["extCp"] + + responseCodes = [200, 201] + + if(updateversion == 'false'): + responseCodes = [200, 201, 409] + + results = [] + for heatType in heatTypes: + result = createNormativeType(beHost, bePort, adminUser, fileDir, heatType, updateversion) + results.append(result) + if ( result[1] == None or result[1] not in responseCodes) : + print "Failed creating heat type " + heatType + ". " + str(result[1]) + return results + + +def main(argv): + print 'Number of arguments:', len(sys.argv), 'arguments.' + + beHost = 'localhost' + bePort = '8080' + adminUser = 'jh0003' + updateversion = 'true' + + try: + opts, args = getopt.getopt(argv,"i:p:u:v:h:",["ip=","port=","user=","updateversion="]) + except getopt.GetoptError: + usage() + errorAndExit(2, 'Invalid input') + + for opt, arg in opts: + #print opt, arg + if opt == '-h': + usage() + sys.exit(3) + elif opt in ("-i", "--ip"): + beHost = arg + elif opt in ("-p", "--port"): + bePort = arg + elif opt in ("-u", "--user"): + adminUser = arg + elif opt in ("-v", "--updateversion"): + if (arg.lower() == "false" or arg.lower() == "no"): + updateversion = 'false' + + print 'be host =',beHost,', be port =', bePort,', user =', adminUser + + if ( beHost == None ): + usage() + sys.exit(3) + + results = importHeatTypes(beHost, bePort, adminUser, "../../../import/tosca/heat-types/", updateversion) + + print "-----------------------------" + for result in results: + print "{0:20} | {1:6}".format(result[0], result[1]) + print "-----------------------------" + + responseCodes = [200, 201] + + if(updateversion == 'false'): + responseCodes = [200, 201, 409] + + failedNormatives = filter(lambda x: x[1] == None or x[1] not in responseCodes, results) + if (len(failedNormatives) > 0): + errorAndExit(1, None) + else: + errorAndExit(0, None) + + +if __name__ == "__main__": + main(sys.argv[1:]) + + diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeAll1.py b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeAll1.py new file mode 100644 index 0000000000..f564fc5b96 --- /dev/null +++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeAll1.py @@ -0,0 +1,118 @@ +import pycurl +import sys, getopt, os +from StringIO import StringIO +import json +import copy +import time +#from importNormativeElements import createNormativeElement +from importNormativeElements import * +from importNormativeTypes import importNormativeTypes +from importHeatTypes1 import importHeatTypes1 +from importNormativeCapabilities import importNormativeCapabilities +from importCategoryTypes import importCategories +from importNormativeInterfaceLifecycleTypes import importNormativeInterfaceLifecycleType +from importDataTypes import importDataTypes +from importGroupTypes import importGroupTypes +from importPolicyTypes import importPolicyTypes +from importCommon import * +import importCommon + +################################################################################################################################################################################################# +# # +# Import all users from a given file # +# # +# activation : # +# python importNormativeAll.py [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] # +# [-v | --updateversion=] # +# # +# shortest activation (be host = localhost, be port = 8080, user = jh0003): # # # +# python importNormativeAll.py # +# # +################################################################################################################################################################################################# + +def usage(): + print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] [-v | --updateversion=]' + +def handleResults(results, updateversion): + printFrameLine() + for result in results: + printNameAndReturnCode(result[0], result[1]) + printFrameLine() + + responseCodes = [200, 201] + + if(updateversion == 'false'): + responseCodes = [200, 201, 409] + + failedResults = filter(lambda x: x[1] == None or x[1] not in responseCodes, results) + if (len(failedResults) > 0): + errorAndExit(1, None) + +def main(argv): + print 'Number of arguments:', len(sys.argv), 'arguments.' + + beHost = 'localhost' + bePort = '8080' + adminUser = 'jh0003' + debugf = None + updateversion = 'true' + importCommon.debugFlag = False + + try: + opts, args = getopt.getopt(argv,"i:p:u:d:v:h",["ip=","port=","user=","debug=","updateversion="]) + except getopt.GetoptError: + usage() + errorAndExit(2, 'Invalid input') + + for opt, arg in opts: + #print opt, arg + if opt == '-h': + usage() + sys.exit(3) + elif opt in ("-i", "--ip"): + beHost = arg + elif opt in ("-p", "--port"): + bePort = arg + elif opt in ("-u", "--user"): + adminUser = arg + elif opt in ("-d", "--debug"): + print arg + debugf = bool(arg.lower() == "true" or arg.lower() == "yes") + elif opt in ("-v", "--updateversion"): + print arg + if (arg.lower() == "false" or arg.lower() == "no"): + updateversion = 'false' + + print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion + + if (debugf != None): + print 'set debug mode to ' + str(debugf) + importCommon.debugFlag = debugf + + if ( beHost == None ): + usage() + sys.exit(3) + + print sys.argv[0] + pathdir = os.path.dirname(os.path.realpath(sys.argv[0])) + debug("path dir =" + pathdir) + + baseFileLocation = pathdir + "/../../../import/tosca/" + + fileLocation = baseFileLocation + "data-types/" + importDataTypes(beHost, bePort, adminUser, False, fileLocation) + + print 'sleep until data type cache is updated' + time.sleep( 1 ) + + fileLocation = baseFileLocation + "heat-types/" + resultsHeat = importHeatTypes1(beHost, bePort, adminUser, fileLocation, updateversion) + handleResults(resultsHeat, updateversion) + + + + errorAndExit(0, None) + +if __name__ == "__main__": + main(sys.argv[1:]) + diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeNoHeatAndNormativeTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeNoHeatAndNormativeTypes.py new file mode 100644 index 0000000000..64a639c3c8 --- /dev/null +++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeNoHeatAndNormativeTypes.py @@ -0,0 +1,135 @@ +import pycurl +import sys, getopt, os +from StringIO import StringIO +import json +import copy +import time +#from importNormativeElements import createNormativeElement +from importNormativeElements import * +from importNormativeTypes import importNormativeTypes +from importHeatTypes import importHeatTypes +from importNormativeCapabilities import importNormativeCapabilities +from importCategoryTypes import importCategories +from importNormativeInterfaceLifecycleTypes import importNormativeInterfaceLifecycleType +from importDataTypes import importDataTypes +from importGroupTypes import importGroupTypes +from importPolicyTypes import importPolicyTypes +from importCommon import * +import importCommon + +################################################################################################################################################################################################# +# # +# Import all users from a given file # +# # +# activation : # +# python importNormativeAll.py [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] # +# [-v | --updateversion=] # +# # +# shortest activation (be host = localhost, be port = 8080, user = jh0003): # # # +# python importNormativeAll.py # +# # +################################################################################################################################################################################################# + +def usage(): + print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] [-v | --updateversion=]' + +def handleResults(results, updateversion): + printFrameLine() + for result in results: + printNameAndReturnCode(result[0], result[1]) + printFrameLine() + + responseCodes = [200, 201] + + if(updateversion == 'false'): + responseCodes = [200, 201, 409] + + failedResults = filter(lambda x: x[1] == None or x[1] not in responseCodes, results) + if (len(failedResults) > 0): + errorAndExit(1, None) + +def main(argv): + print 'Number of arguments:', len(sys.argv), 'arguments.' + + beHost = 'localhost' + bePort = '8080' + adminUser = 'jh0003' + debugf = None + updateversion = 'true' + importCommon.debugFlag = False + + try: + opts, args = getopt.getopt(argv,"i:p:u:d:v:h",["ip=","port=","user=","debug=","updateversion="]) + except getopt.GetoptError: + usage() + errorAndExit(2, 'Invalid input') + + for opt, arg in opts: + #print opt, arg + if opt == '-h': + usage() + sys.exit(3) + elif opt in ("-i", "--ip"): + beHost = arg + elif opt in ("-p", "--port"): + bePort = arg + elif opt in ("-u", "--user"): + adminUser = arg + elif opt in ("-d", "--debug"): + print arg + debugf = bool(arg.lower() == "true" or arg.lower() == "yes") + elif opt in ("-v", "--updateversion"): + print arg + if (arg.lower() == "false" or arg.lower() == "no"): + updateversion = 'false' + + print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion + + if (debugf != None): + print 'set debug mode to ' + str(debugf) + importCommon.debugFlag = debugf + + if ( beHost == None ): + usage() + sys.exit(3) + + print sys.argv[0] + pathdir = os.path.dirname(os.path.realpath(sys.argv[0])) + debug("path dir =" + pathdir) + + baseFileLocation = pathdir + "/../../../import/tosca/" + + fileLocation = baseFileLocation + "data-types/" + importDataTypes(beHost, bePort, adminUser, False, fileLocation) + + print 'sleep until data type cache is updated' + time.sleep( 70 ) + + fileLocation = baseFileLocation + "capability-types/" + importNormativeCapabilities(beHost, bePort, adminUser, False, fileLocation) + + fileLocation = baseFileLocation + "interface-lifecycle-types/" + importNormativeInterfaceLifecycleType(beHost, bePort, adminUser, False, fileLocation) + + #fileLocation = baseFileLocation + "categories/" + #importCategories(beHost, bePort, adminUser, False, fileLocation) + + #fileLocation = baseFileLocation + "normative-types/" + #results = importNormativeTypes(beHost, bePort, adminUser, fileLocation, updateversion) + #handleResults(results, updateversion) + + #fileLocation = baseFileLocation + "heat-types/" + #resultsHeat = importHeatTypes(beHost, bePort, adminUser, fileLocation, updateversion) + #handleResults(resultsHeat, updateversion) + + fileLocation = baseFileLocation + "group-types/" + importGroupTypes(beHost, bePort, adminUser, False, fileLocation) + + fileLocation = baseFileLocation + "policy-types/" + importPolicyTypes(beHost, bePort, adminUser, False, fileLocation) + + errorAndExit(0, None) + +if __name__ == "__main__": + main(sys.argv[1:]) + diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeTypes.py index 76bae682c0..d47c0b8073 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeTypes.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeTypes.py @@ -41,7 +41,7 @@ def createNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME, update path = fileDir + ELEMENT_NAME + "/" + ELEMENT_NAME + ".zip" debug(path) CURRENT_JSON_FILE=fileDir + ELEMENT_NAME + "/" + ELEMENT_NAME + ".json" - #sed -i 's/"userId": ".*",/"userId": "'${ATT_UID}'",/' ${CURRENT_JSON_FILE} + #sed -i 's/"userId": ".*",/"userId": "'${USER_ID}'",/' ${CURRENT_JSON_FILE} jsonFile = open(CURRENT_JSON_FILE) diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py new file mode 100644 index 0000000000..7c0746fb55 --- /dev/null +++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py @@ -0,0 +1,113 @@ +import pycurl +import sys, getopt +from StringIO import StringIO +import json +import copy +from importCommon import * +from importNormativeTypes import * +import importCommon + +################################################################################################################################################ +# # +# Import all users from a given file # +# # +# activation : # +# python importUsers.py [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # +# # +# shortest activation (be host = localhost, be port = 8080): # +# python importUsers.py [-f | --ifile= ] # +# # +################################################################################################################################################ + +def upgradeHeatTypes1707(beHost, bePort, adminUser, fileDir, updateversion): + + heatTypes = [ "volume", + "cinderVolume", + "extVl", + "extCp", + "Generic_VFC", + "Generic_VF", + "Generic_Service", + "globalPort", + "globalNetwork", + "contrailV2VirtualMachineInterface", + "contrailV2VLANSubInterface", + "contrailPort", + "contrailV2VirtualNetwork", + "contrailVirtualNetwork", + "neutronNet", + "neutronPort", + ] + + responseCodes = [200, 201] + + if(updateversion == 'false'): + responseCodes = [200, 201, 409] + + results = [] + for heatType in heatTypes: + result = createNormativeType(beHost, bePort, adminUser, fileDir, heatType, updateversion) + results.append(result) + if ( result[1] == None or result[1] not in responseCodes) : + print "Failed creating heat type " + heatType + ". " + str(result[1]) + return results + + +def main(argv): + print 'Number of arguments:', len(sys.argv), 'arguments.' + + beHost = 'localhost' + bePort = '8080' + adminUser = 'jh0003' + updateversion = 'true' + + try: + opts, args = getopt.getopt(argv,"i:p:u:v:h:",["ip=","port=","user=","updateversion="]) + except getopt.GetoptError: + usage() + errorAndExit(2, 'Invalid input') + + for opt, arg in opts: + #print opt, arg + if opt == '-h': + usage() + sys.exit(3) + elif opt in ("-i", "--ip"): + beHost = arg + elif opt in ("-p", "--port"): + bePort = arg + elif opt in ("-u", "--user"): + adminUser = arg + elif opt in ("-v", "--updateversion"): + if (arg.lower() == "false" or arg.lower() == "no"): + updateversion = 'false' + + print 'be host =',beHost,', be port =', bePort,', user =', adminUser + + if ( beHost == None ): + usage() + sys.exit(3) + + results = upgradeHeatTypes1707(beHost, bePort, adminUser, "../../../import/tosca/heat-types/", updateversion) + + print "-----------------------------" + for result in results: + print "{0:20} | {1:6}".format(result[0], result[1]) + print "-----------------------------" + + responseCodes = [200, 201] + + if(updateversion == 'false'): + responseCodes = [200, 201, 409] + + failedNormatives = filter(lambda x: x[1] == None or x[1] not in responseCodes, results) + if (len(failedNormatives) > 0): + errorAndExit(1, None) + else: + errorAndExit(0, None) + + +if __name__ == "__main__": + main(sys.argv[1:]) + + diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormative.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormative.py index e6bb620692..488d4d739d 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormative.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormative.py @@ -5,11 +5,9 @@ import json import copy import time from importCategoryTypes import importCategories -from importHeatTypes import importHeatTypes -from importNormativeCapabilities import importNormativeCapabilities +from upgradeHeatTypes1707 import upgradeHeatTypes1707 from importDataTypes import importDataTypes -from importGroupTypes import importGroupTypes -from importPolicyTypes import importPolicyTypes + from importCommon import * import importCommon @@ -46,7 +44,7 @@ def main(argv): bePort = '8080' adminUser = 'jh0003' debugf = None - updateversion = 'false' + updateversion = 'true' importCommon.debugFlag = False try: @@ -94,17 +92,9 @@ def main(argv): print 'sleep until data type cache is updated' time.sleep( 70 ) - fileLocation = baseFileLocation + "capability-types/" - importNormativeCapabilities(beHost, bePort, adminUser, False, fileLocation) - - fileLocation = baseFileLocation + "group-types/" - importGroupTypes(beHost, bePort, adminUser, False, fileLocation) - - fileLocation = baseFileLocation + "policy-types/" - importPolicyTypes(beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "heat-types/" - resultsHeat = importHeatTypes(beHost, bePort, adminUser, fileLocation, updateversion) + resultsHeat = upgradeHeatTypes1707(beHost, bePort, adminUser, fileLocation, updateversion) handleResults(resultsHeat, 'false') errorAndExit(0, None) diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersion.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersion.py index 0f70174173..8f8e0491ae 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersion.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersion.py @@ -83,56 +83,20 @@ def main(argv): ########################################################################## - #---------------------------------for release 1610---------------------- # + #---------------------------------for release 1702---------------------- # ########################################################################## - fileLocation = baseFileLocation + "normative-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "compute", updateversion) - results.append(result) - - fileLocation = baseFileLocation + "normative-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "network", updateversion) - results.append(result) - - fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "abstractSubstitute", updateversion) - results.append(result) - - fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailAbstractSubstitute", updateversion) - results.append(result) - - fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailNetworkRules", updateversion) - results.append(result) - fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "novaServer", updateversion) + result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailV2VirtualMachineInterface", updateversion) results.append(result) - + fileLocation = baseFileLocation + "heat-types/" result = createNormativeType(beHost, bePort, adminUser, fileLocation, "neutronPort", updateversion) results.append(result) - fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailVirtualNetwork", updateversion) - results.append(result) - fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "neutronNet", updateversion) - results.append(result) - fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "vl", updateversion) - results.append(result) - - fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailV2VirtualNetwork", updateversion) - results.append(result) - fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "securityRules", updateversion) - results.append(result) handleResults(results, 'false') diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionProd1702_3537.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionProd1702_3537.py new file mode 100644 index 0000000000..13e5d7d63a --- /dev/null +++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionProd1702_3537.py @@ -0,0 +1,129 @@ +import pycurl +import sys, getopt, os +from StringIO import StringIO +import json +import copy +from importCommon import * +from importNormativeTypes import createNormativeType +import importCommon + +################################################################################################################################################################################################# +# # +# Upgrades the normative types # +# # +# activation : # +# python upgradeNormative.py [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] # +# # +# # +# shortest activation (be host = localhost, be port = 8080, user = jh0003): # # # +# python upgradeNormative.py # +# # +################################################################################################################################################################################################# + +def usage(): + print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=]' + +def handleResults(results, updateversion): + printFrameLine() + for result in results: + printNameAndReturnCode(result[0], result[1]) + printFrameLine() + + failedResults = filter(lambda x: x[1] == None or x[1] not in [200, 201, 409], results) + if (len(failedResults) > 0): + errorAndExit(1, None) + +def main(argv): + print 'Number of arguments:', len(sys.argv), 'arguments.' + + beHost = 'localhost' + bePort = '8080' + adminUser = 'jh0003' + debugf = None + updateversion = 'true' + importCommon.debugFlag = False + + try: + opts, args = getopt.getopt(argv,"i:p:u:d:h",["ip=","port=","user=","debug="]) + except getopt.GetoptError: + usage() + errorAndExit(2, 'Invalid input') + + for opt, arg in opts: + #print opt, arg + if opt == '-h': + usage() + sys.exit(3) + elif opt in ("-i", "--ip"): + beHost = arg + elif opt in ("-p", "--port"): + bePort = arg + elif opt in ("-u", "--user"): + adminUser = arg + elif opt in ("-d", "--debug"): + print arg + debugf = bool(arg.lower() == "true" or arg.lower() == "yes") + + print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf + + if (debugf != None): + print 'set debug mode to ' + str(debugf) + importCommon.debugFlag = debugf + + if ( beHost == None ): + usage() + sys.exit(3) + + print sys.argv[0] + pathdir = os.path.dirname(os.path.realpath(sys.argv[0])) + debug("path dir =" + pathdir) + + baseFileLocation = pathdir + "/../../../import/tosca/" + results = [] + + + ########################################################################## + #---------------------------------for release 1702---------------------- # + ########################################################################## + + + fileLocation = baseFileLocation + "heat-types/" + result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailPort", updateversion) + results.append(result) + + fileLocation = baseFileLocation + "heat-types/" + result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailV2VirtualMachineInterface", updateversion) + results.append(result) + + fileLocation = baseFileLocation + "heat-types/" + result = createNormativeType(beHost, bePort, adminUser, fileLocation, "neutronPort", updateversion) + results.append(result) + + fileLocation = baseFileLocation + "heat-types/" + result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailCompute", updateversion) + results.append(result) + + fileLocation = baseFileLocation + "heat-types/" + result = createNormativeType(beHost, bePort, adminUser, fileLocation, "novaServer", updateversion) + results.append(result) + + fileLocation = baseFileLocation + "heat-types/" + result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailV2VirtualNetwork", updateversion) + results.append(result) + + fileLocation = baseFileLocation + "heat-types/" + result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailVirtualNetwork", updateversion) + results.append(result) + + fileLocation = baseFileLocation + "heat-types/" + result = createNormativeType(beHost, bePort, adminUser, fileLocation, "neutronNet", updateversion) + results.append(result) + + + handleResults(results, 'false') + + errorAndExit(0, None) + +if __name__ == "__main__": + main(sys.argv[1:]) + diff --git a/catalog-be/src/main/resources/swagger/lib/backbone-min.js b/catalog-be/src/main/resources/swagger/lib/backbone-min.js index f082fcffca..a3f544be6d 100644 --- a/catalog-be/src/main/resources/swagger/lib/backbone-min.js +++ b/catalog-be/src/main/resources/swagger/lib/backbone-min.js @@ -1,23 +1,3 @@ -/*- - * ============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========================================================= - */ - // Backbone.js 1.1.2 (function(t,e){if(typeof define==="function"&&define.amd){define(["underscore","jquery","exports"],function(i,r,s){t.Backbone=e(t,s,i,r)})}else if(typeof exports!=="undefined"){var i=require("underscore");e(t,exports,i)}else{t.Backbone=e(t,{},t._,t.jQuery||t.Zepto||t.ender||t.$)}})(this,function(t,e,i,r){var s=t.Backbone;var n=[];var a=n.push;var o=n.slice;var h=n.splice;e.VERSION="1.1.2";e.$=r;e.noConflict=function(){t.Backbone=s;return this};e.emulateHTTP=false;e.emulateJSON=false;var u=e.Events={on:function(t,e,i){if(!c(this,"on",t,[e,i])||!e)return this;this._events||(this._events={});var r=this._events[t]||(this._events[t]=[]);r.push({callback:e,context:i,ctx:i||this});return this},once:function(t,e,r){if(!c(this,"once",t,[e,r])||!e)return this;var s=this;var n=i.once(function(){s.off(t,n);e.apply(this,arguments)});n._callback=e;return this.on(t,n,r)},off:function(t,e,r){var s,n,a,o,h,u,l,f;if(!this._events||!c(this,"off",t,[e,r]))return this;if(!t&&!e&&!r){this._events=void 0;return this}o=t?[t]:i.keys(this._events);for(h=0,u=o.length;h").attr(t);this.setElement(r,false)}else{this.setElement(i.result(this,"el"),false)}}});e.sync=function(t,r,s){var n=T[t];i.defaults(s||(s={}),{emulateHTTP:e.emulateHTTP,emulateJSON:e.emulateJSON});var a={type:n,dataType:"json"};if(!s.url){a.url=i.result(r,"url")||M()}if(s.data==null&&r&&(t==="create"||t==="update"||t==="patch")){a.contentType="application/json";a.data=JSON.stringify(s.attrs||r.toJSON(s))}if(s.emulateJSON){a.contentType="application/x-www-form-urlencoded";a.data=a.data?{model:a.data}:{}}if(s.emulateHTTP&&(n==="PUT"||n==="DELETE"||n==="PATCH")){a.type="POST";if(s.emulateJSON)a.data._method=n;var o=s.beforeSend;s.beforeSend=function(t){t.setRequestHeader("X-HTTP-Method-Override",n);if(o)return o.apply(this,arguments)}}if(a.type!=="GET"&&!s.emulateJSON){a.processData=false}if(a.type==="PATCH"&&k){a.xhr=function(){return new ActiveXObject("Microsoft.XMLHTTP")}}var h=s.xhr=e.ajax(i.extend(a,s));r.trigger("request",r,h,s);return h};var k=typeof window!=="undefined"&&!!window.ActiveXObject&&!(window.XMLHttpRequest&&(new XMLHttpRequest).dispatchEvent);var T={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};e.ajax=function(){return e.$.ajax.apply(e.$,arguments)};var $=e.Router=function(t){t||(t={});if(t.routes)this.routes=t.routes;this._bindRoutes();this.initialize.apply(this,arguments)};var S=/\((.*?)\)/g;var H=/(\(\?)?:\w+/g;var A=/\*\w+/g;var I=/[\-{}\[\]+?.,\\\^$|#\s]/g;i.extend($.prototype,u,{initialize:function(){},route:function(t,r,s){if(!i.isRegExp(t))t=this._routeToRegExp(t);if(i.isFunction(r)){s=r;r=""}if(!s)s=this[r];var n=this;e.history.route(t,function(i){var a=n._extractParameters(t,i);n.execute(s,a);n.trigger.apply(n,["route:"+r].concat(a));n.trigger("route",r,a);e.history.trigger("route",n,r,a)});return this},execute:function(t,e){if(t)t.apply(this,e)},navigate:function(t,i){e.history.navigate(t,i);return this},_bindRoutes:function(){if(!this.routes)return;this.routes=i.result(this,"routes");var t,e=i.keys(this.routes);while((t=e.pop())!=null){this.route(t,this.routes[t])}},_routeToRegExp:function(t){t=t.replace(I,"\\$&").replace(S,"(?:$1)?").replace(H,function(t,e){return e?t:"([^/?]+)"}).replace(A,"([^?]*?)");return new RegExp("^"+t+"(?:\\?([\\s\\S]*))?$")},_extractParameters:function(t,e){var r=t.exec(e).slice(1);return i.map(r,function(t,e){if(e===r.length-1)return t||null;return t?decodeURIComponent(t):null})}});var N=e.History=function(){this.handlers=[];i.bindAll(this,"checkUrl");if(typeof window!=="undefined"){this.location=window.location;this.history=window.history}};var R=/^[#\/]|\s+$/g;var O=/^\/+|\/+$/g;var P=/msie [\w.]+/;var C=/\/$/;var j=/#.*$/;N.started=false;i.extend(N.prototype,u,{interval:50,atRoot:function(){return this.location.pathname.replace(/[^\/]$/,"$&/")===this.root},getHash:function(t){var e=(t||this).location.href.match(/#(.*)$/);return e?e[1]:""},getFragment:function(t,e){if(t==null){if(this._hasPushState||!this._wantsHashChange||e){t=decodeURI(this.location.pathname+this.location.search);var i=this.root.replace(C,"");if(!t.indexOf(i))t=t.slice(i.length)}else{t=this.getHash()}}return t.replace(R,"")},start:function(t){if(N.started)throw new Error("Backbone.history has already been started");N.started=true;this.options=i.extend({root:"/"},this.options,t);this.root=this.options.root;this._wantsHashChange=this.options.hashChange!==false;this._wantsPushState=!!this.options.pushState;this._hasPushState=!!(this.options.pushState&&this.history&&this.history.pushState);var r=this.getFragment();var s=document.documentMode;var n=P.exec(navigator.userAgent.toLowerCase())&&(!s||s<=7);this.root=("/"+this.root+"/").replace(O,"/");if(n&&this._wantsHashChange){var a=e.$('