From 51d50f0ef642e0f996a1c8b8d2ef4838bdfec892 Mon Sep 17 00:00:00 2001 From: Tal Gitelman Date: Sun, 10 Dec 2017 18:55:03 +0200 Subject: Final commit to master merge from Change-Id: Ib464f9a8828437c86fe6def8af238aaf83473507 Issue-ID: SDC-714 Signed-off-by: Tal Gitelman --- .../sdc/be/auditing/api/IAuditingManager.java | 2 - .../auditing/impl/AuditingLogFormatConstants.java | 59 +- .../be/auditing/impl/AuditingLogFormatUtil.java | 2 - .../clean/AsdcComponentsCleanerTask.java | 2 +- .../distribution/engine/CambriaHandler.java | 190 +--- .../distribution/engine/DistributionEngine.java | 1 - .../engine/DistributionEngineClusterHealth.java | 10 +- .../distribution/engine/INotificationData.java | 4 + .../distribution/engine/NotificationDataImpl.java | 20 +- .../ServiceDistributionArtifactsBuilder.java | 16 +- .../engine/VfModuleArtifactPayload.java | 2 - .../be/components/impl/ArtifactResolverImpl.java | 14 +- .../be/components/impl/ArtifactsBusinessLogic.java | 515 +++++++---- .../be/components/impl/AttributeBusinessLogic.java | 1 - .../sdc/be/components/impl/BaseBusinessLogic.java | 55 +- .../be/components/impl/CassandraHealthCheck.java | 2 - .../be/components/impl/CommonImportManager.java | 3 +- .../be/components/impl/ComponentBusinessLogic.java | 137 ++- .../impl/ComponentInstanceBusinessLogic.java | 972 +++++++++++++++------ .../components/impl/CompositionBusinessLogic.java | 2 +- .../be/components/impl/CsarValidationUtils.java | 2 - .../impl/DistributionMonitoringBusinessLogic.java | 9 +- .../be/components/impl/ElementBusinessLogic.java | 42 +- .../sdc/be/components/impl/GroupBusinessLogic.java | 12 +- .../be/components/impl/GroupTypeImportManager.java | 18 +- .../components/impl/HealthCheckBusinessLogic.java | 232 +++-- .../sdc/be/components/impl/ImportUtils.java | 10 +- .../InformationDeployedArtifactsBusinessLogic.java | 25 - .../be/components/impl/InputsBusinessLogic.java | 27 +- .../components/impl/PolicyTypeImportManager.java | 12 +- .../ProductComponentInstanceBusinessLogic.java | 3 - .../be/components/impl/PropertyBusinessLogic.java | 31 +- .../be/components/impl/ResourceBusinessLogic.java | 295 ++++--- .../be/components/impl/ResourceImportManager.java | 54 +- .../be/components/impl/ResponseFormatManager.java | 3 - .../be/components/impl/ServiceBusinessLogic.java | 39 +- .../impl/VFComponentInstanceBusinessLogic.java | 7 - .../impl/generic/GenericTypeBusinessLogic.java | 91 ++ .../lifecycle/CertificationChangeTransition.java | 1 + .../lifecycle/CertificationRequestTransition.java | 32 +- .../components/lifecycle/CheckoutTransition.java | 21 +- .../components/lifecycle/LifeCycleTransition.java | 6 +- .../lifecycle/LifecycleBusinessLogic.java | 16 +- .../lifecycle/LifecycleChangeInfoWithAction.java | 2 +- .../lifecycle/StartCertificationTransition.java | 5 +- .../lifecycle/UndoCheckoutTransition.java | 1 + .../merge/GlobalInputsFilteringBusinessLogic.java | 36 + .../merge/GlobalTypesMergeBusinessLogic.java | 41 + .../be/components/merge/RelationsComparator.java | 95 ++ .../be/components/merge/TopologyComparator.java | 105 +++ .../heat/HeatEnvArtifactsMergeBusinessLogic.java | 64 ++ .../merge/input/ComponentInputsMergeBL.java | 60 ++ .../input/InputsValuesMergingBusinessLogic.java | 180 ++++ .../instance/ComponentInstanceArtifactsMerge.java | 101 +++ .../instance/ComponentInstanceHeatEnvMerge.java | 63 ++ .../ComponentInstanceMergeDataBusinessLogic.java | 90 ++ .../instance/ComponentInstanceMergeInterface.java | 18 + .../ComponentInstancePropsAndInputsMerge.java | 131 +++ .../merge/instance/DataForMergeHolder.java | 114 +++ .../merge/property/ComplexPropertyValueMerger.java | 17 + .../property/ComponentInstanceInputsMergeBL.java | 72 ++ .../ComponentInstancePropertiesMergeBL.java | 73 ++ .../DataDefinitionsValuesMergingBusinessLogic.java | 43 + .../merge/property/MergePropertyData.java | 52 ++ .../PropertyDataValueMergeBusinessLogic.java | 164 ++++ .../property/PropertyInstanceMergeDataBuilder.java | 79 ++ .../merge/property/PropertyValueMerger.java | 148 ++++ .../merge/property/ScalarPropertyValueMerger.java | 20 + .../merge/resource/MergeResourceBLFactory.java | 33 + .../merge/resource/MergeResourceBusinessLogic.java | 10 + .../resource/ResourceDataMergeBusinessLogic.java | 62 ++ .../validation/ComponentValidations.java | 6 +- .../sdc/be/exception/SdcActionException.java | 16 + .../servlet/ArtifactExternalServlet.java | 4 +- .../org/openecomp/sdc/be/impl/ComponentsUtils.java | 35 +- .../sdc/be/impl/DownloadArtifactLogic.java | 1 - .../sdc/be/info/ArtifactDefinitionInfo.java | 1 - .../sdc/be/info/ArtifactTemplateInfo.java | 16 +- .../openecomp/sdc/be/info/GroupDefinitionInfo.java | 1 + .../openecomp/sdc/be/info/MergedArtifactInfo.java | 4 +- .../sdc/be/listen/BEAppContextListener.java | 18 +- .../be/servlets/AdditionalInformationServlet.java | 4 +- .../openecomp/sdc/be/servlets/ArtifactServlet.java | 4 +- .../sdc/be/servlets/AttributeServlet.java | 4 +- .../sdc/be/servlets/BeGenericServlet.java | 2 - .../sdc/be/servlets/BeMonitoringServlet.java | 32 +- .../sdc/be/servlets/ComponentInstanceServlet.java | 221 +++-- .../sdc/be/servlets/ComponentServlet.java | 15 +- .../openecomp/sdc/be/servlets/ConsumerServlet.java | 4 +- .../be/servlets/DistributionServiceServlet.java | 4 +- .../openecomp/sdc/be/servlets/ElementServlet.java | 43 +- .../openecomp/sdc/be/servlets/GroupServlet.java | 7 +- .../openecomp/sdc/be/servlets/InputsServlet.java | 7 +- .../sdc/be/servlets/LifecycleServlet.java | 4 +- .../openecomp/sdc/be/servlets/ProductServlet.java | 6 +- .../openecomp/sdc/be/servlets/PropertyServlet.java | 4 +- .../sdc/be/servlets/RequirementsServlet.java | 1 + .../sdc/be/servlets/ResourceUploadServlet.java | 1 + .../sdc/be/servlets/ResourcesServlet.java | 4 +- .../openecomp/sdc/be/servlets/ServiceServlet.java | 5 +- .../sdc/be/servlets/TypesFetchServlet.java | 10 +- .../sdc/be/servlets/TypesUploadServlet.java | 8 +- .../sdc/be/servlets/UserAdminServlet.java | 4 +- .../be/switchover/detector/SwitchoverDetector.java | 2 +- .../be/tosca/CapabiltyRequirementConvertor.java | 79 +- .../java/org/openecomp/sdc/be/tosca/CsarUtils.java | 79 +- .../openecomp/sdc/be/tosca/PropertyConvertor.java | 6 +- .../openecomp/sdc/be/tosca/ToscaExportHandler.java | 270 ++++-- .../sdc/be/tosca/model/ToscaMetadata.java | 40 +- .../openecomp/sdc/be/user/UserBusinessLogic.java | 1 - .../common/transaction/mngr/RollbackManager.java | 10 +- 111 files changed, 4328 insertions(+), 1531 deletions(-) create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComplexPropertyValueMerger.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBL.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBL.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ScalarPropertyValueMerger.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBLFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/exception/SdcActionException.java (limited to 'catalog-be/src/main/java/org') diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/IAuditingManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/IAuditingManager.java index 36b79c2d9c..b6cd4320f4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/IAuditingManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/IAuditingManager.java @@ -22,8 +22,6 @@ package org.openecomp.sdc.be.auditing.api; import java.util.EnumMap; -import javax.servlet.ServletContext; - import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; public interface IAuditingManager { 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 8ff3fca4f8..ed0fd6de0e 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,14 +20,13 @@ 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 { +class AuditingLogFormatConstants { - static AuditingFieldsKeysEnum[] DISTRIBUTION_REGISTRATION_TEMPLATE_ARRAY = { + private AuditingLogFormatConstants() {} + + static final AuditingFieldsKeysEnum[] DISTRIBUTION_REGISTRATION_TEMPLATE_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, @@ -37,7 +36,7 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME}; - static AuditingFieldsKeysEnum[] DISTRIBUTION_DOWNLOAD_TEMPLATE_ARRAY = { + static final AuditingFieldsKeysEnum[] DISTRIBUTION_DOWNLOAD_TEMPLATE_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, @@ -45,7 +44,7 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] GET_UEB_CLUSTER_ARRAY = { + static final AuditingFieldsKeysEnum[] GET_UEB_CLUSTER_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, @@ -53,7 +52,7 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC }; - static AuditingFieldsKeysEnum[] DISTRIBUTION_DEPLOY_ARRAY = { + static final AuditingFieldsKeysEnum[] DISTRIBUTION_DEPLOY_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, @@ -65,7 +64,7 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] DISTRIBUTION_STATUS_TEMPLATE_ARRAY = { + static final AuditingFieldsKeysEnum[] DISTRIBUTION_STATUS_TEMPLATE_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, @@ -76,7 +75,7 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] DISTRIBUTION_NOTIFY_ARRAY = { + static final AuditingFieldsKeysEnum[] DISTRIBUTION_NOTIFY_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, @@ -90,7 +89,7 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] ADD_REMOVE_TOPIC_KEY_ACL_TEMPLATE_ARRAY = { + static final AuditingFieldsKeysEnum[] ADD_REMOVE_TOPIC_KEY_ACL_TEMPLATE_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, @@ -99,14 +98,14 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_STATUS }; - static AuditingFieldsKeysEnum[] CREATE_TOPIC_TEMPLATE_ARRAY = { + static final AuditingFieldsKeysEnum[] CREATE_TOPIC_TEMPLATE_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, AuditingFieldsKeysEnum.AUDIT_STATUS }; - static AuditingFieldsKeysEnum[] ACTIVATE_DISTRIBUTION_ARRAY ={ + static final AuditingFieldsKeysEnum[] ACTIVATE_DISTRIBUTION_ARRAY ={ AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, @@ -121,7 +120,7 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] CHANGE_DISTRIBUTION_STATUS_ARRAY = { + static final AuditingFieldsKeysEnum[] CHANGE_DISTRIBUTION_STATUS_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, @@ -136,12 +135,12 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT }; - static AuditingFieldsKeysEnum[] CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY = { + static final AuditingFieldsKeysEnum[] CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY = { AuditingFieldsKeysEnum.AUDIT_STATUS, AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY = { + static final AuditingFieldsKeysEnum[] CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, @@ -155,14 +154,14 @@ public interface AuditingLogFormatConstants { }; - static AuditingFieldsKeysEnum[] USER_ACCESS_TEMPLATE_ARRAY = { + static final AuditingFieldsKeysEnum[] USER_ACCESS_TEMPLATE_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_USER_UID, AuditingFieldsKeysEnum.AUDIT_STATUS, AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] USER_TEMPLATE_ARRAY = { + static final AuditingFieldsKeysEnum[] USER_TEMPLATE_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, AuditingFieldsKeysEnum.AUDIT_USER_UID, @@ -170,7 +169,7 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] AUTH_TEMPLATE_ARRAY = { + static final AuditingFieldsKeysEnum[] AUTH_TEMPLATE_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_AUTH_URL, AuditingFieldsKeysEnum.AUDIT_AUTH_USER, @@ -178,7 +177,7 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_AUTH_REALM }; - static AuditingFieldsKeysEnum[] ECOMP_USER_TEMPLATE_ARRAY = { + static final AuditingFieldsKeysEnum[] ECOMP_USER_TEMPLATE_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, AuditingFieldsKeysEnum.AUDIT_ECOMP_USER, @@ -186,7 +185,7 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] CATEGORY_TEMPLATE_ARRAY = { + static final AuditingFieldsKeysEnum[] CATEGORY_TEMPLATE_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME, @@ -197,7 +196,7 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] GET_USERS_LIST_TEMPLATE_ARRAY = { + static final AuditingFieldsKeysEnum[] GET_USERS_LIST_TEMPLATE_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, AuditingFieldsKeysEnum.AUDIT_USER_DETAILS, @@ -205,14 +204,14 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] GET_CATEGORY_HIERARCHY_TEMPLATE_ARRAY = { + static final AuditingFieldsKeysEnum[] GET_CATEGORY_HIERARCHY_TEMPLATE_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, AuditingFieldsKeysEnum.AUDIT_DETAILS, AuditingFieldsKeysEnum.AUDIT_STATUS, AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] USER_ADMIN_TEMPLATE_ARRAY = { + static final AuditingFieldsKeysEnum[] USER_ADMIN_TEMPLATE_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, @@ -220,14 +219,14 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_STATUS, AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] EXTERNAL_GET_ASSET_LIST_TEMPLATE_ARRAY = { + static final AuditingFieldsKeysEnum[] EXTERNAL_GET_ASSET_LIST_TEMPLATE_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, AuditingFieldsKeysEnum.AUDIT_STATUS, AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] EXTERNAL_GET_ASSET_TEMPLATE_ARRAY = { + static final AuditingFieldsKeysEnum[] EXTERNAL_GET_ASSET_TEMPLATE_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, @@ -237,13 +236,13 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_STATUS, AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY = { + static final AuditingFieldsKeysEnum[] EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY = { AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, AuditingFieldsKeysEnum.AUDIT_STATUS, AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARTIFACT_ARRAY = { + static final AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARTIFACT_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, @@ -257,7 +256,7 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARRAY = { + static final AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, @@ -278,7 +277,7 @@ public interface AuditingLogFormatConstants { AuditingFieldsKeysEnum.AUDIT_DESC }; - static AuditingFieldsKeysEnum[] EXTERNAL_LYFECYCLE_API_ARRAY = { + static final AuditingFieldsKeysEnum[] EXTERNAL_LYFECYCLE_API_ARRAY = { AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, 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 b965516df8..8fb5c4116e 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,9 +24,7 @@ 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; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTask.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTask.java index b3b842b9e4..824b70073e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTask.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTask.java @@ -162,7 +162,7 @@ public class AsdcComponentsCleanerTask implements Runnable { public void run() { try { componentsCleanBusinessLogic.cleanComponents(componentsToClean); - } catch (Throwable e) { + } catch (Exception e) { log.error("unexpected error occured", e); String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); 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 e6d15b8d5e..c496715a02 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 @@ -25,14 +25,12 @@ import java.net.MalformedURLException; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Collection; -import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; -import com.att.nsa.cambria.client.*; import org.apache.http.HttpStatus; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -43,189 +41,34 @@ import org.slf4j.LoggerFactory; import com.att.nsa.apiClient.http.HttpException; import com.att.nsa.apiClient.http.HttpObjectNotFoundException; +import com.att.nsa.cambria.client.CambriaBatchingPublisher; +import com.att.nsa.cambria.client.CambriaClient; import com.att.nsa.cambria.client.CambriaClient.CambriaApiException; -import com.att.nsa.cambria.client.CambriaClientBuilders.TopicManagerBuilder; -import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder; +import com.att.nsa.cambria.client.CambriaClientBuilders; import com.att.nsa.cambria.client.CambriaClientBuilders.ConsumerBuilder; import com.att.nsa.cambria.client.CambriaClientBuilders.IdentityManagerBuilder; +import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder; +import com.att.nsa.cambria.client.CambriaClientBuilders.TopicManagerBuilder; +import com.att.nsa.cambria.client.CambriaConsumer; +import com.att.nsa.cambria.client.CambriaIdentityManager; import com.att.nsa.cambria.client.CambriaPublisher.message; +import com.att.nsa.cambria.client.CambriaTopicManager; import com.google.gson.Gson; import fj.data.Either; -import jline.internal.Log; public class CambriaHandler { private static Logger logger = LoggerFactory.getLogger(CambriaHandler.class.getName()); - public static String PARTITION_KEY = "asdc" + "aa"; + private static final String PARTITION_KEY = "asdc" + "aa"; + + private final String SEND_NOTIFICATION = "send notification"; private Gson gson = new Gson(); public static boolean useHttpsWithDmaap = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().isUseHttpsWithDmaap(); - 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 = buildCambriaClient(new TopicManagerBuilder().usingHosts(servers).authenticatedBy(key, secret)); - - String topicName = "ASDC-DISTR-NOTIF-TOPIC-PRODesofer"; - - String clientKey1 = "CGGoorrGPXPx2B1C"; - String clientSecret1 = "OTHk2mcCSbskEtHhDw8h5oUa"; - - CambriaTopicManager createStatusTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(servers).authenticatedBy(key, secret)); - String reportTopic = "ASDC-DISTR-STATUS-TOPIC-PRODESOFER"; - createStatusTopicManager.allowProducer(reportTopic, clientKey1); - - CambriaBatchingPublisher createSimplePublisher = new PublisherBuilder().onTopic(reportTopic).usingHttps(useHttpsWithDmaap).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(useHttpsWithDmaap).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(useHttpsWithDmaap).usingHosts(servers).build(); - createConsumer2.setApiCredentials(clientKey2, "FSlNJbmGWWBvBLJetQMYxPP6"); - - createTopicManager.allowConsumer(topicName, clientKey2); - } - - createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHttps(useHttpsWithDmaap).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 @@ -403,7 +246,8 @@ public class CambriaHandler { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, methodName, operationDesc); BeEcompErrorManager.getInstance().logBeUebSystemError(methodName, operationDesc); break; - + default: + break; } } @@ -661,7 +505,7 @@ public class CambriaHandler { CambriaErrorResponse cambriaErrorResponse = processError(e); - writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "send notification"); + writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, SEND_NOTIFICATION); return cambriaErrorResponse; } finally { @@ -719,7 +563,7 @@ public class CambriaHandler { response = processError(e); - writeErrorToLog(response, e.getMessage(), methodName, "send notification"); + writeErrorToLog(response, e.getMessage(), methodName, SEND_NOTIFICATION); return response; @@ -733,7 +577,7 @@ public class CambriaHandler { response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); - writeErrorToLog(response, "closing publisher returned non sent messages", methodName, "send notification"); + writeErrorToLog(response, "closing publisher returned non sent messages", methodName, SEND_NOTIFICATION); } else { logger.debug("No message left in the queue after closing cambria publisher"); response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); @@ -743,7 +587,7 @@ public class CambriaHandler { response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); - writeErrorToLog(response, "closing publisher returned non sent messages", methodName, "send notification"); + writeErrorToLog(response, "closing publisher returned non sent messages", methodName, SEND_NOTIFICATION); } logger.debug("After closing publisher"); 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 d3d04ea735..bd3d74e323 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 @@ -34,7 +34,6 @@ import javax.annotation.PreDestroy; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; -import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; 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 1b868951c5..85a868f156 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 @@ -39,8 +39,8 @@ import javax.annotation.PreDestroy; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.api.HealthCheckInfo; -import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckComponent; import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; import org.openecomp.sdc.common.config.EcompErrorName; import org.slf4j.Logger; @@ -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(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.UP, null, ClusterStatusDescription.OK.getDescription())), + UNAVAILABLE(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.UNAVAILABLE.getDescription())), + NOT_CONFIGURED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.NOT_CONFIGURED.getDescription())), + DISABLED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.DISABLED.getDescription())); private HealthCheckInfo healthCheckInfo; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java index 48f6c42823..d631724701 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java @@ -64,6 +64,8 @@ public interface INotificationData { /** List of the artifacts */ List getServiceArtifacts(); + String getWorkloadContext(); + void setDistributionID(String distributionId); /** Logical Service Name. */ @@ -99,4 +101,6 @@ public interface INotificationData { /** List of the Resource Instances */ void setServiceArtifacts(List artifacts); + void setWorkloadContext(String workloadContext); + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java index 149499811f..353039647d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java @@ -32,6 +32,7 @@ public class NotificationDataImpl implements INotificationData { private String serviceInvariantUUID; private List resources; private List serviceArtifacts; + private String workloadContext; @Override public String getDistributionID() { @@ -76,12 +77,25 @@ public class NotificationDataImpl implements INotificationData { public void setServiceDescription(String serviceDescription) { this.serviceDescription = serviceDescription; } + @Override + public String getWorkloadContext() { return workloadContext; } + + @Override + public void setWorkloadContext(String workloadContext) { this.workloadContext = workloadContext; } - @Override public String toString() { - return "NotificationDataImpl [distributionID=" + distributionID + ", serviceName=" + serviceName + ", serviceVersion=" + serviceVersion + ", serviceUUID=" + serviceUUID + ", serviceDescription=" + serviceDescription - + ", serviceInvariantUUID=" + serviceInvariantUUID + ", resources=" + resources + ", serviceArtifacts=" + serviceArtifacts + "]"; + return "NotificationDataImpl{" + + "distributionID='" + distributionID + '\'' + + ", serviceName='" + serviceName + '\'' + + ", serviceVersion='" + serviceVersion + '\'' + + ", serviceUUID='" + serviceUUID + '\'' + + ", serviceDescription='" + serviceDescription + '\'' + + ", serviceInvariantUUID='" + serviceInvariantUUID + '\'' + + ", resources=" + resources + + ", serviceArtifacts=" + serviceArtifacts + + ", workloadContext='" + workloadContext + '\'' + + '}'; } @Override 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 90120288bc..0330a756c6 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 @@ -101,7 +101,10 @@ public class ServiceDistributionArtifactsBuilder { notificationData.setServiceUUID(service.getUUID()); notificationData.setServiceDescription(service.getDescription()); notificationData.setServiceInvariantUUID(service.getInvariantUUID()); - + String workloadContext= ConfigurationManager.getConfigurationManager().getConfiguration().getWorkloadContext(); + if(workloadContext!=null){ + notificationData.setWorkloadContext(workloadContext); + } logger.debug("Before returning notification data object {}", notificationData); return notificationData; @@ -198,7 +201,7 @@ public class ServiceDistributionArtifactsBuilder { } JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(resourceInstance, resoucreType, - artifacts); + rebuildArtifactswith120TimeoutInsteadOf60(artifacts)/*TODO used to send artifacts, the function is a fix to the short timeout bug in distribution*/); jsonContainer.setResourceInvariantUUID(resourceInvariantUUID); jsonContainer.setCategory(resourceCategory); jsonContainer.setSubcategory(resourceSubcategory); @@ -208,6 +211,15 @@ public class ServiceDistributionArtifactsBuilder { return ret; } + private List rebuildArtifactswith120TimeoutInsteadOf60(List artifacts) { + for(ArtifactInfoImpl artifact : artifacts){ + if(artifact.getArtifactTimeout().equals(60)){ + artifact.setArtifactTimeout(120); + } + } + return artifacts; + } + private List getArtifactsWithPayload(ComponentInstance resourceInstance) { List ret = new ArrayList(); 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 2bcaa4f54a..d706e40f5c 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,13 +20,11 @@ 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; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java index 141ed95575..1c5a35453b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java @@ -20,13 +20,6 @@ package org.openecomp.sdc.be.components.impl; -import org.openecomp.sdc.be.components.ArtifactsResolver; -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.Service; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -34,6 +27,13 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import org.openecomp.sdc.be.components.ArtifactsResolver; +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.Service; + @org.springframework.stereotype.Component("artifact-resolver") public class ArtifactResolverImpl implements ArtifactsResolver { 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 b7344e9911..bd7f61444d 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 @@ -63,6 +63,7 @@ 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; +import org.openecomp.sdc.be.info.ArtifactTemplateInfo; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.ArtifactType; import org.openecomp.sdc.be.model.Component; @@ -111,12 +112,19 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.xml.sax.*; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXNotRecognizedException; +import org.xml.sax.SAXNotSupportedException; +import org.xml.sax.XMLReader; import org.yaml.snakeyaml.Yaml; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import com.sun.org.apache.xerces.internal.parsers.SAXParser; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; import fj.data.Either; @@ -142,7 +150,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { // private static final Integer NON_HEAT_TIMEOUT = 0; private static Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class.getName()); private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - + private static XMLReader parser; @javax.annotation.Resource private IInterfaceLifecycleOperation interfaceLifecycleOperation; @javax.annotation.Resource @@ -198,7 +206,30 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } + + //SAX XML Parser initialization + static { + SAXParserFactory spf = SAXParserFactory.newInstance(); + SAXParser newSAXParser = null; + + try { + newSAXParser = spf.newSAXParser(); + parser = newSAXParser.getXMLReader(); + } catch (ParserConfigurationException | SAXException e1) { + log.debug("SAX XML Parser could not been initialized", e1); + } + + try { + parser.setFeature("http://apache.org/xml/features/validation/schema", false); + } catch (SAXNotRecognizedException e) { + log.debug("SAX Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e); + + } catch (SAXNotSupportedException e) { + log.debug("SAX Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e); + } + } + public class ArtifactOperationInfo { private ArtifactOperationEnum artifactOperationEnum; @@ -438,8 +469,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } return result; - case Create: - return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction); + case Create: + return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction); + case Link: + return handleLink(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction); } return null; } @@ -603,16 +636,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - /** - * - * @param componentId - * @param artifactId - * @param userId - * @param componentType - * @param parentId - * @return - */ - public Either, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) { if (artifactGenerationRequired(component, csarArtifact)) { Either generated = csarUtils.createCsar(component, false, false); @@ -839,6 +862,30 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } + private Either, ResponseFormat> handleLink(String componentId, 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) { + + if (shouldLock) { + Either lockComponent = lockComponent(parent, "Upload Artifact - lock "); + if (lockComponent.isRight()) { + handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right().value(), componentType, null); + return Either.right(lockComponent.right().value()); + } + } + Either, ResponseFormat> resultOp = null; + + try { + resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction); + return resultOp; + } finally { + if (shouldLock) { + unlockComponent(resultOp, parent, inTransaction); + } + + } + + } + 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) { @@ -920,9 +967,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) { - if (auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) { + if (auditingActionEnum != null && auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) { return; - } + } EnumMap auditingFields = createArtifactAuditingFields(artifactDefinition, prevArtifactUuid, currentArtifactUuid); @@ -1019,9 +1066,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5)); } } else { - if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) { - log.debug("Missing md5 header during artifact create"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5)); + if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { + if (payload!=null && payload.length != 0) { + log.debug("Missing md5 header during artifact create"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5)); + } } // Update metadata if (payload != null && payload.length != 0) { @@ -1061,7 +1110,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { // This is a patch to block possibility of updating service api fields // through other artifacts flow - if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) { + if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL)); } else { checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL)); @@ -1073,7 +1122,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } // artifactGroupType is not allowed to be updated - if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) { + if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { Either validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo); if (validateGroupType.isRight()) { return Either.right(validateGroupType.right().value()); @@ -1083,7 +1132,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { NodeTypeEnum parentType = convertParentType(componentType); // TODO TEMP !!! - boolean isCreate = operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create; + boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()); if (isDeploymentArtifact(artifactInfo)) { Either deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType); @@ -1159,11 +1208,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (StringUtils.isNotEmpty(artifactId)) { foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId); } - if (foundArtifact != null && operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) { + if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { log.debug("Artifact {} already exist", artifactId); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel())); } - if (foundArtifact == null && operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) { + if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "")); } @@ -1272,7 +1321,22 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { resultOp = Either.right(responseFormat); } } + boolean isNeedToDeleteArtifactFromDB = true; if (resultOp == null) { + + if(componentType == ComponentTypeEnum.RESOURCE_INSTANCE){ + String instanceId = parentId; + Either isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId); + + if (isOnlyResourceInstanceArtifact.isRight()) { + log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right().value(), foundArtifact.getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value(); + } + 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); @@ -1285,13 +1349,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } 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(isNeedToDeleteArtifactFromDB){ + 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) { @@ -1340,6 +1407,40 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } + private Either isArtifactOnlyResourceInstanceArtifact( ArtifactDefinition foundArtifact, Component parent, String instanceId) { + Either result = Either.left(true); + ComponentInstance foundInstance = null; + Optional componentInstanceOpt = parent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); + if (!componentInstanceOpt.isPresent()) { + result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER); + } else { + foundInstance = componentInstanceOpt.get(); + String componentUid = foundInstance.getComponentUid(); + Either getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId()); + if (getContainerRes.isRight()) { + log.debug("Failed to fetch the container component {}. ", componentUid); + result = Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value())); + } + Component origComponent = getContainerRes.left().value(); + Map deploymentArtifacts = origComponent.getDeploymentArtifacts(); + if( deploymentArtifacts!= null && !deploymentArtifacts.isEmpty()){ + Optional op = deploymentArtifacts.keySet().stream().filter(a -> a.equals(foundArtifact.getArtifactLabel())).findAny(); + if(op.isPresent()){ + return Either.left(false); + } + } + Map artifacts = origComponent.getArtifacts(); + if( artifacts!= null && !artifacts.isEmpty()){ + Optional op = artifacts.keySet().stream().filter(a -> a.equals(foundArtifact.getArtifactLabel())).findAny(); + if(op.isPresent()){ + return Either.left(false); + } + } + + } + return result; + } + private List getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List groups) { List updatedGroups = new ArrayList<>(); boolean isUpdated = false; @@ -1393,7 +1494,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (isMandatory) { log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId); resetMandatoryArtifactFields(foundArtifact); - result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true); + result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true); } 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); @@ -1540,13 +1641,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private Either fetchCurrentArtifact(String parentId, ArtifactOperationInfo operation, String artifactId) { Either artifactById = artifactToscaOperation.getArtifactById(parentId, artifactId); - if (!(operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) && artifactById.isRight()) { + if (!(ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) && artifactById.isRight()) { // in case of update artifact must be 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.getArtifactOperationEnum() == ArtifactOperationEnum.Create && artifactById.isLeft()) { + if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && artifactById.isLeft()) { log.debug("Artifact {} already exist", artifactId); return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); } @@ -1567,7 +1668,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { log.debug("missing artifact logical name for component {}", componentId); return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL)); } - if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && !artifactInfo.getMandatory()) { + if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) { if (operationName != null) { if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) { @@ -1647,6 +1748,52 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { // *************************************************************** + private Either, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user, + ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) { + 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(); + } + boolean isLeft = false; + String artifactUniqueId = null; + StorageOperationStatus error = null; + // information/deployment/api aritfacts + log.trace("Try to create entry on graph"); + NodeTypeEnum nodeType = convertParentType(componentTypeEnum); + Either result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId); + + isLeft = result.isLeft(); + if (isLeft) { + artifactUniqueId = result.left().value().getUniqueId(); + 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; + } + + } if (isLeft) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); + return resultOp; + } 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, instanceName); + resultOp = Either.right(responseFormat); + return resultOp; + + } + } + private Either, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user, ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) { @@ -2039,27 +2186,20 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - @SuppressWarnings("restriction") public boolean isValidXml(byte[] xmlToParse) { - XMLReader parser = new SAXParser(); - try { - parser.setFeature("http://apache.org/xml/features/validation/schema", false); - } catch (SAXNotRecognizedException e) { - e.printStackTrace(); - log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e); - - } catch (SAXNotSupportedException e) { - e.printStackTrace(); - log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e); - + if(parser == null) { + log.debug("SAX XML Parser have not been initialized"); + return false; } 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; } @@ -2898,22 +3038,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } - public StorageOperationStatus deleteAllComponentArtifactsIfNotOnGraph(List artifacts) { - - if (artifacts != null && !artifacts.isEmpty()) { - for (ArtifactDefinition artifactDefinition : artifacts) { - String esId = artifactDefinition.getEsId(); - if (esId != null && !esId.isEmpty()) { - StorageOperationStatus deleteIfNotOnGraph = deleteIfNotOnGraph(artifactDefinition.getUniqueId(), esId, false); - if (!deleteIfNotOnGraph.equals(StorageOperationStatus.OK)) { - return deleteIfNotOnGraph; - } - } - } - } - return StorageOperationStatus.OK; - } - private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) { Operation op = new Operation(); long time = System.currentTimeMillis(); @@ -2933,31 +3057,6 @@ 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 = 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; - } - // download by MSO public Either downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) { @@ -3512,35 +3611,46 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String payload = generateHeatEnvPayload(artifactDefinition); String prevUUID = artifactDefinition.getArtifactUUID(); ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition); - Either generateResult = generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId); - if (generateResult.isLeft()) { - ArtifactDefinition updatedArtDef = generateResult.left().value(); - if (!prevUUID.equals(updatedArtDef.getArtifactUUID())) { - List componentInstances = component.getComponentInstances(); - if (componentInstances != null) { - Optional findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst(); - if (findFirst.isPresent()) { - ComponentInstance relevantInst = findFirst.get(); - List updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst.getGroupInstances()); - - if (CollectionUtils.isNotEmpty(updatedGroupInstances)) { - updatedGroupInstances.forEach(gi -> { - gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId()); - gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID()); - }); - Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances); - if (status.isRight()) { - log.debug("Failed to update groups of the component {}. ", component.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), clonedBeforeGenerate.getArtifactDisplayName()); - return Either.right(responseFormat); - } - } - } - } - } - } + return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId) + .left() + .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); + } - return generateResult; + public Either forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, + boolean shouldLock, String instanceId) { + String payload = generateHeatEnvPayload(artifactDefinition); + String prevUUID = artifactDefinition.getArtifactUUID(); + ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition); + return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId) + .left() + .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); + } + + private Either updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) { + if (!prevUUID.equals(updatedArtDef.getArtifactUUID())) { + List componentInstances = component.getComponentInstances(); + if (componentInstances != null) { + Optional findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst(); + if (findFirst.isPresent()) { + ComponentInstance relevantInst = findFirst.get(); + List updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst.getGroupInstances()); + + if (CollectionUtils.isNotEmpty(updatedGroupInstances)) { + updatedGroupInstances.forEach(gi -> { + gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId()); + gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID()); + }); + Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances); + if (status.isRight()) { + log.debug("Failed to update groups of the component {}. ", component.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), clonedBeforeGenerate.getArtifactDisplayName()); + return Either.right(responseFormat); + } + } + } + } + } + return Either.left(updatedArtDef); } private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) { @@ -3628,6 +3738,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } + public Either forceGenerateAndSaveHeatEnvArtifact(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, System::currentTimeMillis, + () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId); + + } + 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) { @@ -3743,6 +3860,57 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(artifactDefinition); } + + public Map buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List updatedRequiredArtifacts) { + return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef.getArtifactLabel(), artifactDef.getArtifactDisplayName(), + artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters()); + + } + + public Map buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent, + List updatedRequiredArtifacts, List heatParameters) { + + Map json = new HashMap(); + if (artifactId != null && !artifactId.isEmpty()) + json.put(Constants.ARTIFACT_ID, artifactId); + + json.put(Constants.ARTIFACT_NAME, artifactName); + json.put(Constants.ARTIFACT_TYPE, artifactType); + json.put(Constants.ARTIFACT_DESCRIPTION, description); + + if (artifactContent != null) { + String encodedPayload = new String(artifactContent); + + // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent); + // if (!isEncoded) { + log.debug("payload is encoded. perform decode"); + encodedPayload = Base64.encodeBase64String(artifactContent); + 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, 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())); + json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>() + : heatParameters); + return json; + } + + public Either, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) { + + String jsonStr = gson.toJson(json); + ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo; + String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId(); + Either, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId, + artifactDefinitionFromJson, null, jsonStr, null, null, null, user, containerComponent, false, false, true); + if (uploadArtifactToService.isRight()) + return Either.right(uploadArtifactToService.right().value()); + + return Either.left(uploadArtifactToService.left().value()); + } + 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, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { convertParentType(componentType); @@ -3789,7 +3957,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } Either, ResponseFormat> resultOp = null; try { - resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currArtifact, origMd5, inTransaction); + resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5); return resultOp; } finally { @@ -3812,7 +3980,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } private Either, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent, - ComponentTypeEnum componentType, ArtifactDefinition currArtifact1, String origMd5, boolean inTransaction) { + ComponentTypeEnum componentType, String origMd5) { Either, ResponseFormat> resultOp = null; Either insideEither = null; @@ -3859,22 +4027,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) { - String paramName; // fill reduced heat env parameters List for updating - for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { - paramName = heatEnvParam.getName(); - for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { - if (paramName.equalsIgnoreCase(currHeatParam.getName())) { - String updatedParamValue = heatEnvParam.getCurrentValue(); - if (updatedParamValue != null && updatedParamValue.equals("")) { // reset - currHeatParam.setCurrentValue(heatEnvParam.getDefaultValue()); - } else if (updatedParamValue != null) { - currHeatParam.setCurrentValue(updatedParamValue); - } - } - } - } - //currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis()); + replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams); + currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis()); currArtifact.setListHeatParameters(currentHeatEnvParams); Either updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId); @@ -3899,8 +4054,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - // } - insideEither = Either.left(currArtifact); resultOp = Either.left(insideEither); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); @@ -3908,6 +4061,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return resultOp; } + private void replaceCurrHeatValueWithUpdatedValue(List currentHeatEnvParams, List updatedHeatEnvParams) { + for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { + String paramName = heatEnvParam.getName(); + for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { + if (paramName.equalsIgnoreCase(currHeatParam.getName())) { + String updatedParamValue = heatEnvParam.getCurrentValue(); + currHeatParam.setCurrentValue(updatedParamValue); + } + } + } + } + private Either, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent, ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, String origMd5, boolean needToUpdateGroup) { @@ -3929,9 +4094,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } ESArtifactData esArtifactData = artifactfromES.left().value(); - byte[] data = esArtifactData.getDataAsArray(); - - ArtifactDefinition updatedHeatArt = currHeatArtifact; List updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters(); @@ -4149,7 +4311,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * * @param componentType * @param componentUuid - * @param resourceName + * @param resourceInstanceName * @param artifactUUID * @param auditAdditionalParam * @return @@ -4574,15 +4736,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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) { + public Either createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component, + Map existingEnvVersions) { Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); if (deploymentResourceArtifacts == null) { log.debug("no deployment artifacts are configured for generated artifacts"); @@ -4594,64 +4750,55 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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); + String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase(); + Either createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, 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.setGeneratedFromId(heatArtifact.getUniqueId()); artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis()); artifactHeatEnv.setTimeout(0); - buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData); + buildHeatEnvFileName(heatArtifact, 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; + ArtifactDefinition heatEnvPlaceholder; // 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); + Either addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, 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(); + heatEnvPlaceholder = 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); + heatEnvPlaceholder = artifactHeatEnv; + artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion()); + setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder); } - // audit - EnumMap artifactAuditingFields = createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.getUniqueId()); + EnumMap artifactAuditingFields = createArtifactAuditingFields(heatEnvPlaceholder, "", heatEnvPlaceholder.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); + return Either.left(heatEnvPlaceholder); + } + + private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) { + if (artifact.getListHeatParameters() == null) { + return; + } + List heatEnvParameters = new ArrayList<>(); + for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) { + HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter); + heatEnvParameter.setDefaultValue(parameter.getCurrentValue()); + heatEnvParameter.setCurrentValue(null); + heatEnvParameters.add(heatEnvParameter); + } + artifactDefinition.setListHeatParameters(heatEnvParameters); } private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map placeHolderData) { @@ -4707,7 +4854,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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) { + if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { vfcsNewCreatedArtifacts.addAll(uploadedArtifacts); } break; 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 5b8a10a03e..2e14028338 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,6 @@ 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.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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 5a4961b24f..14c451a3b0 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,8 +20,12 @@ package org.openecomp.sdc.be.components.impl; -import com.google.gson.JsonElement; -import fj.data.Either; +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; @@ -36,7 +40,16 @@ 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.*; +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.IPropertyInputCommon; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.User; 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.ToscaOperationFacade; @@ -65,11 +78,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.function.Function; +import com.google.gson.JsonElement; + +import fj.data.Either; public abstract class BaseBusinessLogic { @@ -287,34 +298,6 @@ 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); -// 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)); if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java index 237ec6d5fe..1f5770856b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java @@ -1,8 +1,6 @@ package org.openecomp.sdc.be.components.impl; import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; 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 f97b4cf3f1..31c665686e 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 @@ -31,8 +31,6 @@ import java.util.stream.Collectors; import javax.annotation.Resource; -import jersey.repackaged.com.google.common.base.Function; - import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -52,6 +50,7 @@ import org.springframework.stereotype.Component; import org.yaml.snakeyaml.Yaml; import fj.data.Either; +import jersey.repackaged.com.google.common.base.Function; @Component("commonImportManager") public class CommonImportManager { 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 108e03c274..40e67aa876 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 @@ -31,14 +31,21 @@ import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; 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.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum; import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.*; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +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.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.CapReqDef; @@ -82,6 +89,12 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { @Autowired protected ComponentCache componentCache; + @Autowired + private GenericTypeBusinessLogic genericTypeBusinessLogic; + + public void setGenericTypeBusinessLogic(GenericTypeBusinessLogic genericTypeBusinessLogic) { + this.genericTypeBusinessLogic = genericTypeBusinessLogic; + } private static Logger log = LoggerFactory.getLogger(ComponentBusinessLogic.class.getName()); @@ -116,7 +129,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", auditAction, component.getComponentType()); return Either.right(responseFormat); } - user = userResult.left().value(); return userResult; } @@ -502,17 +514,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return Either.left(true); } - /*** - * Fetches Component From the DB - * - * @param componentId - * @param componentTypeEnum - * @return - */ - public Either getComponent(String componentId, ComponentTypeEnum componentTypeEnum) { - return toscaOperationFacade.getToscaElement(componentId); - } - public Either getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) { Either resp = validateUserExists(userId, "create Component Instance", false); @@ -545,7 +546,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { List componentsUidToFetch = new ArrayList<>(); componentsUidToFetch.addAll(componentUids); - if (componentsUidToFetch.size() > 0) { + if (!componentsUidToFetch.isEmpty()) { 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); @@ -617,7 +618,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { public void setToscaArtifactsPlaceHolders(Component component, User user) { Map artifactMap = component.getToscaArtifacts(); if (artifactMap == null) { - artifactMap = new HashMap(); + artifactMap = new HashMap<>(); } String componentUniqueId = component.getUniqueId(); String componentSystemName = component.getSystemName(); @@ -628,7 +629,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { for (Entry artifactInfoMap : toscaArtifacts.entrySet()) { Map artifactInfo = (Map) artifactInfoMap.getValue(); ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(componentUniqueId, artifactInfoMap.getKey(), artifactInfo, user, ArtifactGroupTypeEnum.TOSCA); - artifactDefinition.setArtifactName(componentType + "-" + componentSystemName + artifactInfo.get("artifactName")); + artifactDefinition.setArtifactName(ValidationUtils.normalizeFileName(componentType + "-" + componentSystemName + artifactInfo.get("artifactName"))); artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); } } @@ -695,7 +696,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { List components = latestVersionEither.left().value(); - Component component = components.stream().filter(c -> c.isHighestVersion()).findFirst().orElse(null); + Component component = components.stream().filter(Component::isHighestVersion).findFirst().orElse(null); if(component == null){ component = components.stream().filter(c -> c.getLifecycleState() == LifecycleStateEnum.CERTIFIED).findFirst().orElse(null); } @@ -785,7 +786,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { protected Either, ResponseFormat> deleteMarkedComponents(ComponentTypeEnum componentType) { -// List deletedComponents = new ArrayList(); log.trace("start deleteMarkedComponents"); Either, StorageOperationStatus> deleteMarkedElements = toscaOperationFacade.deleteMarkedElements(componentType); @@ -794,30 +794,12 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType)); return Either.right(responseFormat); } -// 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(deleteMarkedElements.left().value()); } - public Either, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType, boolean inTransacton) { - List artifacts = new ArrayList(); + public Either, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType) { + List artifacts = new ArrayList<>(); Either, StorageOperationStatus> artifactsResponse = artifactToscaOperation.getArtifacts(parentId); if (artifactsResponse.isRight()) { if (!artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) { @@ -827,16 +809,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { } 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); } @@ -873,50 +845,39 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { 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()); + protected void generateAndAddInputsFromGenericTypeProperties(T component, Resource genericType) { + List genericAndComponentInputs = new ArrayList<>(); + List genericInputs = genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericType); + genericAndComponentInputs.addAll(genericInputs); + if (null != component.getInputs()){ + List nonGenericInputsFromComponent = getAllNonGenericInputsFromComponent(genericInputs, component.getInputs()); + genericAndComponentInputs.addAll(nonGenericInputsFromComponent); + } + component.setInputs(genericAndComponentInputs); } - - private InputDefinition setInputDefinitionFromProp(PropertyDefinition prop, String genericUniqueId){ - InputDefinition input = new InputDefinition(prop); - input.setOwnerId(genericUniqueId); - return input; + + private List getAllNonGenericInputsFromComponent(List genericInputs, List componentInputs) { + if (genericInputs == null) { + return componentInputs; + } + + Map inputByNameMap = MapUtil.toMap(genericInputs, InputDefinition::getName); + List componentNonGenericInputs = new ArrayList<>(); + componentInputs.stream().forEach(input -> { + if (!inputByNameMap.containsKey(input.getName())) { + componentNonGenericInputs.add(input); + } + }); + return componentNonGenericInputs; } protected Either fetchAndSetDerivedFromGenericType(T component){ - String genericTypeToscaName = null; - if(component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).getResourceType() == ResourceTypeEnum.CVFC && CollectionUtils.isNotEmpty(((Resource)component).getDerivedFrom())){ - genericTypeToscaName = ((Resource)component).getDerivedFrom().get(0); - } else { - genericTypeToscaName = component.fetchGenericTypeToscaNameFromConfig(); - } - log.debug("Fetching generic tosca name {}", genericTypeToscaName); - if(null == genericTypeToscaName) { - log.debug("Failed to fetch certified node type by tosca resource name {}", genericTypeToscaName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + Either genericTypeEither = this.genericTypeBusinessLogic.fetchDerivedFromGenericType(component); + if(genericTypeEither.isRight()){ + log.debug("Failed to fetch latest generic type for component {} of type", component.getName(), component.assetType()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType())); } - - Either findLatestGeneric = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(genericTypeToscaName); - if(findLatestGeneric.isRight()){ - log.debug("Failed to fetch certified node type by tosca resource name {}", genericTypeToscaName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType(), genericTypeToscaName)); - } - - Resource genericTypeResource = findLatestGeneric.left().value(); + Resource genericTypeResource = genericTypeEither.left().value(); component.setDerivedFromGenericInfo(genericTypeResource); return Either.left(genericTypeResource); } @@ -1119,7 +1080,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return shouldUpgradeNodeType(componentToCheckOut, latestGeneric); } List genericTypeProps = latestGeneric.getProperties(); - List genericTypeInputs = null == genericTypeProps? null : convertGenericTypePropertiesToInputsDefintion(genericTypeProps, latestGeneric.getUniqueId()); + List genericTypeInputs = null == genericTypeProps? null : genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericTypeProps, latestGeneric.getUniqueId()); List currentList = new ArrayList<>(); // nullify existing ownerId from existing list and merge into updated list if (null != componentToCheckOut.getInputs()) { 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 66d8668fea..b86b28a6c5 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,6 +21,8 @@ package org.openecomp.sdc.be.components.impl; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -32,23 +34,28 @@ 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.components.merge.instance.ComponentInstanceMergeDataBusinessLogic; +import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder; 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.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; 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.CapabilityDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceInput; @@ -59,7 +66,10 @@ import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames; +import org.openecomp.sdc.be.model.RelationshipInfo; 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.User; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; @@ -95,7 +105,10 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { private ArtifactsBusinessLogic artifactBusinessLogic; @Autowired private ApplicationDataTypeCache dataTypeCache; - + + @Autowired + private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL; + public static final String VF_MODULE = "org.openecomp.groups.VfModule"; public ComponentInstanceBusinessLogic() { @@ -112,8 +125,8 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { User user = null; org.openecomp.sdc.be.model.Component containerComponent = null; ComponentTypeEnum containerComponentType; - - try{ + + try { Either resp = validateUserExists(userId, "create Component Instance", inTransaction); if (resp.isRight()) { return Either.right(resp.right().value()); @@ -125,37 +138,56 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (validateValidJson.isRight()) { return Either.right(validateValidJson.right().value()); } - + Either validateComponentType = validateComponentType(containerComponentParam); if (validateComponentType.isRight()) { return Either.right(validateComponentType.right().value()); } else { containerComponentType = validateComponentType.left().value(); } - + Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); if (validateComponentExists.isRight()) { return Either.right(validateComponentExists.right().value()); } else { containerComponent = validateComponentExists.left().value(); } - + if (ModelConverter.isAtomicComponent(containerComponent)) { log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType())); } - + 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()); + OriginTypeEnum originType = resourceInstance.getOriginType(); + if (originType == OriginTypeEnum.ServiceProxy) { + Either serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy"); + if (serviceProxyOrigin.isRight()) { + log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()))); + } + origComponent = serviceProxyOrigin.left().value(); + + StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent); + if (fillProxyRes != StorageOperationStatus.OK) { + log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes))); + + } + } else { - origComponent = getOriginComponentRes.left().value(); + Either getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance); + + if (getOriginComponentRes.isRight()) { + return Either.right(getOriginComponentRes.right().value()); + } else { + origComponent = getOriginComponentRes.left().value(); + } } } if (needLock) { @@ -174,6 +206,43 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } + private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) { + resourceInstance.setIsProxy(true); + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreCapabilities(false); + filter.setIgnoreCapabiltyProperties(false); + filter.setIgnoreComponentInstances(false); + filter.setIgnoreRequirements(false); + Either serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter); + if (serviceRes.isRight()) { + return serviceRes.right().value(); + } + Component service = serviceRes.left().value(); + Map> capabilities = service.getCapabilities(); + resourceInstance.setCapabilities(capabilities); + Map> req = service.getRequirements(); + resourceInstance.setRequirements(req); + + String name = service.getNormalizedName() + ToscaOperationFacade.PROXY_SUFFIX; + String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName(); + int lastIndexOf = toscaResourceName.lastIndexOf('.'); + if (lastIndexOf != -1) { + String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name; + resourceInstance.setToscaComponentName(proxyToscaName); + } + resourceInstance.setName(name); + resourceInstance.setIsProxy(true); + resourceInstance.setSourceModelInvariant(service.getInvariantUUID()); + resourceInstance.setSourceModelName(service.getName()); + resourceInstance.setSourceModelUuid(service.getUUID()); + resourceInstance.setSourceModelUid(service.getUniqueId()); + resourceInstance.setComponentUid(proxyTemplate.getUniqueId()); + resourceInstance.setDescription("A Proxy for Service " + service.getName()); + resourceInstance.setComponentVersion(service.getVersion()); + + return StorageOperationStatus.OK; + } + public Either createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) { Either resultOp = null; @@ -216,7 +285,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { try { log.debug("Try to create entry on graph"); - Either eitherResourceName = getOriginComponentNameFromComponentInstance(resourceInstance, true); + Either eitherResourceName = getOriginComponentFromComponentInstance(resourceInstance, true); if (eitherResourceName.isRight()) { resultOp = Either.right(eitherResourceName.right().value()); @@ -260,7 +329,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - private Either getOriginComponentNameFromComponentInstance(ComponentInstance componentInstance, boolean inTransaction) { + private Either getOriginComponentFromComponentInstance(ComponentInstance componentInstance, boolean inTransaction) { Either eitherResponse; Either eitherComponent = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid()); if (eitherComponent.isRight()) { @@ -286,7 +355,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { log.debug("Entity on graph is created."); Component updatedComponent = result.left().value().getLeft(); Map existingEnvVersions = new HashMap<>(); - //TODO existingEnvVersions ?? + // TODO existingEnvVersions ?? Either addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions); if (addComponentInstanceArtifacts.isRight()) { log.debug("Failed to create component instance {}", componentInstance.getName()); @@ -304,19 +373,17 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return resultOp; } - /** - * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts - * - * @param componentInstance - * @param userId - * @param existingEnvVersions - * TODO - * @param containerComponentId - * - * @return - */ - protected Either addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user, - Map existingEnvVersions) { +/** + * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts + * @param containerComponent + * @param componentInstance + * @param originComponent + * @param user + * @param existingEnvVersions + * @return + */ + 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); @@ -324,80 +391,72 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null); return Either.right(resultOp); } - + StorageOperationStatus artStatus; // generate heat_env if necessary Map componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts(); - if (componentDeploymentArtifacts == null) { - return Either.left(ActionStatus.OK); - } - Map finalDeploymentArtifacts = new HashMap(); - - Map> groupInstancesArtifacts = new HashMap<>(); - - for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) { - String type = artifact.getArtifactType(); + if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) { - if ( !type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) ){ - finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact); - } - - if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) { - continue; - } + Map finalDeploymentArtifacts = new HashMap(); + Map> groupInstancesArtifacts = new HashMap<>(); - if (artifact.checkEsIdExist()) { - 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()); + for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) { + String type = artifact.getArtifactType(); + if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) { + finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact); } - ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value(); - - //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()); + if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) { + continue; } - 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<>(); + if (artifact.checkEsIdExist()) { + 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 artifactDefinition = createHeatEnvPlaceHolder.left().value(); + // 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()); + } + 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; } - artifactsUid.add(artifactDefinition); - groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid); - break; } } - } } + 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.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); + + } + 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.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result))); + } + componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts); } - 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.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); - - } - 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.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result))); - } - componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts); - - + artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts()); - if ( artStatus != StorageOperationStatus.OK){ + if (artStatus != StorageOperationStatus.OK) { log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); - + } componentInstance.setArtifacts(originComponent.getArtifacts()); return Either.left(ActionStatus.OK); @@ -483,7 +542,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } try { - Either eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, inTransaction); + Either eitherResourceName = getOriginComponentFromComponentInstance(componentInstance, inTransaction); if (eitherResourceName.isRight()) { resultOp = Either.right(eitherResourceName.right().value()); @@ -557,42 +616,40 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { List updatedList = new ArrayList<>(); List instancesFromContainerComponent = containerComponent.getComponentInstances(); List listForUpdate = new ArrayList<>(); - if(instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty()) + if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty()) containerComponent.setComponentInstances(componentInstanceList); - else{ + else { Iterator iterator = instancesFromContainerComponent.iterator(); - while(iterator.hasNext()){ + 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(); + if (op.isPresent()) { + ComponentInstance updatedCi = op.get(); updatedCi = buildComponentInstance(updatedCi, origInst); - + 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()); + 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 + } else listForUpdate.add(origInst); } containerComponent.setComponentInstances(listForUpdate); - - if(resultOp == null){ - Either updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); - if(updateStatus.isRight()){ + + if (resultOp == null) { + Either updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter); + 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()){ + for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) { Optional op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny(); - if(op.isPresent()){ + if (op.isPresent()) { updatedList.add(updatedInstance); } } @@ -640,8 +697,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (resultOp == null) { oldComponentInstance = componentInstanceOptional.get(); String newInstanceName = componentInstance.getName(); - if ( oldComponentInstance!=null && oldComponentInstance.getName() != null - && !oldComponentInstance.getName().equals( newInstanceName ) ) + if (oldComponentInstance != null && oldComponentInstance.getName() != null && !oldComponentInstance.getName().equals(newInstanceName)) isNameChanged = true; Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName); if (!isUniqueName) { @@ -655,14 +711,14 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { 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)); - }else{ - //region - Update instance Groups - if ( isNameChanged ){ - Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance( containerComponent ,oldComponentInstance ,componentInstanceId ); - if ( result.isRight() ) - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId ,result.right().value() ); + } else { + // region - Update instance Groups + if (isNameChanged) { + Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId); + if (result.isRight()) + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value()); } - //endregion + // endregion } } if (resultOp == null) { @@ -672,24 +728,28 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { 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{ + } else { resultOp = Either.left(updatedInstanceOptional.get()); } - + } if (resultOp == null) { resultOp = Either.left(componentInstanceOptional.get()); } return resultOp; } + /** - * @param oldPrefix- The normalized old vf name - * @param newNormailzedPrefix- The normalized new vf name - * @param qualifiedGroupInstanceName- old Group Instance Name + * @param oldPrefix- + * The normalized old vf name + * @param newNormailzedPrefix- + * The normalized new vf name + * @param qualifiedGroupInstanceName- + * old Group Instance Name **/ - //modify group names - private String getNewGroupName( String oldPrefix ,String newNormailzedPrefix , String qualifiedGroupInstanceName){ - if (qualifiedGroupInstanceName == null){ + // modify group names + private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) { + if (qualifiedGroupInstanceName == null) { log.info("CANNOT change group name "); return null; } @@ -702,9 +762,8 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { oldComponentInstance.setName(newComponentInstance.getName()); oldComponentInstance.setModificationTime(System.currentTimeMillis()); oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString()); - if ( oldComponentInstance.getGroupInstances() != null ) - oldComponentInstance.getGroupInstances().forEach( group -> - group.setName( getNewGroupName( oldComponentInstance.getNormalizedName() , ValidationUtils.normalizeComponentInstanceName( newComponentInstance.getName() ) , group.getName() ) ) ); + if (oldComponentInstance.getGroupInstances() != null) + oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName()))); return oldComponentInstance; } @@ -772,26 +831,25 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } 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()); + for (GroupDataDefinition currGroup : containerComponent.getGroups()) { + Map members = currGroup.getMembers(); + if (members != null && members.containsKey(deletedInstance.getName())) { + members.remove(deletedInstance.getName()); groupsToUpdate.add(currGroup); } } - Either, StorageOperationStatus> updateGroupsRes = - toscaOperationFacade.updateGroupsOnComponent(containerComponent, containerComponent.getComponentType(), groupsToUpdate); + 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)); } } - if(resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())){ + if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())) { List inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList()); - if(CollectionUtils.isNotEmpty(inputsToDelete)){ - StorageOperationStatus deleteInputsRes = - toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, containerComponent.getComponentType(), inputsToDelete); - if(deleteInputsRes != StorageOperationStatus.OK){ + if (CollectionUtils.isNotEmpty(inputsToDelete)) { + StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, containerComponent.getComponentType(), inputsToDelete); + if (deleteInputsRes != StorageOperationStatus.OK) { log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId); resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId)); } @@ -802,8 +860,8 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) { ComponentInstance foundInstance = null; - for(ComponentInstance instance : containerComponent.getComponentInstances()){ - if(instance.getUniqueId().equals(componentInstanceId)){ + for (ComponentInstance instance : containerComponent.getComponentInstances()) { + if (instance.getUniqueId().equals(componentInstanceId)) { foundInstance = instance; containerComponent.getComponentInstances().remove(instance); break; @@ -885,7 +943,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { toNameOrId = toResult.left().value().getName(); } - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRequirement())); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement())); return resultOp; } @@ -941,13 +999,156 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } resultOp = Either - .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRequirement())); + .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement())); return resultOp; } } finally { unlockComponent(resultOp, containerComponent); } } + /** + * Allows to get relation contained in specified component according to received Id + * @param componentId + * @param relationId + * @param userId + * @param componentTypeEnum + * @return + */ + public Either getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) { + + Either resultOp = null; + try { + org.openecomp.sdc.be.model.Component containerComponent = null; + Either validateComponentExists = null; + RequirementCapabilityRelDef foundRelation = null; + + Either validateUserRes = validateUserExists(userId, "get relation by Id", false); + if (validateUserRes.isRight()) { + resultOp = Either.right(validateUserRes.right().value()); + } + if(resultOp == null){ + validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); + if (validateComponentExists.isRight()) { + resultOp = Either.right(validateComponentExists.right().value()); + } + } + if(resultOp == null){ + containerComponent = validateComponentExists.left().value(); + List requirementCapabilityRelations = containerComponent.getComponentInstancesRelations(); + foundRelation = findRelation(relationId, requirementCapabilityRelations); + if(foundRelation == null){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId); + log.debug("Relation with id {} was not found on the component", relationId, componentId); + resultOp = Either.right(responseFormat); + } + } + if(resultOp == null){ + resultOp = setRelatedCapability(foundRelation, containerComponent); + } + if(resultOp.isLeft()){ + resultOp = setRelatedRequirement(foundRelation, containerComponent); + } + } catch (Exception e) { + log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return resultOp; + } + + private RequirementCapabilityRelDef findRelation(String relationId, List requirementCapabilityRelations) { + for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){ + if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){ + return relationship; + } + } + return null; + } + + private Either setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) { + Either result = null; + RelationshipInfo relationshipInfo = foundRelation.getSingleRelationship().getRelation(); + String instanceId = foundRelation.getFromNode(); + Optional foundRequirement; + Optional instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); + if(!instance.isPresent()){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName()); + log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId()); + result = Either.right(responseFormat); + } + if(result == null){ + for(List requirements : instance.get().getRequirements().values()){ + foundRequirement = requirements.stream().filter(r -> isBelongingRequirement(relationshipInfo, r)).findFirst(); + if(foundRequirement.isPresent()){ + foundRelation.getSingleRelationship().setRequirement(foundRequirement.get()); + result = Either.left(foundRelation); + } + } + } + if(result == null){ + Either getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, req)->isBelongingRequirement(rel, req)); + if(getfulfilledRequirementRes.isRight()){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId()); + log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); + result = Either.right(responseFormat); + } else { + foundRelation.getSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value()); + } + } + if(result == null){ + result = Either.left(foundRelation); + } + return result; + } + + private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) { + return req.getRelationship().equals(relationshipInfo.getRelationship().getType()) && + req.getName().equals(relationshipInfo.getRequirement()) && + req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && + req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId()); + } + + private Either setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) { + Either result = null; + RelationshipInfo relationshipInfo = foundRelation.getSingleRelationship().getRelation(); + String instanceId = foundRelation.getToNode(); + Optional foundCapability; + Optional instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); + if(!instance.isPresent()){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName()); + log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId()); + result = Either.right(responseFormat); + } + if(result == null){ + for(List capabilities : instance.get().getCapabilities().values()){ + foundCapability = capabilities.stream().filter(c -> isBelongingCapability(relationshipInfo, c)).findFirst(); + if(foundCapability.isPresent()){ + foundRelation.getSingleRelationship().setCapability(foundCapability.get()); + result = Either.left(foundRelation); + } + } + } + if(result == null){ + Either getfulfilledRequirementRes = + toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, cap)->isBelongingCapability(rel, cap)); + if(getfulfilledRequirementRes.isRight()){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); + log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); + result = Either.right(responseFormat); + } else { + foundRelation.getSingleRelationship().setCapability(getfulfilledRequirementRes.left().value()); + } + } + if(result == null){ + result = Either.left(foundRelation); + } + return result; + } + + private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) { + return cap.getName().equals(relationshipInfo.getCapability()) && + cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && + cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId()); + } private Either updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) { Either eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true); @@ -999,7 +1200,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { /** * Create Or Updates Attribute Instance - * + * * @param componentTypeEnum * @param componentId * @param resourceInstanceId @@ -1047,28 +1248,82 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - // US833308 VLI in service - specific network_role property value logic + private boolean isNetworkRoleServiceProperty(ComponentInstanceProperty property, ComponentTypeEnum componentTypeEnum) { + return StringUtils.isNotEmpty(property.getValue()) + && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName()) + && ComponentTypeEnum.SERVICE == componentTypeEnum; + } + 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(); + return concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, Arrays.asList(property)); + } + + // US833308 VLI in service - specific network_role property value logic + private StorageOperationStatus concatServiceNameToVLINetworkRolePropertiesValues(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List properties) { + for (ComponentInstanceProperty property: properties) { + if (isNetworkRoleServiceProperty(property, 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; + } + + private Either updatePropertyObjectValue(ComponentInstanceProperty property, Map allDataTypes) { + 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))); } - Component service = getServiceResult.left().value(); - Optional getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny(); - if (!getInstance.isPresent()) { - return StorageOperationStatus.NOT_FOUND; + 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))); } - String prefix = service.getSystemName() + "."; - String value = property.getValue(); - if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) { - property.setValue(prefix + value); + innerType = propDef.getType(); + } + // Specific Update Logic + Either isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes); + 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(); } } - return StorageOperationStatus.OK; + + ImmutablePair pair = propertyOperation.validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, 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)))); + } + return Either.left(newValue); } public Either createOrUpdatePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property, String userId) { @@ -1156,7 +1411,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { 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) { @@ -1169,12 +1424,12 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Optional instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); StorageOperationStatus status; instanceProperty.get().setValue(newValue); - if(instanceProperty.isPresent()){ + if (instanceProperty.isPresent()) { status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property); } else { status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property); } - if(status != StorageOperationStatus.OK){ + if (status != StorageOperationStatus.OK) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); return resultOp; @@ -1182,17 +1437,17 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { List path = new ArrayList<>(); path.add(foundResourceInstance.getUniqueId()); property.setPath(path); - + 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; + resultOp = Either.left(property); + return resultOp; } finally { if (resultOp == null || resultOp.isRight()) { @@ -1205,7 +1460,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - + public Either createOrUpdateInstanceInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput property, String userId) { Either resultOp = null; @@ -1239,9 +1494,9 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { 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) { @@ -1276,44 +1531,38 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } 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) { + if (!res) { 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()){ + 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){ + 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; + resultOp = Either.left(property); + return resultOp; } finally { if (resultOp == null || resultOp.isRight()) { @@ -1577,7 +1826,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } private Either getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) { - + Either eitherResponse = null; ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType); Component component; @@ -1589,16 +1838,16 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); eitherResponse = Either.right(errorResponse); } - if(eitherResponse == null) { + 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); + eitherResponse = Either.right(errorResponse); } } - if(eitherResponse == null) { + if (eitherResponse == null) { eitherResponse = Either.left(getComponentRes.left().value()); } return eitherResponse; @@ -1632,7 +1881,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return Either.right(validateCanWorkOnComponent.right().value()); } - Either resourceInstanceStatus = getResourceInstanceById(containerComponent,componentInstanceId); + Either resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId); if (resourceInstanceStatus.isRight()) { resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId)); return resultOp; @@ -1646,48 +1895,79 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } try { + + if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) { resultOp = Either.left(currentResourceInstance); return resultOp; } String resourceId = newComponentInstance.getComponentUid(); + + + Either componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId); - if(componentExistsRes.isRight()){ + 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; - } - else if (!componentExistsRes.left().value()) { + } else if (!componentExistsRes.left().value()) { log.debug("The resource {} not found ", resourceId); resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); return resultOp; } - // List groupInstances = currentResourceInstance.getGroupInstances(); - Map deploymentArtifacts = currentResourceInstance.getDeploymentArtifacts(); + Either eitherOriginComponent = getOriginComponentFromComponentInstance(currentResourceInstance, true); + + if (eitherOriginComponent.isRight()) { + resultOp = Either.right(eitherOriginComponent.right().value()); + return resultOp; + } + DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent.left().value()); resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); if (resultOp.isRight()) { log.debug("failed to delete resource instance {}", resourceId); return resultOp; } + ComponentInstance resResourceInfo = resultOp.left().value(); + Component origComponent = null; + OriginTypeEnum originType = currentResourceInstance.getOriginType(); + if (originType == OriginTypeEnum.ServiceProxy) { + Either serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy"); + if (serviceProxyOrigin.isRight()) { + log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()))); + } + origComponent = serviceProxyOrigin.left().value(); - Either eitherResourceName = getOriginComponentNameFromComponentInstance(newComponentInstance, true); + StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent); - if (eitherResourceName.isRight()) { - resultOp = Either.right(eitherResourceName.right().value()); - return resultOp; - } + if (fillProxyRes != StorageOperationStatus.OK) { + log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes))); - Component origComponent = eitherResourceName.left().value(); + } + newComponentInstance.setOriginType(originType); + }else{ + + + Either eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance, true); + + if (eitherResourceName.isRight()) { + resultOp = Either.right(eitherResourceName.right().value()); + return resultOp; + } + + origComponent = eitherResourceName.left().value(); + + newComponentInstance.setName(resResourceInfo.getName()); + //newComponentInstance.setToscaComponentName(((ResourceMetadataDataDefinition) origComponent.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName()); + } - ComponentInstance resResourceInfo = resultOp.left().value(); - newComponentInstance.setName(resResourceInfo.getName()); newComponentInstance.setInvariantName(resResourceInfo.getInvariantName()); newComponentInstance.setPosX(resResourceInfo.getPosX()); newComponentInstance.setPosY(resResourceInfo.getPosY()); newComponentInstance.setDescription(resResourceInfo.getDescription()); - newComponentInstance.setToscaComponentName(((ResourceMetadataDataDefinition)origComponent.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName()); resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user); @@ -1702,29 +1982,25 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return resultOp; } - /* 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; - } - - + Either mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId()); + if (mergeStatusEither.isRight()) { + return Either.right(mergeStatusEither.right().value()); } - 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; - } - }*/ - + /* + * 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; } } + */ + ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnoreComponentInstances(false); - Either updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter); + Either updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter); if (updatedComponentRes.isRight()) { StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value(); ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType()); @@ -1732,7 +2008,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { log.debug("Component with id {} was not found", containerComponentId); return Either.right(responseFormat); } - resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(),updatedComponentInstance.getUniqueId()); + resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId()); if (resourceInstanceStatus.isRight()) { resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId())); return resultOp; @@ -1780,9 +2056,9 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { 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)){ + if (CollectionUtils.isEmpty(instanceProperties)) { instanceProperties = new ArrayList<>(); } resultOp = Either.left(instanceProperties); @@ -1808,7 +2084,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { /** * updates componentInstance modificationTime - * + * * @param componentInstance * @param componentInstanceType * @param modificationTime @@ -1827,7 +2103,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } return result; } - + public Either deleteServiceProxy(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) { // TODO Add implementation Either result = Either.left(new ComponentInstance()); @@ -1845,7 +2121,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Either result = Either.left(new ComponentInstance()); return result; } - + private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) { Boolean isUnique = true; String newInstanceNormalizedName = ValidationUtils.normalizeComponentInstanceName(newInstanceName); @@ -1859,57 +2135,259 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } private Either getResourceInstanceById(Component containerComponent, String instanceId) { - + Either result = null; List instances = containerComponent.getComponentInstances(); Optional foundInstance = null; - if(CollectionUtils.isEmpty(instances)){ + if (CollectionUtils.isEmpty(instances)) { result = Either.right(StorageOperationStatus.NOT_FOUND); } - if(result == null){ + if (result == null) { foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); - if(!foundInstance.isPresent()){ + if (!foundInstance.isPresent()) { result = Either.right(StorageOperationStatus.NOT_FOUND); } } - if(result == null){ + if (result == null) { result = Either.left(foundInstance.get()); } return result; } - - private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) { - Long creationDate = origInstanceForUpdate.getCreationTime(); - + private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) { + + Long creationDate = origInstanceForUpdate.getCreationTime(); + Long modificationTime = System.currentTimeMillis(); resourceInstanceForUpdate.setCreationTime(creationDate); resourceInstanceForUpdate.setModificationTime(modificationTime); - + resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID()); - + if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) { resourceInstanceForUpdate.setName(origInstanceForUpdate.getName()); } - + resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName())); - + if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon())) - resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon()); - - + resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon()); + if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion())) resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion()); - + if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName())) resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName()); - + if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName())) - resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName()); - - if (resourceInstanceForUpdate.getOriginType() == null) { + resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName()); + + if (resourceInstanceForUpdate.getOriginType() == null) { resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType()); } + if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy) + resourceInstanceForUpdate.setIsProxy(true); + if (resourceInstanceForUpdate.getSourceModelInvariant() == null) { + resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant()); + } + if (resourceInstanceForUpdate.getSourceModelName() == null) { + resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName()); + } + if (resourceInstanceForUpdate.getSourceModelUuid() == null) { + resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid()); + } + if (resourceInstanceForUpdate.getSourceModelUid() == null) { + resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid()); + } return resourceInstanceForUpdate; } + /** + * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name and type + * @param containerComponentType + * @param containerComponentId + * @param componentInstanceUniqueId + * @param capabilityType + * @param capabilityName + * @param userId + * @return + */ + public Either, ResponseFormat> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String userId) { + + Component containerComponent = null; + + Either, ResponseFormat> resultOp = null; + try { + Either validateUserExists = validateUserExists(userId, "Get Component Instance Properties By Id", false); + if (validateUserExists.isRight()) { + resultOp = Either.right(validateUserExists.right().value()); + } + if(resultOp == null){ + Either validateComponentType = validateComponentType(containerComponentType); + if (validateComponentType.isRight()) { + resultOp = Either.right(validateComponentType.right().value()); + } + } + if(resultOp == null){ + Either validateContainerComponentExists = toscaOperationFacade.getToscaFullElement(containerComponentId); + if (validateContainerComponentExists.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()))); + } else { + containerComponent = validateContainerComponentExists.left().value(); + } + } + if(resultOp == null){ + Either resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); + if (resourceInstanceStatus.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); + } else { + resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, resourceInstanceStatus.left().value().getCapabilities()); + } + } + return resultOp; + } finally { + unlockComponent(resultOp, containerComponent); + } + } + + private Either, ResponseFormat> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, Map> instanceCapabilities) { + Either, ResponseFormat> result = null; + CapabilityDefinition foundCapability; + if (MapUtils.isNotEmpty(instanceCapabilities)) { + List capabilitiesPerType = instanceCapabilities.get(capabilityType); + if (capabilitiesPerType != null) { + Optional capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName)).findFirst(); + if (capabilityOpt.isPresent()) { + foundCapability = capabilityOpt.get(); + result = Either.left(foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties()); + } + } + } + if (result == null) { + result = fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName); + } + return result; + } + + private Either, ResponseFormat> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName) { + Either, ResponseFormat> resultOp = null; + try { + Either, StorageOperationStatus> getComponentInstanceCapabilityProperties = toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType); + if(getComponentInstanceCapabilityProperties.isRight()){ + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentInstanceCapabilityProperties.right().value()), capabilityType, instanceId, componentId)); + } else { + resultOp = Either.left(getComponentInstanceCapabilityProperties.left().value()); + } + } catch(Exception e){ + log.error("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return resultOp; + } + + private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance, + String capabilityType, String capabilityName) { + String componentInstanceUniqueId = foundResourceInstance.getUniqueId(); + StringBuilder sb = new StringBuilder(componentInstanceUniqueId); + sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName); + String capKey = sb.toString(); + + Map> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities()) + .orElse(Collections.emptyMap()); + List capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList()); + Optional cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny(); + if (cap.isPresent()) { + List capProperties = cap.get().getProperties(); + if (capProperties != null) { + Optional instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); + StorageOperationStatus status; + if (instanceProperty.isPresent()) { + instanceProperty.get().setValue(newValue); + List path = new ArrayList<>(); + path.add(componentInstanceUniqueId); + path.add(capKey); + instanceProperty.get().setPath(path); + status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get()); + if (status != StorageOperationStatus.OK) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""); + + } + foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); + } + } + } + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + + public Either, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, + List properties, String userId) { + Either, ResponseFormat> resultOp = null; + + Either resp = validateUserExists(userId, "update instance capability property", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + } + Either getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId); + + if (getResourceResult.isRight()) { + log.debug("Failed to retrieve component, component id {}", containerComponentId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + Component containerComponent = getResourceResult.left().value(); + + if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { + log.info("Restricted operation for user: {} on component {}", userId, containerComponentId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + Either resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); + if (resourceInstanceStatus.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); + } + ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); + // lock resource + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock component {}", containerComponentId); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + } + + 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)))); + } + + try { + for (ComponentInstanceProperty property : properties) { + Either newPropertyValueEither = updatePropertyObjectValue(property, allDataTypes.left().value()); + newPropertyValueEither.bimap(updatedValue -> + updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName), + responseFormat -> Either.right(responseFormat)); + } + 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(properties); + return resultOp; + + } finally { + if (resultOp == null || resultOp.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType()); + } + } } 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 e8c04c22c1..f6a108cf75 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 @@ -69,7 +69,7 @@ public class CompositionBusinessLogic { boolean isNotAllPositionsCalculated = resource.getComponentInstances() == null || resource.getComponentInstances().stream().filter(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty())).findAny().isPresent(); - if (isNotAllPositionsCalculated) { + if (isNotAllPositionsCalculated && resource.getComponentInstances() != null) { // Arrange Icons In Spiral Pattern Map, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(resource); 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 8b0c6fa8bf..53dceb8112 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 @@ -20,8 +20,6 @@ package org.openecomp.sdc.be.components.impl; -import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringReader; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java index 9d9425ea85..be3ac13cc9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java @@ -20,9 +20,12 @@ package org.openecomp.sdc.be.components.impl; -import org.springframework.beans.factory.annotation.Autowired; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; -import fj.data.Either; import org.apache.http.HttpStatus; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; @@ -43,7 +46,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.*; +import fj.data.Either; @Component("distributionMonitoringBusinessLogic") public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic { 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 2c051b2b94..54bed5ae56 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 @@ -20,10 +20,20 @@ package org.openecomp.sdc.be.components.impl; -import com.thinkaurelius.titan.core.TitanGraph; -import fj.data.Either; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedList; +import java.util.List; +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; @@ -38,10 +48,27 @@ 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.*; +import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum; +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.GraphPropertyEnum; +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.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.ArtifactType; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +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; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.GroupingDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; @@ -64,10 +91,9 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.function.Predicate; -import java.util.stream.Collectors; +import com.thinkaurelius.titan.core.TitanGraph; + +import fj.data.Either; @org.springframework.stereotype.Component("elementsBusinessLogic") public class ElementBusinessLogic extends BaseBusinessLogic { 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 a3d590374f..de571b0f03 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,7 +20,6 @@ package org.openecomp.sdc.be.components.impl; -import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -42,17 +41,13 @@ 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; import org.openecomp.sdc.be.info.ArtifactTemplateInfo; import org.openecomp.sdc.be.info.GroupDefinitionInfo; @@ -69,17 +64,15 @@ 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.Resource; +import org.openecomp.sdc.be.model.User; 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.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.UniqueIdBuilder; -import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; @@ -88,7 +81,6 @@ 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; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java index 2de9eee217..b3448b27ef 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java @@ -20,7 +20,15 @@ package org.openecomp.sdc.be.components.impl; -import fj.data.Either; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +import javax.annotation.Resource; + import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; @@ -37,13 +45,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import javax.annotation.Resource; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; -import java.util.stream.Collectors; +import fj.data.Either; @Component("groupTypeImportManager") public class GroupTypeImportManager { 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 fe9c8488aa..eff3d39f7f 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 @@ -21,7 +21,6 @@ package org.openecomp.sdc.be.components.impl; import java.io.IOException; -import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -38,6 +37,8 @@ import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; @@ -54,18 +55,18 @@ import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.IEsHealthCheckDao; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.switchover.detector.SwitchoverDetector; +import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.api.HealthCheckInfo; -import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckComponent; import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; -import org.openecomp.sdc.common.api.HealthCheckWrapper; import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.util.HealthCheckUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; @Component("healthCheckBusinessLogic") public class HealthCheckBusinessLogic { @@ -135,12 +136,26 @@ public class HealthCheckBusinessLogic { return true; } - public List getBeHealthCheckInfosStatus() { + public Pair> getBeHealthCheckInfosStatus() { - return prevBeHealthCheckInfos; + return new ImmutablePair>(getAggregateBeStatus(prevBeHealthCheckInfos), prevBeHealthCheckInfos); } + private Boolean getAggregateBeStatus(List beHealthCheckInfos) { + + Boolean status = true; + + for (HealthCheckInfo healthCheckInfo : beHealthCheckInfos) { + if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN) && !healthCheckInfo.getHealthCheckComponent().equals(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE)) { + status = false; + break; + } + } + return status; + } + + private List getBeHealthCheckInfos() { log.trace("In getBeHealthCheckInfos"); @@ -150,9 +165,6 @@ public class HealthCheckBusinessLogic { // BE getBeHealthCheck(healthCheckInfos); - /*// ES - getEsHealthCheck(healthCheckInfos);*/ - // Titan getTitanHealthCheck(healthCheckInfos); @@ -165,18 +177,21 @@ public class HealthCheckBusinessLogic { // Amdocs getAmdocsHealthCheck(healthCheckInfos); + //DCAE + getDcaeHealthCheck(healthCheckInfos); + return healthCheckInfos; } private List getBeHealthCheck(List healthCheckInfos) { String appVersion = ExternalConfiguration.getAppVersion(); String description = "OK"; - healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.BE, HealthCheckStatus.UP, appVersion, description)); + healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.UP, appVersion, description)); return healthCheckInfos; } //Removed from aggregate HC - TDP 293490 -/* private List getEsHealthCheck(List healthCheckInfos) { + /* private List getEsHealthCheck(List healthCheckInfos) { // ES health check and version HealthCheckStatus healthCheckStatus; @@ -198,7 +213,7 @@ public class HealthCheckBusinessLogic { healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ES, healthCheckStatus, null, description)); return healthCheckInfos; } -*/ + */ public List getTitanHealthCheck(List healthCheckInfos) { // Titan health check and version String description; @@ -208,15 +223,15 @@ public class HealthCheckBusinessLogic { isTitanUp = titanGenericDao.isGraphOpen(); } catch (Exception e) { description = "Titan error: " + e.getMessage(); - healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.DOWN, null, description)); + healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.DOWN, null, description)); return healthCheckInfos; } if (isTitanUp) { description = "OK"; - healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.UP, null, description)); + healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.UP, null, description)); } else { description = "Titan graph is down"; - healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.DOWN, null, description)); + healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.DOWN, null, description)); } return healthCheckInfos; } @@ -234,10 +249,10 @@ public class HealthCheckBusinessLogic { } if (isCassandraUp) { description = "OK"; - healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.CASSANDRA, HealthCheckStatus.UP, null, description)); + healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_CASSANDRA, HealthCheckStatus.UP, null, description)); } else { description = "Cassandra is down"; - healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.CASSANDRA, HealthCheckStatus.DOWN, null, description)); + healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_CASSANDRA, HealthCheckStatus.DOWN, null, description)); } return healthCheckInfos; @@ -252,71 +267,92 @@ public class HealthCheckBusinessLogic { } private List getAmdocsHealthCheck(List healthCheckInfos) { + HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(Constants.HC_COMPONENT_ON_BOARDING, buildOnBoardingHealthCheckUrl()); + healthCheckInfos.add(beHealthCheckInfo); + return healthCheckInfos; + } + + private List getDcaeHealthCheck(List healthCheckInfos) { + HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(Constants.HC_COMPONENT_DCAE, buildDcaeHealthCheckUrl()); + healthCheckInfos.add(beHealthCheckInfo); + return healthCheckInfos; + } + + private HealthCheckInfo getHostedComponentsBeHealthCheck(String componentName, String healthCheckUrl) { HealthCheckStatus healthCheckStatus; String description; String version = null; List componentsInfo = new ArrayList<>(); CloseableHttpClient httpClient = getHttpClient(); - String amdocsHealtchCheckUrl = buildHealthCheckUrl(); - HttpGet httpGet = new HttpGet(amdocsHealtchCheckUrl); - CloseableHttpResponse beResponse; - int beStatus; - try { - beResponse = httpClient.execute(httpGet); - beStatus = beResponse.getStatusLine().getStatusCode(); - - StringBuilder sb = new StringBuilder(); - - if (beStatus == HttpStatus.SC_OK || beStatus == HttpStatus.SC_INTERNAL_SERVER_ERROR) { - HttpEntity entity = beResponse.getEntity(); - String beJsonResponse = EntityUtils.toString(entity); - Gson gson = new Gson(); - HealthCheckWrapper healthCheckWrapper = gson.fromJson(beJsonResponse, HealthCheckWrapper.class); - version = healthCheckWrapper.getSdcVersion(); - componentsInfo = healthCheckWrapper.getComponentsInfo(); - - if (componentsInfo != null) { - componentsInfo.forEach(x -> { - if (x.getHealthCheckStatus() == HealthCheckStatus.DOWN) { - sb.append("Component " + x.getHealthCheckComponent().name() + " is Down, "); - } - }); + + if (healthCheckUrl != null) { + HttpGet httpGet = new HttpGet(healthCheckUrl); + CloseableHttpResponse beResponse; + int beStatus; + try { + beResponse = httpClient.execute(httpGet); + beStatus = beResponse.getStatusLine().getStatusCode(); + + String aggDescription = ""; + + if (beStatus == HttpStatus.SC_OK || beStatus == HttpStatus.SC_INTERNAL_SERVER_ERROR) { + HttpEntity entity = beResponse.getEntity(); + String beJsonResponse = EntityUtils.toString(entity); + log.trace("{} Health Check response: {}", componentName, beJsonResponse); + + ObjectMapper mapper = new ObjectMapper(); + Map healthCheckMap = mapper.readValue(beJsonResponse, new TypeReference>(){}); + version = healthCheckMap.get("sdcVersion") != null ? healthCheckMap.get("sdcVersion").toString() : null; + if (healthCheckMap.containsKey("componentsInfo")) { + componentsInfo = mapper.convertValue(healthCheckMap.get("componentsInfo"), new TypeReference>() {}); + } + + if (componentsInfo.size() > 0) { + aggDescription = HealthCheckUtil.getAggregateDescription(componentsInfo, null); + } else { + componentsInfo.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.DOWN, null, null)); + } } else { - componentsInfo.add(new HealthCheckInfo(HealthCheckComponent.BE, HealthCheckStatus.DOWN, null, null)); + log.trace("{} Health Check Response code: {}", componentName, beStatus); } - } - if (beStatus != HttpStatus.SC_OK) { - healthCheckStatus = HealthCheckStatus.DOWN; - //Removing the last comma - description = sb.length()>0 - ? sb.substring(0, sb.length()-1) - : "Onboarding is Down, specific reason unknown";//No Amdocs inner component returned DOWN, but the status of Amdocs HC is still DOWN. - if (componentsInfo.size() == 0) { - componentsInfo.add(new HealthCheckInfo(HealthCheckComponent.BE, HealthCheckStatus.DOWN, null, description)); + if (beStatus != HttpStatus.SC_OK) { + healthCheckStatus = HealthCheckStatus.DOWN; + description = aggDescription.length() > 0 + ? aggDescription + : componentName + " is Down, specific reason unknown";//No inner component returned DOWN, but the status of HC is still DOWN. + if (componentsInfo.size() == 0) { + componentsInfo.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.DOWN, null, description)); + } + } else { + healthCheckStatus = HealthCheckStatus.UP; + description = "OK"; } - } else { - healthCheckStatus = HealthCheckStatus.UP; - description = "OK"; - } - } catch (Exception e) { - healthCheckStatus = HealthCheckStatus.DOWN; - description = "Onboarding unexpected response: " + e.getMessage(); - componentsInfo.add(new HealthCheckInfo(HealthCheckComponent.BE, HealthCheckStatus.DOWN, null, description)); - } finally { - if (httpClient != null) { - try { - httpClient.close(); - } catch (IOException e) { - e.printStackTrace(); + } catch (Exception e) { + log.error("{} unexpected response: ", componentName, e); + healthCheckStatus = HealthCheckStatus.DOWN; + description = componentName + " unexpected response: " + e.getMessage(); + if (componentsInfo != null && componentsInfo.size() == 0) { + componentsInfo.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.DOWN, null, description)); + } + } finally { + if (httpClient != null) { + try { + httpClient.close(); + } catch (IOException e) { + log.error("closing http client has failed" , e); + } } } + } else { + healthCheckStatus = HealthCheckStatus.DOWN; + description = componentName + " health check Configuration is missing"; + componentsInfo.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.DOWN, null, description)); } - healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ON_BOARDING, healthCheckStatus, version, description, componentsInfo)); - return healthCheckInfos; + return new HealthCheckInfo(componentName, healthCheckStatus, version, description, componentsInfo); } private CloseableHttpClient getHttpClient() { @@ -371,20 +407,6 @@ public class HealthCheckBusinessLogic { } } - - private boolean getAggregateBeStatus(List beHealthCheckInfos) { - - boolean status = true; - - for (HealthCheckInfo healthCheckInfo : beHealthCheckInfos) { - if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN) && healthCheckInfo.getHealthCheckComponent() != HealthCheckComponent.DE) { - status = false; - break; - } - } - return status; - } - } private void logAlarm(boolean prevHealthState) { @@ -410,8 +432,8 @@ public class HealthCheckBusinessLogic { if (beHealthCheckInfos != null && prevBeHealthCheckInfos != null) { - Map currentValues = beHealthCheckInfos.stream().collect(Collectors.toMap(p -> p.getHealthCheckComponent(), p -> p.getHealthCheckStatus())); - Map prevValues = prevBeHealthCheckInfos.stream().collect(Collectors.toMap(p -> p.getHealthCheckComponent(), p -> p.getHealthCheckStatus())); + Map currentValues = beHealthCheckInfos.stream().collect(Collectors.toMap(p -> p.getHealthCheckComponent(), p -> p.getHealthCheckStatus())); + Map prevValues = prevBeHealthCheckInfos.stream().collect(Collectors.toMap(p -> p.getHealthCheckComponent(), p -> p.getHealthCheckStatus())); if (currentValues != null && prevValues != null) { int currentSize = currentValues.size(); @@ -421,7 +443,7 @@ public class HealthCheckBusinessLogic { result = true; //extra/missing component - Map notPresent = null; + Map notPresent = null; if (currentValues.keySet().containsAll(prevValues.keySet())) { notPresent = new HashMap<>(currentValues); notPresent.keySet().removeAll(prevValues.keySet()); @@ -430,15 +452,15 @@ public class HealthCheckBusinessLogic { notPresent.keySet().removeAll(currentValues.keySet()); } - for (HealthCheckComponent component : notPresent.keySet()) { + for (String component : notPresent.keySet()) { logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, component, prevValues.get(component), currentValues.get(component))); } // HealthCheckComponent changedComponent = notPresent.keySet().iterator().next(); } else { - for (Entry entry : currentValues.entrySet()) { - HealthCheckComponent key = entry.getKey(); + for (Entry entry : currentValues.entrySet()) { + String key = entry.getKey(); HealthCheckStatus value = entry.getValue(); if (!prevValues.containsKey(key)) { @@ -468,15 +490,37 @@ public class HealthCheckBusinessLogic { return result; } - private String buildHealthCheckUrl() { + private String buildOnBoardingHealthCheckUrl() { Configuration.OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding(); - String protocol = onboardingConfig.getProtocol(); - String host = onboardingConfig.getHost(); - Integer port = onboardingConfig.getPort(); - String uri = onboardingConfig.getHealthCheckUri(); + if (onboardingConfig != null) { + String protocol = onboardingConfig.getProtocol(); + String host = onboardingConfig.getHost(); + Integer port = onboardingConfig.getPort(); + String uri = onboardingConfig.getHealthCheckUri(); + + return protocol + "://" + host + ":" + port + uri; + } + + log.error("onboarding health check configuration is missing."); + return null; + } + + private String buildDcaeHealthCheckUrl() { + + Configuration.DcaeConfig dcaeConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getDcae(); + + if (dcaeConfig != null) { + String protocol = dcaeConfig.getProtocol(); + String host = dcaeConfig.getHost(); + Integer port = dcaeConfig.getPort(); + String uri = dcaeConfig.getHealthCheckUri(); + + return protocol + "://" + host + ":" + port + uri; + } - return protocol + "://" + host + ":" + port + uri; + log.error("dcae health check configuration is missing."); + return null; } } 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 1755d0b20c..01d64f519f 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 @@ -21,7 +21,15 @@ package org.openecomp.sdc.be.components.impl; import java.lang.reflect.Type; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; import java.util.function.Consumer; import java.util.function.Function; 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 3b6e0f7a76..52dcce9e2e 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 @@ -20,31 +20,6 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.function.Predicate; -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.ArtifactTypeConfig; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -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.Resource; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; -import org.openecomp.sdc.common.api.ArtifactTypeEnum; -import org.openecomp.sdc.common.datastructure.Wrapper; -import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import fj.data.Either; - //Pavel //currently NOT IN USE - there are no informational deployed artifacts after US601880 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 892da8af9d..a9e7f0b34b 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 @@ -20,12 +20,19 @@ package org.openecomp.sdc.be.components.impl; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; import java.util.function.BiConsumer; import java.util.stream.Collectors; -import jline.internal.Log; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.json.simple.JSONObject; @@ -50,7 +57,6 @@ import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement; 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.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; @@ -65,6 +71,7 @@ import org.yaml.snakeyaml.Yaml; import com.google.gson.Gson; import fj.data.Either; +import jline.internal.Log; @Component("inputsBusinessLogic") public class InputsBusinessLogic extends BaseBusinessLogic { @@ -311,6 +318,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } currentInput.setDefaultValue(newValue); + currentInput.setOwnerId(userId); Either status = toscaOperationFacade.updateInputOfComponent(component, currentInput); @@ -473,6 +481,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } + assignOwnerIdToInputs(userId, inputsToCreate); Either, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.addInputsToComponent(inputsToCreate, component.getUniqueId()); if(assotiateInputsEither.isRight()){ @@ -524,6 +533,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } + private void assignOwnerIdToInputs(String userId, Map inputsToCreate) { + inputsToCreate.values().forEach(inputDefinition -> inputDefinition.setOwnerId(userId)); + } + private StorageOperationStatus addInputsToComponent(String componentId, Map inputsToCreate, Map> inputsValueToCreateMap, Map allDataTypes, List resList, int index, String compInstId, String compInstname, org.openecomp.sdc.be.model.Component origComponent, InputDefinition input) { @@ -642,7 +655,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } Map inputs = inputsDefinitions.stream().collect(Collectors.toMap( o -> o.getName(), o -> o)); - result = createInputsInGraph(inputs, component, user, inTransaction); + result = createInputsInGraph(inputs, component); } return result; @@ -669,7 +682,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } - public Either, ResponseFormat> createInputsInGraph(Map inputs, org.openecomp.sdc.be.model.Component component, User user, boolean inTransaction) { + public Either, ResponseFormat> createInputsInGraph(Map inputs, org.openecomp.sdc.be.model.Component component) { List resList = inputs.values().stream().collect(Collectors.toList()); Either, ResponseFormat> result = Either.left(resList); @@ -1212,7 +1225,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { propInput.setOwnerId(null); propInput.setParentUniqueId(null); - Either createInputRes = createInputForComponentInstance(component, origComponent,ci, inputsToCreate, propertiesToCreate, inputsValueToCreate, dataTypes, inputName, propInput, isInputValue); + Either createInputRes = createInputForComponentInstance(component, ci, inputsToCreate, propertiesToCreate, inputsValueToCreate, inputName, propInput, isInputValue); if (createInputRes.isRight()) { log.debug("Failed to create input of resource instance for id {} error {}", compInstId, createInputRes.right().value()); @@ -1235,7 +1248,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { 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, List inputsValueToCreate, Map dataTypes, String inputName, ComponentInstancePropInput propInput, boolean isInputValue) { + private Either createInputForComponentInstance(org.openecomp.sdc.be.model.Component component, ComponentInstance ci, Map inputsToCreate, List propertiesToCreate, List inputsValueToCreate, String inputName, ComponentInstancePropInput propInput, boolean isInputValue) { String propertiesName = propInput.getPropertiesName() ; PropertyDefinition selectedProp = propInput.getInput(); String[] parsedPropNames = propInput.getParsedPropNames(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java index 7b55a6988e..4a07120994 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java @@ -20,7 +20,12 @@ package org.openecomp.sdc.be.components.impl; -import fj.data.Either; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; + +import javax.annotation.Resource; + import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; @@ -34,10 +39,7 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import javax.annotation.Resource; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; +import fj.data.Either; @Component("policyTypeImportManager") public class PolicyTypeImportManager { 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 7a7148a6a1..73f72216d2 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,11 +22,8 @@ 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.exception.ResponseFormat; import org.springframework.stereotype.Component; -import fj.data.Either; - @Component("productComponentInstanceBusinessLogic") public class ProductComponentInstanceBusinessLogic extends ComponentInstanceBusinessLogic { 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 e16b34f389..ff26ced5c9 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,11 +20,16 @@ package org.openecomp.sdc.be.components.impl; -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; +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; @@ -57,14 +62,12 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; -import javax.servlet.ServletContext; -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 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") public class PropertyBusinessLogic extends BaseBusinessLogic { @@ -229,7 +232,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, "")); } for (PropertyDefinition property : properties) { - if (property.getUniqueId().equals(propertyId) && isPropertyBelongsToResource(property, resourceId)) { + if (property.getUniqueId().equals(propertyId) ) { Map propMap = new HashMap<>(); propMap.put(property.getName(), property); return Either.left(propMap.entrySet().iterator().next()); 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 1ab7ffb007..4924bd25a7 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 @@ -55,6 +55,8 @@ import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; 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.components.merge.resource.MergeResourceBLFactory; +import org.openecomp.sdc.be.components.merge.resource.MergeResourceBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.config.Configuration.VfModuleProperty; @@ -76,6 +78,7 @@ 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.CapabilityDefinition; +import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; @@ -97,7 +100,7 @@ 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.RelationshipInfo; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.Resource; @@ -127,7 +130,6 @@ 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.tosca.ToscaUtils; import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; import org.openecomp.sdc.be.user.IUserBusinessLogic; import org.openecomp.sdc.be.user.Role; @@ -215,6 +217,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { @Autowired private ApplicationDataTypeCache dataTypeCache; + @Autowired + private MergeResourceBLFactory mergeResourceBLFactory; + private Gson gson = new Gson(); public CsarOperation getCsarOperation() { @@ -539,20 +544,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } Map>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes.left().value(); try{ - result = updateResourceFromYaml(oldRresource, newRresource, updateResource, createdArtifacts, isUpdateYaml, yamlFileName, yamlFileContents, csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null); + result = updateResourceFromYaml(oldRresource, newRresource, updateResource, createdArtifacts, isUpdateYaml, yamlFileName, yamlFileContents, csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false); } finally { if (result == null || result.isRight()) { log.warn("operation failed. do rollback"); titanDao.rollback(); - if (!createdArtifacts.isEmpty()) { - StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts); - if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes); - result = Either.right(componentsUtils.getResponseFormat(actionStatus, oldRresource.getName())); - } - log.debug("component and all its artifacts were deleted, id = {}", oldRresource.getName()); - } } else { log.debug("operation success. do commit"); titanDao.commit(); @@ -566,7 +563,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { private Either updateResourceFromYaml(Resource oldRresource, Resource newRresource, AuditingActionEnum updateResource, List createdArtifacts, boolean isUpdateYaml, String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map nodeTypesInfo, - Map>> nodeTypesArtifactsToHandle, String nodeName) { + Map>> nodeTypesArtifactsToHandle, String nodeName, boolean isNested) { Either result; Either, ResponseFormat> parseNodeTypeInfoYamlEither; boolean inTransaction = true; @@ -586,7 +583,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (isUpdateYaml || !nodeTypesArtifactsToHandle.isEmpty()) { - prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), inTransaction, shouldLock); + prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), inTransaction, shouldLock, isNested); if (prepareForUpdate.isRight()) { log.debug("Failed to prepare resource for update : {}", prepareForUpdate.right().value()); result = Either.right(prepareForUpdate.right().value()); @@ -690,19 +687,35 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { preparedResource = createdCsarArtifactsEither.left().value(); } + ActionStatus mergingPropsAndInputsStatus = mergeResourceEntities(oldRresource, preparedResource); + if (mergingPropsAndInputsStatus != ActionStatus.OK) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, preparedResource); + return Either.right(responseFormat); + } + Either, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId()); result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(preparedResource); return result; } + + private ActionStatus mergeResourceEntities(Resource oldResource, Resource newResource) { + Either mergeResourceBLEither = mergeResourceBLFactory.getInstance(oldResource, newResource); + if (mergeResourceBLEither.isRight()) { + return mergeResourceBLEither.right().value(); + } + MergeResourceBusinessLogic mergeResourceBusinessLogic = mergeResourceBLEither.left().value(); + return mergeResourceBusinessLogic.mergeResourceEntities(oldResource, newResource); + } + private Either handleResourceGenericType(Resource resource) { Either genericResourceEither = fetchAndSetDerivedFromGenericType(resource); if (genericResourceEither.isRight()) { return genericResourceEither; } if (resource.shouldGenerateInputs()) { - generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value()); + generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value()); } return genericResourceEither; } @@ -715,18 +728,22 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { try { nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle); - Map extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo); + Map> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo); Either>, ResponseFormat> curNodeTypeArtifactsToHandleRes; EnumMap> curNodeTypeArtifactsToHandle = null; log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(), csarInfo.getCsarUUID()); - for (Entry currVfcToscaNameEntry : extractedVfcToscaNames.entrySet()) { - String currVfcToscaName = currVfcToscaNameEntry.getValue(); + for (Entry> currVfcToscaNameEntry : extractedVfcToscaNames.entrySet()) { + String currVfcToscaName = currVfcToscaNameEntry.getValue().getLeft(); + String previousVfcToscaName = currVfcToscaNameEntry.getValue().getRight(); String currNamespace = currVfcToscaNameEntry.getKey(); 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) { + curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(previousVfcToscaName); + } 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()), csarInfo.getCsarUUID()); @@ -925,15 +942,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return handleNodeTypeArtifactsRes; } - private Map extractVfcToscaNames(Map nodeTypesInfo, String vfResourceName, CsarInfo csarInfo) { - Map vfcToscaNames = new HashMap<>(); + private Map> extractVfcToscaNames(Map nodeTypesInfo, String vfResourceName, CsarInfo csarInfo) { + Map> vfcToscaNames = new HashMap<>(); Map nodes = extractAllNodes(nodeTypesInfo, csarInfo); if (!nodes.isEmpty()) { Iterator> nodesNameEntry = nodes.entrySet().iterator(); while (nodesNameEntry.hasNext()) { Entry nodeType = nodesNameEntry.next(); - String toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey()); + ImmutablePair toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey()); vfcToscaNames.put(nodeType.getKey(), toscaResourceName); } } @@ -1201,7 +1218,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { vfcCreated = handleNeatedVfcYaml.left().value(); } else if(csarInfo.getCreatedNodesToscaResourceNames()!= null && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())){ log.trace("************* Going to create node {}", nodeType.getKey()); - Either, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo); + Either, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true); log.debug("************* Finished to create node {}", nodeType.getKey()); if (resourceCreated.isRight()) { @@ -1257,11 +1274,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if(result == null){ newComplexVfc = buildCvfcRes.left().value(); Either oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName()); + if(oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND){ + oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getRight()); + } if(oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND){ log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value()); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } else if(oldComplexVfcRes.isLeft()){ - oldComplexVfc = oldComplexVfcRes.left().value(); + log.debug("validate derived before update"); + Either eitherValidation = validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion())); + if (eitherValidation.isLeft()) { + oldComplexVfc = oldComplexVfcRes.left().value(); + } } } if(result == null){ @@ -1298,7 +1322,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { log.debug("Failed to create resource {} from YAML {}. ", newComplexVfc.getName(), yamlName); } } else { - handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, true, yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName); + handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, true, yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true); if (handleComplexVfcRes.isRight()) { log.debug("Failed to update resource {} from YAML {}. ", oldComplexVfc.getName(), yamlName); } @@ -1335,13 +1359,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } private Either, ResponseFormat> createNodeTypeResourceFromYaml(String yamlName, Entry nodeNameValue, User user, Map mapToConvert, Resource resourceVf, boolean needLock, - Map> nodeTypeArtifactsToHandle, List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo) { + Map> nodeTypeArtifactsToHandle, List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, boolean isNested) { Either resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user); if (resourceMetaData.isRight()) { return Either.right(resourceMetaData.right().value()); } - String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.left().value().getResourceType(), csarInfo.getVfResourceName()); + String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.left().value().getResourceType(), csarInfo); Either eitherCreator = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true); if (eitherCreator.isRight()) { @@ -1349,10 +1373,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } user = eitherCreator.left().value(); - return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo); + return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested); } - private String buildNodeTypeYaml(Entry nodeNameValue, Map mapToConvert, String nodeResourceType, String csarVfName) { + private String buildNodeTypeYaml(Entry nodeNameValue, Map mapToConvert, String nodeResourceType, CsarInfo csarInfo) { // We need to create a Yaml from each node_types in order to create // resource from each node type using import normative flow. DumperOptions options = new DumperOptions(); @@ -1360,7 +1384,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Yaml yaml = new Yaml(options); Map node = new HashMap<>(); - node.put(buildNestedToscaResourceName(nodeResourceType, csarVfName, nodeNameValue.getKey()), nodeNameValue.getValue()); + node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()).getLeft(), nodeNameValue.getValue()); mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), node); return yaml.dumpAsMap(mapToConvert); @@ -1376,11 +1400,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } public Either, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock, - Map> nodeTypeArtifactsToHandle, List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo) { + Map> nodeTypeArtifactsToHandle, List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, boolean isNested) { 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, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo); + return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested); } private Either fillResourceMetadata(String yamlName, Resource resourceVf, String nodeName, User user) { @@ -1457,7 +1481,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { cvfc.setVendorName(resourceVf.getVendorName()); cvfc.setVendorRelease(resourceVf.getVendorRelease()); cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber()); - cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName)); + cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getLeft()); cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); List tags = new ArrayList<>(); @@ -1521,7 +1545,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { // add groups to resource log.trace("************* Going to add inputs from yaml {}", yamlName); if (resource.shouldGenerateInputs()) - generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value()); + generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value()); Map inputs = parsedToscaYamlInfo.getInputs(); Either createInputsOnResource = createInputsOnResource(resource, csarInfo.getModifier(), inputs, inTransaction); @@ -1599,11 +1623,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { 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); - return Either.right(componentsUtils.getResponseFormat(actionStatus, resource.getName())); - } log.debug("component and all its artifacts were deleted, id = {}", resource.getName()); } @@ -1720,7 +1739,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { List resourceProperties = resource.getInputs(); if ( (inputs != null && false == inputs.isEmpty()) || (resourceProperties != null && false == resourceProperties.isEmpty()) ) { - Either, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource, user, inTransaction); + Either, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource); if (createInputs.isRight()) { return Either.right(createInputs.right().value()); } @@ -2042,12 +2061,7 @@ 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 (String artifactId : artifactsToDelete) { Either, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null, null, shouldLock, inTransaction); @@ -2169,9 +2183,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { ////////////////////////////////////// create set parsed ////////////////////////////////////// artifacts/////////////////////////////////////////// Map> parsedArtifactsMap = parseResourceInfoFromYamlEither.left().value(); - Collection> parsedArifactsCollection = parsedArtifactsMap.values(); + Map> parsedGroup = new HashMap>(); - + List artifactsWithoutGroups = null; + if(parsedArtifactsMap.containsKey(ArtifactTemplateInfo.CSAR_ARTIFACT)){ + artifactsWithoutGroups = parsedArtifactsMap.get(ArtifactTemplateInfo.CSAR_ARTIFACT); + parsedArtifactsMap.remove(ArtifactTemplateInfo.CSAR_ARTIFACT); + } + Collection> parsedArifactsCollection = parsedArtifactsMap.values(); for (List parsedGroupTemplateList : parsedArifactsCollection) { for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) { @@ -2235,7 +2254,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { ////////////// artifacts//////////////////////////// Either assDissotiateEither = associateAndDissociateArtifactsToGroup(csarInfo, resource, createdNewArtifacts, labelCounter, shouldLock, inTransaction, createdDeplymentArtifactsAfterDelete, mergedgroup, deletedArtifacts); - + groups = resource.getGroups(); if (assDissotiateEither.isRight()) { log.debug("Failed to delete artifacts. Status is {} ", assDissotiateEither.right().value()); @@ -2251,7 +2270,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } - groups = resource.getGroups(); + // update vfModule names Set groupForAssociateWithMembers = mergedgroup.keySet(); @@ -2331,7 +2350,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } - + if(artifactsWithoutGroups != null && !artifactsWithoutGroups.isEmpty()){ + for(ArtifactTemplateInfo t: artifactsWithoutGroups){ + List arrtifacts = new ArrayList(); + arrtifacts.add(t); + Either resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, arrtifacts, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction); + if (resStatus.isRight()) + return resStatus; + }; + } + Either eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); if (eitherGerResource.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); @@ -2351,17 +2379,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { 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()); - */ - - } else { + if (artifactTypeEnum != ArtifactTypeEnum.HEAT_ENV) { Either, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resourceId, artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null, null, shouldLock, inTransaction); if (handleDelete.isRight()) { @@ -2425,8 +2443,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { GroupDefinition groupToUpdate = artifactsToUpdateEntry.getKey(); for (ImmutablePair artifact : artifactsToUpdateList) { - String prevUUID = artifact.getKey().getArtifactUUID(); + String prevUUID = artifact.getKey().getArtifactUUID(); String prevId = artifact.getKey().getUniqueId(); + String prevHeatEnvId = checkAndGetHeatEnvId(artifact.getKey()); Either updateArtifactEither = updateDeploymentArtifactsFromCsar(csarInfo, resource, artifact.getKey(), artifact.getValue(), updatedArtifacts, artifact.getRight().getRelatedArtifactsInfo(), shouldLock, inTransaction); if (updateArtifactEither.isRight()) { @@ -2441,6 +2460,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { groupToUpdate.getArtifacts().add(artAfterUpdate.getUniqueId()); groupToUpdate.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID()); } + Optional op = updatedArtifacts.stream().filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(artAfterUpdate.getUniqueId())).findAny(); + if (op.isPresent()) { + ArtifactDefinition artifactInfoHeatEnv = op.get(); + groupToUpdate.getArtifacts().remove(prevHeatEnvId); + groupToUpdate.getArtifacts().add(artifactInfoHeatEnv.getUniqueId()); + } + } } } @@ -2521,16 +2547,7 @@ 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; - * - * } } - */ + ComponentParametersView parametersView = new ComponentParametersView(); parametersView.disableAll(); @@ -3332,6 +3349,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return resStatus; } ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value(); + updatedArtifacts.add(currentInfo); Either updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, artifactTemplateInfo, currentInfo, true); if (updateEnvEither.isRight()) { @@ -3342,7 +3360,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { // TODO evg update env time ( must be separate US for this!!!!) updatedArtifacts.add(updateEnvEither.left().value()); - resStatus = Either.left(updateEnvEither.left().value()); + resStatus = Either.left(currentInfo); return resStatus; @@ -3359,11 +3377,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { 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(); @@ -3405,6 +3419,23 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } if (isUpdateEnv) { + ComponentParametersView parametersView = new ComponentParametersView(); + parametersView.disableAll(); + parametersView.setIgnoreComponentInstances(false); + parametersView.setIgnoreUsers(false); + parametersView.setIgnoreArtifacts(false); + parametersView.setIgnoreGroups(false); + + Either eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView); + + if (eitherGerResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); + + resStatus = Either.right(responseFormat); + return resStatus; + + } + resource = eitherGerResource.left().value(); Map artifacts = resource.getDeploymentArtifacts(); Optional op = artifacts.values().stream().filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId())).findAny(); if (op.isPresent()) { @@ -3414,6 +3445,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { 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()))); } + resStatus = Either.left(updateArifactOnResource.left().value()); } } return resStatus; @@ -3821,7 +3853,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { String value = null; List getInputs = null; boolean isValidate = true; - if (null != propertyInfo && null != propertyInfo.getValue()) { + if (propertyInfo.getValue() != null) { getInputs = propertyInfo.getGet_input(); isValidate = getInputs == null || getInputs.isEmpty(); if (isValidate) { @@ -3944,10 +3976,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } RequirementDefinition validReq = eitherReqStatus.left().value(); - List reqAndRelationshipPairList = regCapRelDef.getRelationships(); + List reqAndRelationshipPairList = regCapRelDef.getRelationships(); if (reqAndRelationshipPairList == null) - reqAndRelationshipPairList = new ArrayList(); - RequirementAndRelationshipPair reqAndRelationshipPair = new RequirementAndRelationshipPair(); + reqAndRelationshipPairList = new ArrayList<>(); + RelationshipInfo reqAndRelationshipPair = new RelationshipInfo(); reqAndRelationshipPair.setRequirement(regName); reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId()); reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId()); @@ -3982,7 +4014,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { reqAndRelationshipPair.setCapability(aviableCapForRel.getName()); reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId()); reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId()); - reqAndRelationshipPairList.add(reqAndRelationshipPair); + CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); + capReqRel.setRelation(reqAndRelationshipPair); + reqAndRelationshipPairList.add(capReqRel); regCapRelDef.setRelationships(reqAndRelationshipPairList); relations.add(regCapRelDef); } @@ -4151,8 +4185,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value())); } - // String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(currentCompInstance.getComponentUid(), index++); - // property.setUniqueId(uniqueId); property.setValue(validatevalueEiter.left().value()); if (getInputs != null && !getInputs.isEmpty()) { @@ -4239,18 +4271,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } - - // 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; - // } return cap; } @@ -4261,13 +4281,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { List capList = capMap.get(validReq.getCapability()); for (CapabilityDefinition cap : capList) { - // TODO temporary fix - remove specific capability node - // String reqNode = validReq.getNode(); - // if (reqNode != null && !reqNode.isEmpty()) { - // if (!cap.getCapabilitySources().contains(reqNode)) { - // continue; - // } - // } if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { String leftOccurrences = cap.getLeftOccurrences(); if (leftOccurrences == null) { @@ -5097,7 +5110,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); } */ - public Either, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo) { + public Either, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo, String nodeName, boolean isNested) { // check if resource already exist Either latestByName = toscaOperationFacade.getLatestByName(resource.getName()); @@ -5107,10 +5120,22 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { 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)) + if (csarInfo!= null && csarInfo.isUpdate() && nodeName != null && latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)){ + latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight()); + // update + if (latestByToscaName.isLeft()) { + log.debug("validate derived before update"); + Either eitherValidation = validateNestedDerivedFromDuringUpdate(latestByToscaName.left().value(), resource, ValidationUtils.hasBeenCertified(latestByToscaName.left().value().getVersion())); + if (eitherValidation.isRight()) { + result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); + } else { + result = updateExistingResourceByImport(resource, latestByToscaName.left().value(), user, isNormative, needLock, isNested); + } + } + } + if (result == null && latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)){ result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); - - else { + } else if (result == null){ StorageOperationStatus status = latestByName.right().value(); BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); log.debug("resource already exist {}. status={}", resource.getName(), status); @@ -5123,7 +5148,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { // update else if (latestByName.isLeft()) { - result = updateExistingResourceByImport(resource, latestByName.left().value(), user, isNormative, needLock); + result = updateExistingResourceByImport(resource, latestByName.left().value(), user, isNormative, needLock, isNested); } // error @@ -5160,7 +5185,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return latestByName.isLeft(); } - private Either, ResponseFormat> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock) { + private Either, ResponseFormat> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock, boolean isNested) { String lockedResourceId = oldResource.getUniqueId(); log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(), oldResource.getLifecycleState()); Either, ResponseFormat> result = null; @@ -5184,7 +5209,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { mergeOldResourceMetadataWithNew(oldResource, newResource); - Either validateFieldsResponse = validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction); + Either validateFieldsResponse = validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested); if (validateFieldsResponse.isRight()) { result = Either.right(validateFieldsResponse.right().value()); return result; @@ -5211,7 +5236,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { newResource.setSystemName(oldResource.getSystemName()); if (oldResource.getCsarUUID() != null) { newResource.setCsarUUID(oldResource.getCsarUUID()); - } + } if (oldResource.getImportedToscaChecksum() != null) { newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum()); } @@ -5957,7 +5982,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } //endregion - Either validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction); + Either validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false); if (validateResourceFields.isRight()) { return Either.right(validateResourceFields.right().value()); } @@ -6117,15 +6142,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { * validateResourceFieldsBeforeUpdate * * @param currentResource - Resource object to validate + * @param isNested * @return Either */ - private Either validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction) { + private Either validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) { boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion()); // validate resource name log.debug("validate resource name before update"); - Either eitherValidation = validateResourceName(currentResource, updateInfoResource, hasBeenCertified); + Either eitherValidation = validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested); if (eitherValidation.isRight()) { return eitherValidation; } @@ -6314,10 +6340,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return resourceName+"Cvfc"; } - private Either validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) { + private Either validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean isNested) { String resourceNameUpdated = updateInfoResource.getName(); if (!isResourceNameEquals(currentResource, updateInfoResource)) { - if (!hasBeenCertified) { + if (isNested || !hasBeenCertified) { Either validateResourceNameResponse = validateComponentName(null, updateInfoResource, null); if (validateResourceNameResponse.isRight()) { ResponseFormat errorResponse = validateResourceNameResponse.right().value(); @@ -6449,6 +6475,36 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } return Either.left(true); } + + private Either validateNestedDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) { + + List currentDerivedFrom = currentResource.getDerivedFrom(); + List updatedDerivedFrom = updateInfoResource.getDerivedFrom(); + if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) { + log.trace("Update normative types"); + return Either.left(true); + } + + String derivedFromCurrent = currentDerivedFrom.get(0); + String derivedFromUpdated = updatedDerivedFrom.get(0); + + if (!derivedFromCurrent.equals(derivedFromUpdated)) { + if (!hasBeenCertified) { + Either validateDerivedFromExistsEither = validateDerivedFromExist(null, updateInfoResource, null); + if (validateDerivedFromExistsEither.isRight()) { + return validateDerivedFromExistsEither; + } + } else { + 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; + } + } + } + return Either.left(true); + } private Either validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) { @@ -7309,9 +7365,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } - private String buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) { + private ImmutablePair buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) { String actualType; String actualVfName; + String actualPreviousVfName; if(ResourceTypeEnum.CVFC.name().equals(nodeResourceType)){ actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name(); actualType = ResourceTypeEnum.VFC.name(); @@ -7319,6 +7376,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { actualVfName = vfResourceName; actualType = nodeResourceType; } + StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); String nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); String[] findTypes = nameWithouNamespacePrefix.split("\\."); @@ -7330,7 +7388,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } else { toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT); } - return toscaResourceName.append(actualName.toLowerCase()).toString(); + StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName); + return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(), previousToscaResourceName.append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()).toString()); } public ICacheMangerOperation getCacheManagerOperation() { 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 b21195ff42..7ed90ce3b6 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 @@ -20,7 +20,22 @@ package org.openecomp.sdc.be.components.impl; -import fj.data.Either; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +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.regex.Pattern; +import java.util.stream.Collectors; + +import javax.servlet.ServletContext; + import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.auditing.api.IAuditingManager; @@ -38,7 +53,17 @@ 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.*; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.CsarInfo; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +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.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; @@ -57,20 +82,7 @@ import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; import org.yaml.snakeyaml.Yaml; -import javax.servlet.ServletContext; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -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.regex.Pattern; -import java.util.stream.Collectors; +import fj.data.Either; @Component("resourceImportManager") public class ResourceImportManager { @@ -110,7 +122,7 @@ public class ResourceImportManager { lifecycleChangeInfo.setUserRemarks("certification on import"); Function> validator = (resource) -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); - return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null); + return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false); } public Either, ResponseFormat> importNormativeResourceFromCsar(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) { @@ -119,11 +131,11 @@ public class ResourceImportManager { lifecycleChangeInfo.setUserRemarks("certification on import"); Function> validator = (resource) -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); - return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null); + return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false); } public Either, ResponseFormat> importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, Function> validationFunction, - LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map> nodeTypeArtifactsToHandle, List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo) { + LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map> nodeTypeArtifactsToHandle, List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, boolean isNested) { Resource resource = new Resource(); ImmutablePair responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED); Either, ResponseFormat> response = Either.left(responsePair); @@ -152,7 +164,7 @@ public class ResourceImportManager { } } - response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo); + response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, isNested); Either changeStateResponse; if (response.isLeft()) { resource = response.left().value().left; @@ -240,7 +252,7 @@ public class ResourceImportManager { Either validatePropertiesTypes = resourceBusinessLogic.validatePropertiesDefaultValues(resource); if (validatePropertiesTypes.isLeft()) { - response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, false, isInTransaction, true, null); + response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, false, isInTransaction, true, null, null, false); } else { ResponseFormat validationErrorResponse = validatePropertiesTypes.right().value(); auditErrorImport(resourceMetaData, creator, validationErrorResponse, false); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java index e8c0bf3d8a..136121484d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java @@ -20,13 +20,11 @@ package org.openecomp.sdc.be.components.impl; -import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.ErrorConfiguration; import org.openecomp.sdc.be.config.ErrorInfo; import org.openecomp.sdc.be.config.ErrorInfo.ErrorInfoType; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.exception.OkResponseInfo; import org.openecomp.sdc.exception.PolicyException; import org.openecomp.sdc.exception.ResponseFormat; @@ -60,7 +58,6 @@ public class ResponseFormatManager { ErrorConfiguration errorConfiguration = configurationManager.getErrorConfiguration(); ErrorInfo errorInfo = errorConfiguration.getErrorInfo(responseEnum.name()); if (errorInfo == null) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.EcompErrorNotFound, "ResponseFormatManager", responseEnum.name()); log.debug("failed to locate {} in error configuration", responseEnum.name()); errorInfo = errorConfiguration.getErrorInfo(ActionStatus.GENERAL_ERROR.name()); } 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 89c444b6d9..23852c30a2 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 @@ -23,7 +23,6 @@ package org.openecomp.sdc.be.components.impl; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; @@ -359,7 +358,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (genericServiceEither.isRight()) return Either.right(genericServiceEither.right().value()); - generateInputsFromGenericTypeProperties(service, genericServiceEither.left().value()); + generateAndAddInputsFromGenericTypeProperties(service, genericServiceEither.left().value()); Either dataModelResponse = toscaOperationFacade.createToscaComponent(service); @@ -711,7 +710,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { String uuidUpdated = serviceUpdate.getUUID(); String uuidCurrent = currentService.getUUID(); if (!uuidCurrent.equals(uuidUpdated)) { - log.info("update srvice: recived request to update uuid to {} the field is not updatable ignoring.", uuidUpdated); + log.info("update service: recived request to update uuid to {} the field is not updatable ignoring.", uuidUpdated); } response = validateAndUpdateServiceType(user, currentService, serviceUpdate, null); @@ -734,7 +733,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { serviceUpdate.setInvariantUUID(currentInvariantUuid); } validateAndUpdateEcompNaming(currentService, serviceUpdate); - + + currentService.setEnvironmentContext(serviceUpdate.getEnvironmentContext()); + return Either.left(currentService); } @@ -1508,7 +1509,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return vfModuleAertifact; } - private void fillVfModuleInstHeatEnvPayload(List groupsForCurrVF, ComponentInstance currVFInstance, Wrapper payloadWrapper) { + private void fillVfModuleInstHeatEnvPayload(List groupsForCurrVF, Wrapper payloadWrapper) { // Converts GroupDefinition to VfModuleArtifactPayload which is the // format used in the payload @@ -1531,37 +1532,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } - private void addHeatEnvArtifactsToVFModulePayload(VfModuleArtifactPayload vfModulePayload, ComponentInstance currVFInstance) { - 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()); - // Unique Id Of Artifacts In the vf module - List moduleArtUniqueId = depInsArtifacts.stream().filter(art -> originalModuleArtifacts.contains(art.getArtifactUUID())).map(art -> art.getUniqueId()).collect(Collectors.toList()); - // Collect Only Heat Artifatcs that are Generated from artifacts in - // the module - List relevantHeatEnvUUID = heatEnvArtifacts.stream().filter(heatEnv -> moduleArtUniqueId.contains(heatEnv.getGeneratedFromId())).map(heatEnv -> heatEnv.getArtifactUUID()).collect(Collectors.toList()); - - List fullArtifactList = new ArrayList<>(); - fullArtifactList.addAll(filteredUUIDFromModule); - fullArtifactList.addAll(relevantHeatEnvUUID); - - vfModulePayload.setArtifacts(fullArtifactList); - } - } - private Either generateVfModuleInstanceArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock) { ArtifactDefinition vfModuleAertifact = null; Wrapper responseWrapper = new Wrapper<>(); Wrapper payloadWrapper = new Wrapper<>(); List groupsForCurrVF = collectGroupsInstanceForCompInstance(currVFInstance, responseWrapper); if (responseWrapper.isEmpty()) { - fillVfModuleInstHeatEnvPayload(groupsForCurrVF, currVFInstance, payloadWrapper); + fillVfModuleInstHeatEnvPayload(groupsForCurrVF, payloadWrapper); } if (responseWrapper.isEmpty() && payloadWrapper.getInnerElement() != null) { vfModuleAertifact = getVfModuleInstArtifactForCompInstance(currVFInstance, service, modifier, groupsForCurrVF, payloadWrapper, responseWrapper); @@ -1694,7 +1671,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { @Override public Either call() throws Exception { - return artifactsBusinessLogic.generateHeatEnvArtifact(artifactDefinition, ComponentTypeEnum.RESOURCE_INSTANCE, service, resourceInstanceName, modifier, shouldLock, instanceId); + return artifactsBusinessLogic.forceGenerateHeatEnvArtifact(artifactDefinition, ComponentTypeEnum.RESOURCE_INSTANCE, service, resourceInstanceName, modifier, shouldLock, instanceId); } public ArtifactDefinition getArtifactDefinition() { 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 5a93ecf182..c5db7ee022 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 @@ -20,19 +20,12 @@ package org.openecomp.sdc.be.components.impl; -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.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.tosca.ToscaUtils; -import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; - @Component("vfComponentInstanceBusinessLogic") public class VFComponentInstanceBusinessLogic extends ComponentInstanceBusinessLogic { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java new file mode 100644 index 0000000000..7f6abe7f2c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java @@ -0,0 +1,91 @@ +package org.openecomp.sdc.be.components.impl.generic; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +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.InputDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import fj.data.Either; + +@org.springframework.stereotype.Component +public class GenericTypeBusinessLogic { + + private final static Logger log = LoggerFactory.getLogger(GenericTypeBusinessLogic.class); + + @Autowired + private ComponentsUtils componentsUtils; + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + + /** + * @param component the component of which to fetch its generic type + * @return the generic node type which corresponds to the given component + */ + public Either fetchDerivedFromGenericType(Component component){ + String genericTypeToscaName = getGenericTypeToscaName(component); + log.debug("Fetching generic tosca name {}", genericTypeToscaName); + if(null == genericTypeToscaName) { + log.debug("Failed to fetch certified generic node type for component {}", component.getName()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + Either findLatestGeneric = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(genericTypeToscaName); + if(findLatestGeneric.isRight()){ + log.debug("Failed to fetch certified node type by tosca resource name {}", genericTypeToscaName); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType(), genericTypeToscaName)); + } + + Resource genericTypeResource = findLatestGeneric.left().value(); + return Either.left(genericTypeResource); + } + + /** + * + * @param genericType the generic node type + * @return the generic type properties as inputs + */ + public List generateInputsFromGenericTypeProperties(Resource genericType) { + List genericTypeProps = genericType.getProperties(); + if(null != genericTypeProps) { + return convertGenericTypePropertiesToInputsDefintion(genericTypeProps, genericType.getUniqueId()); + } + return new ArrayList<>(); + } + + public 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; + } + + private String getGenericTypeToscaName(T component) { + return isCvfcHasDerivedFrom(component) ? ((Resource)component).getDerivedFrom().get(0) : component.fetchGenericTypeToscaNameFromConfig(); + } + + private boolean isCvfcHasDerivedFrom(T component) { + return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).getResourceType() == ResourceTypeEnum.CVFC && CollectionUtils.isNotEmpty(((Resource)component).getDerivedFrom()); + } + +} 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 0e0f6f9464..47e494f66d 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,6 +21,7 @@ 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; 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 d12afdbd55..4a7f446739 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 @@ -20,7 +20,14 @@ package org.openecomp.sdc.be.components.lifecycle; -import fj.data.Either; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; + import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; @@ -32,7 +39,15 @@ 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.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.*; +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.LifeCycleTransitionEnum; +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.datamodel.ToscaElement; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; @@ -48,14 +63,7 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; +import fj.data.Either; public class CertificationRequestTransition extends LifeCycleTransition { @@ -229,12 +237,12 @@ public class CertificationRequestTransition extends LifeCycleTransition { } finally { if (result == null || result.isRight()) { BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); - if (inTransaction == false) { + if (!inTransaction) { log.debug("operation failed. do rollback"); titanDao.rollback(); } } else { - if (inTransaction == false) { + if (!inTransaction) { log.debug("operation success. do commit"); titanDao.commit(); } 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 14f54e4c19..b7983b1174 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,10 +21,7 @@ package org.openecomp.sdc.be.components.lifecycle; import java.util.Arrays; -import java.util.Collection; import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -32,22 +29,17 @@ 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.elements.ComponentInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; 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.jsontitan.datamodel.TopologyTemplate; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementOperation; 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; @@ -108,11 +100,22 @@ public class CheckoutTransition extends LifeCycleTransition { } else { Component clonedComponent = ModelConverter.convertFromToscaElement(checkoutResourceResult.left().value()); + if ( checkoutResourceResult.left().value().getToscaType() == ToscaElementTypeEnum.NodeType ){ + Either upgradeToLatestDerived = componentBl.shouldUpgradeToLatestDerived(clonedComponent); + if (upgradeToLatestDerived.isRight() && ActionStatus.OK != upgradeToLatestDerived.right().value()){ + result = Either.right(componentUtils.getResponseFormat(upgradeToLatestDerived.right().value())); + return result; + } + if ( upgradeToLatestDerived.isLeft() ){ + //get resource after update derived + clonedComponent = upgradeToLatestDerived.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()) { + else if (upgradeToLatestGeneric.left().value() ) { StorageOperationStatus response = upgradeToLatestGenericData(clonedComponent); if (StorageOperationStatus.OK != response) { ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); 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 cc534bb694..87e8175960 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 @@ -145,10 +145,12 @@ public abstract class LifeCycleTransition { 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 + // this is only used in 2 cases + //1. 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 - if (lifecycleChangeInfo != null && lifecycleChangeInfo.getAction() != null && lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.CREATE_FROM_CSAR) { + //2. certification flow upno upgrade migration + if (lifecycleChangeInfo != null && lifecycleChangeInfo.getAction() != null && (lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.CREATE_FROM_CSAR|| lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.UPGRADE_MIGRATION)) { return Either.left(true); } 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 f0b369072e..e478bc6924 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 @@ -207,7 +207,7 @@ public class LifecycleBusinessLogic { LifecycleStateEnum resourceCurrState = component.getLifecycleState(); // lock resource - if (inTransaction == false && needLock) { + if (!inTransaction && needLock) { log.info("lock component {}", componentId); Either eitherLockResource = lockComponent(componentType, component); if (eitherLockResource.isRight()) { @@ -216,7 +216,7 @@ public class LifecycleBusinessLogic { log.error("lock component {} failed", componentId); return Either.right(errorResponse); } - log.info("after lock component {}", componentId); + log.debug("after lock component {}", componentId); } try { Either commentValidationResult = validateComment(changeInfo, transitionEnum); @@ -228,12 +228,12 @@ public class LifecycleBusinessLogic { return Either.right(errorResponse); } changeInfo.setUserRemarks(commentValidationResult.left().value()); - log.info("after validate component"); + log.debug("after validate component"); Either validateHighestVersion = validateHighestVersion(modifier, lifeCycleTransition, component, resourceCurrVersion, componentType); if (validateHighestVersion.isRight()) { return Either.right(validateHighestVersion.right().value()); } - log.info("after validate Highest Version"); + log.debug("after validate Highest Version"); if (isComponentVFCMT(component,componentType)){ Either changeVFCMTStateResponse = changeVFCMTState(componentType, modifier, transitionEnum, changeInfo, inTransaction, component); if (changeVFCMTStateResponse.isRight()){ @@ -243,11 +243,11 @@ public class LifecycleBusinessLogic { return changeState(component, lifeCycleTransition, componentType, modifier, changeInfo, inTransaction); } finally { - log.info("unlock component {}", componentId); - if (inTransaction == false && needLock && component != null) { - component.setUniqueId(componentId); + component.setUniqueId(componentId); + if (!inTransaction && needLock) { + log.info("unlock component {}", componentId); NodeTypeEnum nodeType = componentType.getNodeType(); - log.info("During change state, another component {} has been created/updated", componentId); + log.info("During change state, another component {} has been created/updated", componentId); graphLockOperation.unlockComponent(componentId, nodeType); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java index 170e187f15..5d8b29ecdc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java @@ -23,7 +23,7 @@ package org.openecomp.sdc.be.components.lifecycle; public class LifecycleChangeInfoWithAction extends LifecycleChangeInfoBase { public enum LifecycleChanceActionEnum { - CREATE_FROM_CSAR, UPDATE_FROM_EXTERNAL_API + CREATE_FROM_CSAR, UPDATE_FROM_EXTERNAL_API, UPGRADE_MIGRATION }; private LifecycleChanceActionEnum action; 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 24266521c2..b74ae5d8e5 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 @@ -20,7 +20,8 @@ package org.openecomp.sdc.be.components.lifecycle; -import fj.data.Either; +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; @@ -43,7 +44,7 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Arrays; +import fj.data.Either; public class StartCertificationTransition extends LifeCycleTransition { 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 277cd173aa..324e46016f 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,6 +21,7 @@ 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; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java new file mode 100644 index 0000000000..9c140b36c7 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java @@ -0,0 +1,36 @@ +package org.openecomp.sdc.be.components.merge; + +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import org.openecomp.sdc.be.components.impl.BaseBusinessLogic; +import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.springframework.stereotype.Component; + +import fj.data.Either; + +@Component +public class GlobalInputsFilteringBusinessLogic extends BaseBusinessLogic { + + @javax.annotation.Resource + private GenericTypeBusinessLogic genericTypeBusinessLogic; + + Either, ActionStatus> filterGlobalInputs(Resource newResource) { + Either genericComp = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(newResource.fetchGenericTypeToscaNameFromConfig()); + return genericComp.bimap(genericResource -> findCommonInputs(genericResource, newResource), + storageOperationStatus -> componentsUtils.convertFromStorageResponse(storageOperationStatus)); + } + + private List findCommonInputs(Resource genericResource, Resource resource) { + List resourceInputs = resource.getInputs(); + List genericInputs = genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericResource); + Set genericInputsNames = genericInputs.stream().map(InputDefinition::getName).collect(Collectors.toSet()); + return resourceInputs.stream().filter(input -> genericInputsNames.contains(input.getName())).collect(Collectors.toList()); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogic.java new file mode 100644 index 0000000000..eb359e949e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogic.java @@ -0,0 +1,41 @@ +package org.openecomp.sdc.be.components.merge; + +import java.util.List; + +import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL; +import org.openecomp.sdc.be.components.merge.resource.MergeResourceBusinessLogic; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import fj.data.Either; + +@Component +public class GlobalTypesMergeBusinessLogic implements MergeResourceBusinessLogic { + + private static final Logger LOGGER = LoggerFactory.getLogger(GlobalTypesMergeBusinessLogic.class); + + @javax.annotation.Resource + private GlobalInputsFilteringBusinessLogic globalInputsFilteringBusinessLogic; + + @javax.annotation.Resource + private ComponentInputsMergeBL inputsValuesMergeBL; + + @Override + public ActionStatus mergeResourceEntities(Resource oldResource, Resource newResource) { + if (oldResource == null) { + return ActionStatus.OK; + } + Either, ActionStatus> globalInputsEither = globalInputsFilteringBusinessLogic.filterGlobalInputs(newResource); + if (globalInputsEither.isRight()) { + LOGGER.error("failed to get global inputs of resource {} status is {}", newResource.getUniqueId(), globalInputsEither.right().value()); + return globalInputsEither.right().value(); + } + List globalInputs = globalInputsEither.left().value(); + return inputsValuesMergeBL.mergeComponentInputs(oldResource, newResource, globalInputs); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java new file mode 100644 index 0000000000..6c20e501f9 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java @@ -0,0 +1,95 @@ +package org.openecomp.sdc.be.components.merge; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.RelationshipInfo; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.Resource; +import org.springframework.stereotype.Component; + +@Component +public class RelationsComparator { + + /** + * + * @param oldResource the old resource + * @param newResource the new resource + * @return true if there was a change in one of the relations between the old and new resource + * a change in relation is determine by comparing the relations type, node, capability and requirement name + */ + public boolean isRelationsChanged(Resource oldResource, Resource newResource) { + Map> oldRelationsByInstance = oldResource.groupRelationsByInstanceName(oldResource); + Map> newRelationsByInstance = newResource.groupRelationsByInstanceName(newResource); + for (Map.Entry> relationByInst : newRelationsByInstance.entrySet()) { + List oldRelations = oldRelationsByInstance.get(relationByInst.getKey()); + List newRelations = relationByInst.getValue(); + if (isInstanceRelationsChanged(oldResource, oldRelations, newResource, newRelations)) { + return true; + } + } + return false; + + } + + private boolean isInstanceRelationsChanged(Resource oldResource, List oldRelations, Resource newResource, List newRelations) { + if (oldRelations == null || oldRelations.size() != newRelations.size()){ + return true; + } + return newRelations.stream().anyMatch(newRelation -> !findRelation(oldResource, oldRelations, newResource, newRelation)); + } + + + + private boolean findRelation(Resource oldResource, List oldRelations, Resource newResource, RequirementCapabilityRelDef newRelation) { + for (RequirementCapabilityRelDef oldRelation : oldRelations) { + RelationshipInfo oldRelationship = oldRelation.getSingleRelationship().getRelation(); + RelationshipInfo newRelationship = newRelation.getSingleRelationship().getRelation(); + if (oldRelationship != null && newRelationship != null && isRelationEqual(oldRelationship, newRelationship) && isRelationToNodeEquals(oldResource, oldRelation, newResource, newRelation)) { + return true; + } + } + return false; + } + + private boolean isRelationToNodeEquals(Resource oldResource, RequirementCapabilityRelDef oldRelation, Resource newResource, RequirementCapabilityRelDef newRelation) { + String oldToNodeId = oldRelation.getToNode(); + String newToNodeId = newRelation.getToNode(); + Optional oldRelationToNode = oldResource.getComponentInstanceById(oldToNodeId); + Optional newRelationToNode = newResource.getComponentInstanceById(newToNodeId); + return oldRelationToNode.isPresent() && newRelationToNode.isPresent() && oldRelationToNode.get().getName().equals(newRelationToNode.get().getName()); + } + + private boolean isRelationEqual(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) { + return isRelationshipTypeEquals(oldRelationship, newRelationship) && + isRelationshipCapabilityEquals(oldRelationship, newRelationship) && + isRelationshipReqNameEquals(oldRelationship, newRelationship); + } + + private boolean isRelationshipCapabilityEquals(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) { + if(oldRelationship.getCapabilityUid() !=null && newRelationship.getCapabilityUid() != null){ + return oldRelationship.getCapabilityUid().equals(newRelationship.getCapabilityUid()); + } + else if(oldRelationship.getCapabilityUid() == null && newRelationship.getCapabilityUid() == null){ + return true; + } + return false; + } + + private boolean isRelationshipTypeEquals(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) { + return oldRelationship.getRelationship().getType().equals(newRelationship.getRelationship().getType()); + } + + private boolean isRelationshipReqNameEquals(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) { + if(oldRelationship.getRequirement() != null && newRelationship.getRequirement() != null){ + return oldRelationship.getRequirement().equals(newRelationship.getRequirement()); + } + else if(oldRelationship.getRequirement() == null && newRelationship.getRequirement() == null){ + return true; + } + return false; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java new file mode 100644 index 0000000000..8b48b0897a --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java @@ -0,0 +1,105 @@ +package org.openecomp.sdc.be.components.merge; + +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.exception.SdcActionException; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import fj.data.Either; + +@org.springframework.stereotype.Component +public class TopologyComparator { + + public static final Logger LOGGER = LoggerFactory.getLogger(TopologyComparator.class); + + @javax.annotation.Resource + private RelationsComparator relationsComparator; + + @javax.annotation.Resource + private ToscaOperationFacade toscaOperationFacade; + + @javax.annotation.Resource + private ComponentsUtils componentsUtils; + + /** + * + * @param oldResource the old version of the resource of which to check for topology change + * @param newResource the new version of the resource of which to check for topology change + * @return true if there was a topology change between the old resource and new resource or false otherwise + * in case the action to find topology change failed, an appropriate {@link ActionStatus} will be returned + */ + public Either isTopologyChanged(Resource oldResource, Resource newResource) { + List oldInstances = oldResource.getComponentInstances(); + List newInstances = newResource.getComponentInstances(); + if (oldInstances != null && newInstances == null || oldInstances == null && newInstances != null) { + return Either.left(true); + } + if (oldInstances == null && newInstances == null) { + return Either.left(false); + } + Map oldInstancesByName = MapUtil.toMap(oldInstances, ComponentInstance::getName); + Map newInstancesByName = MapUtil.toMap(newInstances, ComponentInstance::getName); + return isTopologyInstancesChanged(oldResource, newResource, oldInstancesByName, newInstancesByName); + } + + private Either isTopologyInstancesChanged(Resource oldResource, Resource newResource, Map oldInstancesByName, Map newInstancesByName) { + try { + boolean isTopologyChanged = isInstanceNamesChanged(oldInstancesByName, newInstancesByName) || + isInstanceTypesChanged(oldInstancesByName, newInstancesByName) || + relationsComparator.isRelationsChanged(oldResource, newResource); + return Either.left(isTopologyChanged); + } catch (SdcActionException e) { + LOGGER.error("failed to merge entities of previous resource %s to current resource %s. reason: %s", oldResource.getUniqueId(), newResource.getUniqueId(), e.getActionStatus(), e); + return Either.right(e.getActionStatus()); + } + } + + private boolean isInstanceTypesChanged(Map oldInstancesByName, Map newInstancesByName) { + for (Map.Entry instanceByName : newInstancesByName.entrySet()) { + ComponentInstance oldInstance = oldInstancesByName.get(instanceByName.getKey()); + if (!isSameToscaTypeOrOriginComponent(oldInstance, instanceByName.getValue())) { + return true; + } + } + return false; + } + + private boolean isInstanceNamesChanged(Map oldInstanceByName, Map newInstancesByName) { + return !oldInstanceByName.keySet().equals(newInstancesByName.keySet()); + } + + private boolean isSameToscaTypeOrOriginComponent(ComponentInstance oldInstance, ComponentInstance newInstance) { + return isSameToscaType(oldInstance, newInstance) || + isSameOriginComponent(oldInstance, newInstance); + } + + private boolean isSameToscaType(ComponentInstance oldInstance, ComponentInstance newInstance) { + return oldInstance.getToscaComponentName().equals(newInstance.getToscaComponentName()); + } + + private boolean isSameOriginComponent(ComponentInstance oldInstance, ComponentInstance newInstance) { + if (oldInstance.getComponentUid().equals(newInstance.getComponentUid())) { + return true; + } + Component oldOriginCmpt = toscaOperationFacade.getToscaElement(oldInstance.getComponentUid()).left().on(storageStatus -> throwSdcActionException(storageStatus, oldInstance)); + Component newOriginCmpt = toscaOperationFacade.getToscaElement(newInstance.getComponentUid()).left().on(storageStatus -> throwSdcActionException(storageStatus, newInstance)); + return oldOriginCmpt.getInvariantUUID().equals(newOriginCmpt.getInvariantUUID()); + } + + private Component throwSdcActionException(StorageOperationStatus storageOperationStatus, ComponentInstance cmptInstance) { + LOGGER.error("failed to fetch origin node type %s for instance %s", cmptInstance.getUniqueId(), cmptInstance.getComponentUid()); + throw new SdcActionException(componentsUtils.convertFromStorageResponse(storageOperationStatus)); + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java new file mode 100644 index 0000000000..1e1bc862cf --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java @@ -0,0 +1,64 @@ +package org.openecomp.sdc.be.components.merge.heat; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.HeatParameterDefinition; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; + +/** + * Created by chaya on 9/14/2017. + */ +@Component +public class HeatEnvArtifactsMergeBusinessLogic { + + public List mergeInstanceHeatEnvArtifacts(List origHeatEnvArtifacts, List newHeatEnvArtifacts) { + Map origArtifactDefinitionByLabel = MapUtil.toMap(origHeatEnvArtifacts, ArtifactDefinition::getArtifactLabel); + List artifactsToUpdate = new ArrayList<>(); + newHeatEnvArtifacts.stream() + .filter(heatEnvArtifact -> origArtifactDefinitionByLabel.containsKey(heatEnvArtifact.getArtifactLabel())) + .forEach(heatEnvArtifact -> { + ArtifactDefinition origHeatEnvArtifact = origArtifactDefinitionByLabel.get(heatEnvArtifact.getArtifactLabel()); + Boolean wasMergedHeatEnvArtifact = mergeHeatEnvArtifactsParameters(heatEnvArtifact, origHeatEnvArtifact); + if (wasMergedHeatEnvArtifact) { + artifactsToUpdate.add(heatEnvArtifact); + } + }); + return artifactsToUpdate; + } + + private Boolean mergeHeatEnvArtifactsParameters(ArtifactDefinition currArtifact, ArtifactDefinition origArtifact) { + List currentHeatEnvParams = currArtifact.getListHeatParameters(); + List origHeatEnvParams = origArtifact.getListHeatParameters(); + boolean wasChanged = false; + + if (CollectionUtils.isEmpty(origHeatEnvParams) || CollectionUtils.isEmpty(currentHeatEnvParams)) { + return false; + } + + Map origHeatParametersByName = MapUtil.toMap(origHeatEnvParams, HeatParameterDefinition::getName); + + for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { + String paramName = currHeatParam.getName(); + HeatParameterDefinition origHeatParam = origHeatParametersByName.get(paramName); + if (isSameHeatWithDiffValue(origHeatParam, currHeatParam)) { + currHeatParam.setCurrentValue(origHeatParam.getCurrentValue()); + wasChanged = true; + } + } + currArtifact.setListHeatParameters(currentHeatEnvParams); + return wasChanged; + } + + private boolean isSameHeatWithDiffValue(HeatParameterDefinition origHeatParam, HeatParameterDefinition newHeatParam) { + return origHeatParam != null && + origHeatParam.getCurrentValue() != null && + origHeatParam.getType().equals(newHeatParam.getType()) && + !origHeatParam.getCurrentValue().equals(newHeatParam.getCurrentValue()); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java new file mode 100644 index 0000000000..b8ea5e35c4 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java @@ -0,0 +1,60 @@ +package org.openecomp.sdc.be.components.merge.input; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.utils.MapUtil; +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.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import fj.data.Either; + +@org.springframework.stereotype.Component +public class ComponentInputsMergeBL { + + @javax.annotation.Resource + private InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic; + + @javax.annotation.Resource + private ToscaOperationFacade toscaOperationFacade; + + @javax.annotation.Resource + private ComponentsUtils componentsUtils; + + public ActionStatus mergeAndRedeclareComponentInputs(Component prevComponent, Component newComponent, List inputsToMerge) { + mergeInputs(prevComponent, inputsToMerge); + List previouslyDeclaredInputs = inputsValuesMergingBusinessLogic.getPreviouslyDeclaredInputsToMerge(prevComponent, newComponent); + inputsToMerge.addAll(previouslyDeclaredInputs); + return updateInputs(newComponent.getUniqueId(), inputsToMerge); + } + + public ActionStatus mergeComponentInputs(Component prevComponent, Component newComponent, List inputsToMerge) { + mergeInputs(prevComponent, inputsToMerge); + return updateInputs(newComponent.getUniqueId(), inputsToMerge); + } + + public ActionStatus redeclareComponentInputsForInstance(List oldInputs, Component newComponent, String instanceId) { + List previouslyDeclaredInputs = inputsValuesMergingBusinessLogic.getPreviouslyDeclaredInputsToMerge(oldInputs, newComponent, instanceId); + return updateInputs(newComponent.getUniqueId(), previouslyDeclaredInputs); + } + + private void mergeInputs(Component prevComponent, List inputsToMerge) { + Map oldInputsByName = prevComponent.getInputs() == null ? Collections.emptyMap() : MapUtil.toMap(prevComponent.getInputs(), InputDefinition::getName); + Map inputsToMergeByName = MapUtil.toMap(inputsToMerge, InputDefinition::getName); + inputsValuesMergingBusinessLogic.mergeComponentInputs(oldInputsByName, inputsToMergeByName); + } + + private ActionStatus updateInputs(String containerId, List inputsToUpdate) { + Either, StorageOperationStatus> updateInputsEither = toscaOperationFacade.updateInputsToComponent(inputsToUpdate, containerId); + if (updateInputsEither.isRight()) { + return componentsUtils.convertFromStorageResponse(updateInputsEither.right().value()); + } + return ActionStatus.OK; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java new file mode 100644 index 0000000000..e49d2b2c87 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java @@ -0,0 +1,180 @@ +package org.openecomp.sdc.be.components.merge.input; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.commons.lang.StringUtils; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.InputDefinition; + +@org.springframework.stereotype.Component +public class InputsValuesMergingBusinessLogic { + + /** + * Merge old inputs values into the updated inputs + * An input value is merged if the input previous version had a user defined value and its value is empty in current version + * @param oldInputs the currently persisted inputs mapped by their names + * @param updatedInputs the currently being update inputs mapped by their names + */ + public void mergeComponentInputs(Map oldInputs, Map updatedInputs) { + updatedInputs.forEach((inputName, input) -> mergeInputsValues(oldInputs.get(inputName), input)); + } + + /** + * @param oldComponent the old state of {@link Component} that is being updated + * @param newComponent the new state of {@link Component} that is being updated + * @return a list of all inputs that were previously declared and need to be merged to the updating component + * An input needs to merged if a property was declared as an input (by the user) in previous component version and the declared input not exist in new version + */ + public List getPreviouslyDeclaredInputsToMerge(Component oldComponent, Component newComponent) { + if (oldComponent == null || oldComponent.getInputs() == null || newComponent == null ) { + return Collections.emptyList(); + } + Map> getInputProperties = getAllGetInputPropertyData(newComponent); + List inputsToRedeclareData = buildRedeclareInputData(newComponent, getInputProperties); + return findPrevDeclaredInputs(oldComponent.getInputs(), inputsToRedeclareData); + } + + /** + * @param oldInputs list of previous inputs to find inputs to redeclare from + * @param newComponent the new state of {@link Component} that is being updated + * @param instanceId instance id + * @return a list of all inputs that were previously declared and need to be merged to the updating component + * An input needs to merged if an instance property was declared as an input (by the user) in previous component version and the declared input not exist in new version + */ + public List getPreviouslyDeclaredInputsToMerge(List oldInputs, Component newComponent, String instanceId) { + if (oldInputs == null || newComponent == null ) { + return Collections.emptyList(); + } + Map> getInputProperties = getAllGetInputPropertyData(newComponent, instanceId); + List inputsToRedeclareData = buildRedeclareInputData(newComponent, getInputProperties); + return findPrevDeclaredInputs(oldInputs, inputsToRedeclareData); + } + + private List findPrevDeclaredInputs(List oldInputs, List inputsToRedeclareData) { + Map oldInputsById = MapUtil.toMap(oldInputs, InputDefinition::getUniqueId); + List inputsToRedeclare = new ArrayList<>(); + inputsToRedeclareData.forEach(redeclareInputData -> { + List inputDefinitions = prepareInputsForRedeclaration(oldInputsById, redeclareInputData); + inputsToRedeclare.addAll(inputDefinitions); + }); + return inputsToRedeclare; + } + + private List prepareInputsForRedeclaration(Map oldInputsById, RedeclareInputData redeclareInputData) { + List inputsForRedeclaration = redeclareInputData.declaredInputIds.stream().map(oldInputsById::get).collect(Collectors.toList()); + inputsForRedeclaration.forEach(input -> { + input.setPropertyId(redeclareInputData.propertyId); + input.setInstanceUniqueId(redeclareInputData.instanceId); + }); + return inputsForRedeclaration; + } + + private Map> findGetInputPropsDefinitions(Map> instancesPropDefinitions) { + Map> getInputProps = new HashMap<>(); + if (instancesPropDefinitions == null) { + return getInputProps; + } + return instancesPropDefinitions.entrySet() + .stream() + .collect(Collectors.toMap(Map.Entry::getKey, + entry -> this.filterGetInputProps(entry.getValue()))); + } + + private List filterGetInputProps(List propDefinitions) { + return propDefinitions + .stream() + .filter(PropertyDataDefinition::isGetInputProperty) + .collect(Collectors.toList()); + } + + private void mergeInputsValues(InputDefinition oldInput, InputDefinition updatedInput) { + if (shouldMergeOldValue(oldInput, updatedInput)) { + updatedInput.setDefaultValue(oldInput.getDefaultValue()); + } + } + + private boolean shouldMergeOldValue(InputDefinition oldInput, InputDefinition newInput) { + return isNonEmptyDefaultValue(oldInput) && isEmptyDefaultValue(newInput) && isSameType(oldInput, newInput); + } + + private boolean isSameType(InputDefinition oldInput, InputDefinition updatedInput) { + return oldInput.typeEquals(updatedInput); + } + + private boolean isEmptyDefaultValue(InputDefinition input) { + return input != null && StringUtils.isEmpty(input.getDefaultValue()); + } + + private boolean isNonEmptyDefaultValue(InputDefinition input) { + return input != null && !isEmptyDefaultValue(input); + } + + private List buildRedeclareInputData(Component newComponent, Map> getInputProperties) { + Map inputsById = MapUtil.toMap(newComponent.getInputs(), InputDefinition::getUniqueId); + List redeclareInputData = new ArrayList<>(); + getInputProperties.forEach((instanceId, getInputProps) -> { + redeclareInputData.addAll(findInputsToRedeclare(inputsById, instanceId, getInputProps)); + }); + return redeclareInputData; + + } + + private Map> getAllGetInputPropertyData(Component newComponent) { + Map> getInputInstanceProps = findGetInputPropsDefinitions(newComponent.getComponentInstancesProperties()); + Map> getInputInstanceInputs = findGetInputPropsDefinitions(newComponent.getComponentInstancesInputs()); + getInputInstanceInputs.putAll(getInputInstanceProps); + return getInputInstanceInputs; + } + + private Map> getAllGetInputPropertyData(Component newComponent, String instanceId) { + List getInputInstanceProps = this.filterGetInputProps(newComponent.safeGetComponentInstanceProperties(instanceId)); + List getInputInstanceInputs = this.filterGetInputProps(newComponent.safeGetComponentInstanceInput(instanceId)); + getInputInstanceInputs.addAll(getInputInstanceProps); + return Collections.singletonMap(instanceId, getInputInstanceInputs); + } + + private List findInputsToRedeclare(Map inputsById, String instanceId, List getInputProps) { + List redeclareInputDataList = new ArrayList<>(); + getInputProps.forEach(property -> { + List inputsToRedeclareIds = findInputsToRedeclareIds(inputsById, property); + RedeclareInputData redeclareInputData = new RedeclareInputData(property.getUniqueId(), inputsToRedeclareIds, instanceId); + redeclareInputDataList.add(redeclareInputData); + }); + return redeclareInputDataList; + } + + private List findInputsToRedeclareIds(Map inputsById, PropertyDataDefinition property) { + List getInputValues = property.getGetInputValues(); + return getInputValues.stream() + .filter(getInputVal -> getInputValueWithNoCorrespondingInput(getInputVal, inputsById)) + .map(GetInputValueDataDefinition::getInputId) + .collect(Collectors.toList()); + } + + private boolean getInputValueWithNoCorrespondingInput(GetInputValueDataDefinition getInputVal, Map inputsById) { + return !inputsById.containsKey(getInputVal.getInputId()); + } + + private class RedeclareInputData { + private String propertyId; + private List declaredInputIds; + private String instanceId; + + public RedeclareInputData(String propertyId, List declaredInputIds, String instanceId) { + this.propertyId = propertyId; + this.declaredInputIds = declaredInputIds; + this.instanceId = instanceId; + } + + } + + +} \ No newline at end of file diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java new file mode 100644 index 0000000000..cac8c977e3 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java @@ -0,0 +1,101 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +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.Operation; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.beans.factory.annotation.Autowired; + +import fj.data.Either; + +/** + * Created by chaya on 9/20/2017. + */ +@org.springframework.stereotype.Component("ComponentInstanceArtifactsMerge") +public class ComponentInstanceArtifactsMerge implements ComponentInstanceMergeInterface { + + @Autowired + ToscaOperationFacade toscaOperationFacade; + + @Autowired + ArtifactsBusinessLogic artifactsBusinessLogic; + + @Override + public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) { + Map componentInstancesDeploymentArtifacts = currentResourceInstance.safeGetDeploymentArtifacts(); + Map originalComponentDeploymentArtifacts = originComponent.getDeploymentArtifacts(); + Map deploymentArtifactsCreatedOnTheInstance = componentInstancesDeploymentArtifacts.entrySet() + .stream() + .filter(i -> !originalComponentDeploymentArtifacts.containsKey(i.getKey())) + .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue())); + + dataHolder.setOrigComponentDeploymentArtifactsCreatedOnTheInstance(deploymentArtifactsCreatedOnTheInstance); + + Map componentInstancesInformationalArtifacts = currentResourceInstance.safeGetArtifacts(); + Map originalComponentInformationalArtifacts = originComponent.getArtifacts(); + Map informationalArtifactsCreatedOnTheInstance = componentInstancesInformationalArtifacts.entrySet() + .stream() + .filter(i -> !originalComponentInformationalArtifacts.containsKey(i.getKey())) + .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue())); + dataHolder.setOrigComponentInformationalArtifactsCreatedOnTheInstance(informationalArtifactsCreatedOnTheInstance); + } + + private void addEsIdToArtifactJson(Map artifactJson, String origEsId) { + artifactJson.put(Constants.ARTIFACT_ES_ID, origEsId); + } + + @Override + public Either mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) { + Map origInstanceDeploymentArtifactsCreatedOnTheInstance = dataHolder.getOrigComponentDeploymentArtifactsCreatedOnTheInstance(); + Map currentInstanceDeploymentArtifacts = updatedContainerComponent.safeGetComponentInstanceDeploymentArtifacts(newInstanceId); + Map filteredDeploymentArtifactsToAdd = Optional.ofNullable(origInstanceDeploymentArtifactsCreatedOnTheInstance).orElse(new HashMap<>()).entrySet().stream() + .filter(artifact -> noArtifactWithTheSameLabel(artifact.getValue().getArtifactLabel(), currentInstanceDeploymentArtifacts)) + .collect(Collectors.toMap(p -> p.getKey(), q -> q.getValue())); + Map origInstanceInformationalArtifactsCreatedOnTheInstance = dataHolder.getOrigComponentInformationalArtifactsCreatedOnTheInstance(); + Map currentInstanceInformationalArtifacts = updatedContainerComponent.safeGetComponentInstanceInformationalArtifacts(newInstanceId); + Map filteredInformationalArtifactsToAdd = Optional.ofNullable(origInstanceInformationalArtifactsCreatedOnTheInstance).orElse(new HashMap<>()).entrySet().stream() + .filter(artifact -> noArtifactWithTheSameLabel(artifact.getValue().getArtifactLabel(), currentInstanceInformationalArtifacts)) + .collect(Collectors.toMap(p -> p.getKey(), q -> q.getValue())); + Map allFilteredArtifactsToAdd = new HashMap<>(); + allFilteredArtifactsToAdd.putAll(filteredDeploymentArtifactsToAdd); + allFilteredArtifactsToAdd.putAll(filteredInformationalArtifactsToAdd); + + for (Map.Entry currentArtifactDefinition : allFilteredArtifactsToAdd.entrySet()) { + Map jsonForUpdateArtifact = artifactsBusinessLogic.buildJsonForUpdateArtifact( + currentArtifactDefinition.getValue().getUniqueId(), currentArtifactDefinition.getValue().getArtifactName(), + currentArtifactDefinition.getValue().getArtifactType(), currentArtifactDefinition.getValue().getArtifactGroupType(), + currentArtifactDefinition.getValue().getArtifactLabel(), currentArtifactDefinition.getValue().getArtifactDisplayName(), + currentArtifactDefinition.getValue().getDescription(), currentArtifactDefinition.getValue().getPayloadData(), + null, currentArtifactDefinition.getValue().getListHeatParameters()); + addEsIdToArtifactJson(jsonForUpdateArtifact, currentArtifactDefinition.getValue().getEsId()); + Either, ResponseFormat> uploadArtifactToService = + artifactsBusinessLogic.updateResourceInstanceArtifactNoContent(newInstanceId, updatedContainerComponent, + user, jsonForUpdateArtifact, artifactsBusinessLogic.new ArtifactOperationInfo( + false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.Link), currentArtifactDefinition.getValue()); + if (uploadArtifactToService.isRight()) { + return Either.right(uploadArtifactToService.right().value()); + } + toscaOperationFacade.commit(); + } + return Either.left(updatedContainerComponent); + } + + private boolean noArtifactWithTheSameLabel(String artifactLabel, Map currDeploymentArtifacts) { + for (Map.Entry artifact : currDeploymentArtifacts.entrySet()) { + if (artifact.getValue().getArtifactLabel().equals(artifactLabel)) { + return false; + } + } + return true; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java new file mode 100644 index 0000000000..1561cdc797 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java @@ -0,0 +1,63 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.components.merge.heat.HeatEnvArtifactsMergeBusinessLogic; +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.Operation; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import fj.data.Either; + +/** + * Created by chaya on 9/20/2017. + */ +@org.springframework.stereotype.Component("ComponentInstanceHeatEnvMerge") +public class ComponentInstanceHeatEnvMerge implements ComponentInstanceMergeInterface { + + private static Logger log = LoggerFactory.getLogger(ComponentInstanceHeatEnvMerge.class.getName()); + + @Autowired + private ArtifactsBusinessLogic artifactsBusinessLogic; + + @Autowired + private HeatEnvArtifactsMergeBusinessLogic heatEnvArtifactsMergeBusinessLogic; + + @Autowired + protected ComponentsUtils componentsUtils; + + + @Override + public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) { + dataHolder.setOrigComponentInstanceHeatEnvArtifacts(containerComponent.safeGetComponentInstanceHeatArtifacts(currentResourceInstance.getUniqueId())); + } + + @Override + public Either mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) { + List origCompInstHeatEnvArtifacts = dataHolder.getOrigComponentInstanceHeatEnvArtifacts(); + List newCompInstHeatEnvArtifacts = updatedContainerComponent.safeGetComponentInstanceHeatArtifacts(newInstanceId); + List artifactsToUpdate = heatEnvArtifactsMergeBusinessLogic.mergeInstanceHeatEnvArtifacts(origCompInstHeatEnvArtifacts, newCompInstHeatEnvArtifacts); + + for (ArtifactDefinition artifactInfo : artifactsToUpdate) { + Map json = artifactsBusinessLogic.buildJsonForUpdateArtifact(artifactInfo, ArtifactGroupTypeEnum.DEPLOYMENT, null); + + Either, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.updateResourceInstanceArtifactNoContent(newInstanceId, updatedContainerComponent, user, json, + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.Update), null); + if (uploadArtifactToService.isRight()) { + log.error("Failed to update artifact {} on resourceInstance {}", artifactInfo.getArtifactLabel(), newInstanceId); + return Either.right(uploadArtifactToService.right().value()); + } + } + return Either.left(updatedContainerComponent); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java new file mode 100644 index 0000000000..04af6b7fc0 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java @@ -0,0 +1,90 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import java.util.List; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +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.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import fj.data.Either; +/** + * Created by chaya on 9/12/2017. + */ +@org.springframework.stereotype.Component("componentInstanceMergeDataBusinessLogic") +public class ComponentInstanceMergeDataBusinessLogic { + + private static Logger log = LoggerFactory.getLogger(ComponentInstanceMergeDataBusinessLogic.class.getName()); + + @Autowired + private List componentInstancesMergeBLs; + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + + @Autowired + private ComponentsUtils componentsUtils; + + //for testing only + protected void setComponentInstancesMergeBLs(List componentInstancesMergeBLs) { + this.componentInstancesMergeBLs = componentInstancesMergeBLs; + } + + /** + * Saves all containerComponents data before deleting, in order to merge once creating a new instance + * @param containerComponent + * @param currentResourceInstance + */ + public DataForMergeHolder saveAllDataBeforeDeleting(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) { + DataForMergeHolder dataHolder = new DataForMergeHolder(); + for (ComponentInstanceMergeInterface compInstMergeBL : componentInstancesMergeBLs) { + compInstMergeBL.saveDataBeforeMerge(dataHolder, containerComponent, currentResourceInstance, originComponent); + } + return dataHolder; + } + + /** + * Merges inputs and instance inputs/props of the new Container component with the old container component data (before deleting) + * @param containerComponent + * @param newContainerComponentId + * @param newInstanceId + * @return + */ + public Either mergeComponentUserOrigData(User user, DataForMergeHolder dataHolder, org.openecomp.sdc.be.model.Component containerComponent, String newContainerComponentId, String newInstanceId) { + + Either componentWithInstancesInputsAndProperties = getComponentWithInstancesInputsAndProperties(newContainerComponentId); + if (componentWithInstancesInputsAndProperties.isRight()) { + log.error("Component with id {} was not found", newContainerComponentId); + StorageOperationStatus storageOperationStatus = componentWithInstancesInputsAndProperties.right().value(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType()); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + Component updatedContainerComponent = componentWithInstancesInputsAndProperties.left().value(); + + for (ComponentInstanceMergeInterface compInstMergeBL: componentInstancesMergeBLs) { + Either compInstanceMergeEither = compInstMergeBL.mergeDataAfterCreate(user, dataHolder, updatedContainerComponent, newInstanceId); + if (compInstanceMergeEither.isRight()) { + return Either.right(compInstanceMergeEither.right().value()); + } + } + + return Either.left(updatedContainerComponent); + } + + private Either getComponentWithInstancesInputsAndProperties(String containerComponentId) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreComponentInstances(false); + filter.setIgnoreComponentInstancesInputs(false); + filter.setIgnoreComponentInstancesProperties(false); + filter.setIgnoreArtifacts(false); + return toscaOperationFacade.getToscaElement(containerComponentId, filter); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java new file mode 100644 index 0000000000..1d2849b94c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java @@ -0,0 +1,18 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +/** + * Created by chaya on 9/20/2017. + */ +public interface ComponentInstanceMergeInterface { + + void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent); + + Either mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId); +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java new file mode 100644 index 0000000000..765ddb57f6 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java @@ -0,0 +1,131 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL; +import org.openecomp.sdc.be.components.merge.property.ComponentInstanceInputsMergeBL; +import org.openecomp.sdc.be.components.merge.property.ComponentInstancePropertiesMergeBL; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +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.InputDefinition; +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.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import fj.data.Either; + +/** + * Created by chaya on 9/20/2017. + */ +@org.springframework.stereotype.Component("ComponentInstancePropsAndInputsMerge") +public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMergeInterface { + + private static Logger log = LoggerFactory.getLogger(ComponentInstancePropsAndInputsMerge.class.getName()); + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + + @Autowired + private ComponentsUtils componentsUtils; + + @Autowired + private ComponentInstancePropertiesMergeBL componentInstancePropertiesMergeBL; + + @Autowired + private ComponentInstanceInputsMergeBL resourceInstanceInputsMergeBL; + + @Autowired + private ComponentInputsMergeBL resourceInputsMergeBL; + + @Override + public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) { + dataHolder.setOrigComponentInstanceInputs(containerComponent.safeGetComponentInstanceInputsByName(currentResourceInstance.getName())); + dataHolder.setOrigComponentInstanceProperties(containerComponent.safeGetComponentInstanceProperties(currentResourceInstance.getUniqueId())); + dataHolder.setOrigComponentInputs(containerComponent.getInputs()); + } + + @Override + public Either mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) { + Either, ActionStatus> instanceInputsEither = mergeComponentInstanceInputsIntoContainer(dataHolder, updatedContainerComponent, newInstanceId); + if (instanceInputsEither.isRight()) { + ActionStatus actionStatus = instanceInputsEither.right().value(); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + Either, ActionStatus> instancePropsEither = mergeComponentInstancePropsIntoContainer(dataHolder, updatedContainerComponent, newInstanceId); + if (instancePropsEither.isRight()) { + ActionStatus actionStatus = instancePropsEither.right().value(); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + Either, ActionStatus> inputsEither = mergeComponentInputsIntoContainer(dataHolder, updatedContainerComponent.getUniqueId(), newInstanceId); + if (inputsEither.isRight()) { + ActionStatus actionStatus = inputsEither.right().value(); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + return Either.left(updatedContainerComponent); + } + + private Either, ActionStatus> mergeComponentInstancePropsIntoContainer(DataForMergeHolder dataHolder, Component updatedComponent, String instanceId) { + List originComponentInstanceProps = dataHolder.getOrigComponentInstanceProperties(); + List originComponentsInputs = dataHolder.getOrigComponentInputs(); + List newComponentInstancesProps = updatedComponent.safeGetComponentInstanceProperties(instanceId); + ActionStatus actionStatus = componentInstancePropertiesMergeBL.mergeComponentInstanceProperties(originComponentInstanceProps, originComponentsInputs, updatedComponent, instanceId); + + if (actionStatus != ActionStatus.OK) { + log.error("Failed to update component {} with merged instance properties", updatedComponent.getUniqueId(), newComponentInstancesProps); + return Either.right(actionStatus); + } + return Either.left(newComponentInstancesProps); + } + + private Either, ActionStatus> mergeComponentInstanceInputsIntoContainer(DataForMergeHolder dataHolder, Component updatedComponent, String instanceId) { + List originComponentInstanceInputs = dataHolder.getOrigComponentInstanceInputs(); + List originComponentsInputs = dataHolder.getOrigComponentInputs(); + List newComponentInstancesInputs = updatedComponent.safeGetComponentInstanceInput(instanceId); + ActionStatus actionStatus = resourceInstanceInputsMergeBL.mergeComponentInstanceInputs(originComponentInstanceInputs, originComponentsInputs, updatedComponent, instanceId); + if (actionStatus != ActionStatus.OK) { + log.error("Failed to update component {} with merged instance properties", updatedComponent.getUniqueId(), newComponentInstancesInputs); + return Either.right(actionStatus); + } + return Either.left(newComponentInstancesInputs); + } + + private Either, ActionStatus> mergeComponentInputsIntoContainer(DataForMergeHolder dataHolder, String newContainerComponentId, String newInstanceId) { + List origComponentInputs = dataHolder.getOrigComponentInputs(); + List inputsToAddToContainer = new ArrayList<>(); + if (origComponentInputs != null && !origComponentInputs.isEmpty()) { + // get instance inputs and properties after merge + Either componentWithInstancesInputsAndProperties = getComponentWithInstancesInputsAndProperties(newContainerComponentId); + if (componentWithInstancesInputsAndProperties.isRight()) { + log.error("Component %s was not found", newContainerComponentId); + return Either.right(componentsUtils.convertFromStorageResponse(componentWithInstancesInputsAndProperties.right().value())); + } + Component updatedContainerComponent = componentWithInstancesInputsAndProperties.left().value(); + + ActionStatus redeclareStatus = resourceInputsMergeBL.redeclareComponentInputsForInstance(origComponentInputs, updatedContainerComponent, newInstanceId); + if (redeclareStatus != ActionStatus.OK) { + log.error("Failed to update component {} with merged inputs {}", newContainerComponentId, inputsToAddToContainer); + Either.right(redeclareStatus); + } + } + return Either.left(inputsToAddToContainer); + } + + private Either getComponentWithInstancesInputsAndProperties(String containerComponentId) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreComponentInstances(false); + filter.setIgnoreComponentInstancesInputs(false); + filter.setIgnoreComponentInstancesProperties(false); + filter.setIgnoreArtifacts(false); + return toscaOperationFacade.getToscaElement(containerComponentId, filter); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java new file mode 100644 index 0000000000..c5fb1d4a86 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java @@ -0,0 +1,114 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InputDefinition; + +/** + * Created by chaya on 9/7/2017. + */ +public class DataForMergeHolder { + + private List origComponentInstanceInputs; + private List origComponentInstanceProperties; + private List origComponentInputs; + private Map origCompInstDeploymentArtifactsCreatedOnTheInstance; + private Map origCompInstInformationalArtifactsCreatedOnTheInstance; + private List origComponentInstanceHeatEnvArtifacts; + + public DataForMergeHolder() { + origComponentInstanceInputs = new ArrayList<>(); + origComponentInstanceProperties = new ArrayList<>(); + origComponentInputs = new ArrayList<>(); + origCompInstDeploymentArtifactsCreatedOnTheInstance = new HashMap<>(); + origCompInstDeploymentArtifactsCreatedOnTheInstance = new HashMap<>(); + + } + + public List getOrigComponentInstanceHeatEnvArtifacts() { + return origComponentInstanceHeatEnvArtifacts; + } + + public void setOrigComponentInstanceHeatEnvArtifacts(List origComponentInstanceHeatEnvArtifacts) { + this.origComponentInstanceHeatEnvArtifacts = origComponentInstanceHeatEnvArtifacts; + } + + public List getOrigComponentInstanceInputs() { + return origComponentInstanceInputs; + } + + public void setOrigComponentInstanceInputs(List origComponentInstanceInputs) { + Optional.ofNullable(origComponentInstanceInputs).orElse(Collections.emptyList()).stream().forEach(input -> { + ComponentInstanceInput copyInput = new ComponentInstanceInput(); + copyInput.setType(input.getType()); + copyInput.setPath(input.getPath()); + copyInput.setRules(input.getRules()); + copyInput.setValueUniqueUid(input.getValueUniqueUid()); + copyInput.setDefaultValue(input.getDefaultValue()); + copyInput.setDescription(input.getDescription()); + copyInput.setGetInputValues(input.getGetInputValues()); + copyInput.setInputId(input.getInputId()); + copyInput.setInputPath(input.getInputPath()); + copyInput.setInputs(input.getInputs()); + copyInput.setLabel(input.getLabel()); + copyInput.setName(input.getName()); + copyInput.setParentUniqueId(input.getParentUniqueId()); + copyInput.setProperties(input.getProperties()); + copyInput.setPropertyId(input.getPropertyId()); + copyInput.setSchema(input.getSchema()); + copyInput.setStatus(input.getStatus()); + copyInput.setDefaultValue(input.getDefaultValue()); + copyInput.setValue(input.getValue()); + this.origComponentInstanceInputs.add(copyInput); + }); + } + + public List getOrigComponentInstanceProperties() { + return origComponentInstanceProperties; + } + + public void setOrigComponentInstanceProperties(List origComponentInstanceProperties) { + Optional.ofNullable(origComponentInstanceProperties).orElse(Collections.emptyList()).stream().forEach(property -> { + ComponentInstanceProperty propertyCopy = new ComponentInstanceProperty(); + propertyCopy.setType(property.getType()); + propertyCopy.setName(property.getName()); + propertyCopy.setValue(property.getValue()); + propertyCopy.setUniqueId(property.getUniqueId()); + propertyCopy.setDefaultValue(property.getDefaultValue()); + propertyCopy.setInputId(property.getInputId()); + propertyCopy.setGetInputValues(property.getGetInputValues()); + this.origComponentInstanceProperties.add(propertyCopy); + }); + } + + public List getOrigComponentInputs() { + return origComponentInputs; + } + + public void setOrigComponentInputs(List origComponentInputs) { + this.origComponentInputs = origComponentInputs; + } + + public Map getOrigComponentDeploymentArtifactsCreatedOnTheInstance(){ return this.origCompInstDeploymentArtifactsCreatedOnTheInstance;} + + public Map getOrigComponentInformationalArtifactsCreatedOnTheInstance(){ return origCompInstInformationalArtifactsCreatedOnTheInstance;} + + public void setOrigComponentDeploymentArtifactsCreatedOnTheInstance(Map origDeploymentArtifacts){ + origCompInstDeploymentArtifactsCreatedOnTheInstance = origDeploymentArtifacts; + } + + public void setOrigComponentInformationalArtifactsCreatedOnTheInstance(Map origInformationalArtifacts){ + origCompInstInformationalArtifactsCreatedOnTheInstance = origInformationalArtifacts; + } + + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComplexPropertyValueMerger.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComplexPropertyValueMerger.java new file mode 100644 index 0000000000..a68e28024c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComplexPropertyValueMerger.java @@ -0,0 +1,17 @@ +package org.openecomp.sdc.be.components.merge.property; + +import java.util.List; + +public class ComplexPropertyValueMerger extends PropertyValueMerger { + + private static final ComplexPropertyValueMerger INSTANCE = new ComplexPropertyValueMerger(); + + public static PropertyValueMerger getInstance() { + return INSTANCE; + } + + @Override + Object merge(Object oldVal, Object newVal, List someStrings) { + return mergeValues(oldVal, newVal, someStrings); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBL.java new file mode 100644 index 0000000000..4e49eef94c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBL.java @@ -0,0 +1,72 @@ +package org.openecomp.sdc.be.components.merge.property; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +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.InputDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import fj.data.Either; + +@org.springframework.stereotype.Component +public class ComponentInstanceInputsMergeBL { + + @javax.annotation.Resource + private ToscaOperationFacade toscaOperationFacade; + + @javax.annotation.Resource + private ComponentsUtils componentsUtils; + + @javax.annotation.Resource + private DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic; + + public ActionStatus mergeComponentInstancesInputs(Component oldComponent, Component newComponent) { + Map> componentInstancesInputs = newComponent.getComponentInstancesInputs(); + if (componentInstancesInputs == null) { + return ActionStatus.OK; + } + componentInstancesInputs.forEach((instanceId, instInputs) -> mergeOldInstanceInputsValues(oldComponent, newComponent, instanceId, instInputs)); + return updateComponentInstancesInputs(newComponent, componentInstancesInputs); + } + + public ActionStatus mergeComponentInstanceInputs(List oldInstProps, List oldInputs, Component newComponent, String instanceId) { + List newInstInput = newComponent.safeGetComponentInstanceInput(instanceId); + if (newInstInput == null) { + return ActionStatus.OK; + } + propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstProps, oldInputs, newInstInput, newComponent.getInputs()); + return updateComponentInstanceInputs(newComponent, instanceId, newInstInput); + } + + private ActionStatus updateComponentInstanceInputs(Component newComponent, String instanceId, List newInstInput) { + StorageOperationStatus storageOperationStatus = toscaOperationFacade.updateComponentInstanceInputs(newComponent, instanceId, newInstInput); + if (storageOperationStatus != StorageOperationStatus.OK) { + return componentsUtils.convertFromStorageResponse(storageOperationStatus); + } + return ActionStatus.OK; + } + + private ActionStatus updateComponentInstancesInputs(Component component, Map> componentInstancesInputs) { + Either>, StorageOperationStatus> mapStorageOperationStatusEither = toscaOperationFacade.updateComponentInstanceInputsToComponent(componentInstancesInputs, component.getUniqueId()); + if (mapStorageOperationStatusEither.isRight()) { + return componentsUtils.convertFromStorageResponse(mapStorageOperationStatusEither.right().value()); + } + return ActionStatus.OK; + } + + private void mergeOldInstanceInputsValues(Component oldComponent, Component newComponent, String instanceId, List instInputs) { + ComponentInstance currentCompInstance = newComponent.getComponentInstanceById(instanceId).get(); + List oldInstInputs = oldComponent == null ? Collections.emptyList() : oldComponent.safeGetComponentInstanceInputsByName(currentCompInstance.getName()); + List oldInputs = oldComponent == null ? Collections.emptyList() : oldComponent.getInputs(); + propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstInputs, oldInputs, instInputs, newComponent.getInputs()); + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBL.java new file mode 100644 index 0000000000..43e3ec624a --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBL.java @@ -0,0 +1,73 @@ +package org.openecomp.sdc.be.components.merge.property; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import fj.data.Either; + +@org.springframework.stereotype.Component +public class ComponentInstancePropertiesMergeBL { + + @javax.annotation.Resource + private ToscaOperationFacade toscaOperationFacade; + + @javax.annotation.Resource(name = "componentUtils") + private ComponentsUtils componentsUtils; + + @javax.annotation.Resource + private DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic; + + public ActionStatus mergeComponentInstancesProperties(Component oldComponent, Resource newResource) { + Map> newInstProps = newResource.getComponentInstancesProperties(); + if (newInstProps == null) { + return ActionStatus.OK; + } + newInstProps.forEach((instanceId, newProps) -> mergeOldInstancePropertiesValues(oldComponent, newResource, instanceId, newProps) ); + return updateComponentInstancesProperties(newResource, newInstProps); + } + + + public ActionStatus mergeComponentInstanceProperties(List oldInstProps, List oldInputs, Component newComponent, String instanceId) { + List newInstProps = newComponent.safeGetComponentInstanceProperties(instanceId); + if (newInstProps == null) { + return ActionStatus.OK; + } + propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstProps, oldInputs, newInstProps, newComponent.getInputs()); + return updateComponentInstanceProperties(newComponent, instanceId, newInstProps); + } + + private void mergeOldInstancePropertiesValues(Component oldComponent, Component newComponent, String instanceId, List newProps) { + List oldInstProperties = oldComponent == null ? Collections.emptyList() : oldComponent.safeGetComponentInstanceProperties(instanceId); + List oldInputs = oldComponent == null ? Collections.emptyList() : oldComponent.getInputs(); + propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstProperties, oldInputs, newProps, newComponent.getInputs()); + } + + private ActionStatus updateComponentInstancesProperties(Component newComponent, Map> newInstProps) { + Either>, StorageOperationStatus> mapStorageOperationStatusEither = toscaOperationFacade.updateComponentInstancePropsToComponent(newInstProps, newComponent.getUniqueId()); + if (mapStorageOperationStatusEither.isRight()) { + return componentsUtils.convertFromStorageResponse(mapStorageOperationStatusEither.right().value()); + } + return ActionStatus.OK; + } + + private ActionStatus updateComponentInstanceProperties(Component component, String instanceId, List newInstProps) { + StorageOperationStatus storageOperationStatus = toscaOperationFacade.updateComponentInstanceProperties(component, instanceId, newInstProps); + if (storageOperationStatus != StorageOperationStatus.OK) { + return componentsUtils.convertFromStorageResponse(storageOperationStatus); + } + return ActionStatus.OK; + } + + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java new file mode 100644 index 0000000000..96d3bce97e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java @@ -0,0 +1,43 @@ +package org.openecomp.sdc.be.components.merge.property; + +import java.util.List; + +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.InputDefinition; +import org.springframework.stereotype.Component; + +@Component +public class DataDefinitionsValuesMergingBusinessLogic { + + @javax.annotation.Resource + private PropertyDataValueMergeBusinessLogic propertyValueMergeBL; + + /** + * Merge previous version data definition values into the new version data definition. + * A data definition value is merged if it had a value in previous version and has no value in the current version. + * in case a property get input value has no corresponding input in the current version its value will not be merged + * @param oldInstanceDataDefinition the currently persisted instance data definitions + * @param oldInputs the previous version inputs + * @param updatedInstanceDataDefinition the currently being update instance data definitions + * @param newInputs the new version inputs + */ + public void mergeInstanceDataDefinitions(List oldInstanceDataDefinition, List oldInputs, List updatedInstanceDataDefinition, List newInputs) { + if (updatedInstanceDataDefinition == null || updatedInstanceDataDefinition.isEmpty() || oldInstanceDataDefinition == null || oldInstanceDataDefinition.isEmpty()) { + return; + } + List mergePropertyData = PropertyInstanceMergeDataBuilder.getInstance().buildDataForMerging(oldInstanceDataDefinition, oldInputs, updatedInstanceDataDefinition, newInputs); + mergePropertyData.forEach(this::mergeInstanceDefinition); + + } + + private void mergeInstanceDefinition(MergePropertyData mergeData) { + if (isSameType(mergeData.getOldProp(), mergeData.getNewProp())) { + propertyValueMergeBL.mergePropertyValue(mergeData.getOldProp(), mergeData.getNewProp(), mergeData.getGetInputNamesToMerge()); + } + } + + private boolean isSameType(PropertyDataDefinition oldDataDefinition, PropertyDataDefinition updatedDataDefinition) { + return oldDataDefinition.typeEquals(updatedDataDefinition); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java new file mode 100644 index 0000000000..63a7a1b3a0 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java @@ -0,0 +1,52 @@ +package org.openecomp.sdc.be.components.merge.property; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; + +/** + * A POJO which represents an instance property data definition (a {@link org.openecomp.sdc.be.model.ComponentInstanceProperty} or {@link org.openecomp.sdc.be.model.ComponentInstanceInput}) + * that its value needs to be merged during an upgrade of a VSP. + * + */ +public class MergePropertyData { + + /*The previous state of the instance property to merge */ + private PropertyDataDefinition oldProp; + /*The new state of the instance property to merge */ + private PropertyDataDefinition newProp; + + private List getInputNamesToMerge = new ArrayList<>(); + + public PropertyDataDefinition getOldProp() { + return oldProp; + } + + public MergePropertyData setOldProp(PropertyDataDefinition oldProp) { + this.oldProp = oldProp; + return this; + } + + public MergePropertyData setNewProp(PropertyDataDefinition newProp) { + this.newProp = newProp; + return this; + } + + public PropertyDataDefinition getNewProp() { + return newProp; + } + + public void addAddGetInputNamesToMerge(List getInputsNameToMerge) { + getInputNamesToMerge.addAll(getInputsNameToMerge); + } + + public List getGetInputNamesToMerge() { + return getInputNamesToMerge; + } + + public boolean isGetInputProp() { + return oldProp.isGetInputProperty(); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java new file mode 100644 index 0000000000..6b083596c7 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java @@ -0,0 +1,164 @@ +package org.openecomp.sdc.be.components.merge.property; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +import javax.annotation.Resource; + +import org.openecomp.sdc.be.components.impl.ImportUtils; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; +import org.openecomp.sdc.be.model.tosca.ToscaFunctions; +import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; +import org.openecomp.sdc.be.tosca.PropertyConvertor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import com.google.gson.Gson; + +import fj.data.Either; + +@Component +public class PropertyDataValueMergeBusinessLogic { + + private static final Logger LOGGER = LoggerFactory.getLogger(PropertyDataValueMergeBusinessLogic.class); + + private final PropertyConvertor propertyConvertor = PropertyConvertor.getInstance(); + + private PropertyValueMerger complexPropertyValueMerger = ComplexPropertyValueMerger.getInstance(); + + private PropertyValueMerger scalarPropertyValueMerger = ScalarPropertyValueMerger.getInstance(); + + @Resource + private ApplicationDataTypeCache dataTypeCache; + + private final Gson gson = new Gson(); + + /** + * + * @param oldProp the old property to merge value from + * @param newProp the new property to merge value into + * @param getInputNamesToMerge inputs names which their corresponding get_input values are allowed to be merged + */ + public void mergePropertyValue(PropertyDataDefinition oldProp, PropertyDataDefinition newProp, List getInputNamesToMerge) { + Either, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + if (dataTypesEither.isRight()) { + LOGGER.debug("failed to fetch data types, skip merging of previous property values. status: {}", dataTypesEither.right().value()); + } + mergePropertyValue(oldProp, newProp, dataTypesEither.left().value(), getInputNamesToMerge); + mergeComplexPropertyGetInputsValues(oldProp, newProp); + } + + private void mergePropertyValue(PropertyDataDefinition oldProp, PropertyDataDefinition newProp, Map dataTypes, List getInputNamesToMerge) { + Object oldValAsObject = convertPropertyStrValueToObject(oldProp, dataTypes); + Object newValAsObject = convertPropertyStrValueToObject(newProp, dataTypes); + PropertyValueMerger propertyValueMerger = getPropertyValueMerger(newProp); + if(oldValAsObject != null){ + Object mergedValue = propertyValueMerger.mergeValues(oldValAsObject, newValAsObject, getInputNamesToMerge); + newProp.setValue(convertPropertyValueObjectToString(mergedValue)); + } + } + + private PropertyValueMerger getPropertyValueMerger(PropertyDataDefinition newProp) { + if (ToscaPropertyType.isPrimitiveType(newProp.getType()) || ToscaPropertyType.isPrimitiveType(newProp.getSchemaType())) { + return scalarPropertyValueMerger; + } + return complexPropertyValueMerger; + } + + private String convertPropertyValueObjectToString(Object mergedValue) { + if (isEmptyValue(mergedValue)) { + return null; + } + return mergedValue instanceof String? mergedValue.toString() : gson.toJson(mergedValue); + } + + private Object convertPropertyStrValueToObject(PropertyDataDefinition propertyDataDefinition, Map dataTypes) { + String propValue = propertyDataDefinition.getValue() == null ? "": propertyDataDefinition.getValue(); + String propertyType = propertyDataDefinition.getType(); + String innerType = propertyDataDefinition.getSchemaType(); + return propertyConvertor.convertToToscaObject(propertyType, propValue, innerType, dataTypes); + } + + + @SuppressWarnings("unchecked") + private Object removeUnwantedGetInputValues(Object val, List getInputNamesToMerge) { + if (val instanceof Map) { + return removeUnwantedGetInputValues((Map) val, getInputNamesToMerge); + } + if (val instanceof List) { + return removeUnwantedGetInputValues((List)val, getInputNamesToMerge); + } + return val; + } + + private List removeUnwantedGetInputValues(List listVal, List getInputNamesToMerge) { + return listVal.stream().map(val -> removeUnwantedGetInputValues(val, getInputNamesToMerge)).collect(Collectors.toList()); + } + + private Map removeUnwantedGetInputValues(Map val, List getInputNamesToMerge) { + return val.entrySet().stream().filter(entry -> !isGetInputEntry(entry) || isGetInputToMerge(getInputNamesToMerge, entry)) + .collect(Collectors.toMap(Map.Entry::getKey, entry -> removeUnwantedGetInputValues(entry.getValue(), getInputNamesToMerge))); + } + + private boolean isGetInputToMerge(List getInputNamesToMerge, Map.Entry entry) { + return getInputNamesToMerge.contains(retrieveGetInputInputName(entry.getValue())); + } + + private String retrieveGetInputInputName(Object getInputValue) { + return getInputValue instanceof List ? (String)((List) getInputValue).get(0) : (String)getInputValue; + } + + private boolean isGetInputEntry(Map.Entry oldValEntry) { + return oldValEntry.getKey().equals(ImportUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); + } + + private boolean isEmptyValue(Object val) { + return val == null || + val instanceof Map && ((Map) val).isEmpty() || + val instanceof List && ((List) val).isEmpty(); + } + + private void mergeComplexPropertyGetInputsValues(PropertyDataDefinition oldProp, PropertyDataDefinition newProp) { + if (!oldProp.isGetInputProperty()) { + return; + } + List getInputsToMerge = findOldGetInputValuesToMerge(oldProp, newProp); + List newPropGetInputValues = Optional.ofNullable(newProp.getGetInputValues()).orElse(new ArrayList<>()); + newPropGetInputValues.addAll(getInputsToMerge); + newProp.setGetInputValues(newPropGetInputValues); + } + + private List findOldGetInputValuesToMerge(PropertyDataDefinition oldProp, PropertyDataDefinition newProp) { + List oldGetInputValues = oldProp.getGetInputValues(); + List newGetInputValues = Optional.ofNullable(newProp.getGetInputValues()).orElse(Collections.emptyList()); + List newGetInputNames = newGetInputValues.stream().map(GetInputValueDataDefinition::getInputName).collect(Collectors.toList()); + return oldGetInputValues.stream() + .filter(getInput -> !newGetInputNames.contains(getInput.getInputName())) + .filter(getInput -> isValueContainsGetInput(getInput.getInputName(), newProp.getValue())) + .collect(Collectors.toList()); + } + + private boolean isValueContainsGetInput(String inputName, String value) { + String getInputEntry = "\"%s\":\"%s\""; + return value != null && value.contains(String.format(getInputEntry, ToscaFunctions.GET_INPUT.getFunctionName(), inputName)); + } + + + + + + + + + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java new file mode 100644 index 0000000000..09f26a39ee --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java @@ -0,0 +1,79 @@ +package org.openecomp.sdc.be.components.merge.property; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.InputDefinition; + +public class PropertyInstanceMergeDataBuilder { + + private final static PropertyInstanceMergeDataBuilder INSTANCE = new PropertyInstanceMergeDataBuilder(); + + private PropertyInstanceMergeDataBuilder() { + } + + public static PropertyInstanceMergeDataBuilder getInstance() { + return INSTANCE; + } + + public List buildDataForMerging(List oldProps, + List oldInputs, + List newProps, + List newInputs) { + + Map oldPropsByName = MapUtil.toMap(oldProps, T::getName); + Map oldInputsByName = MapUtil.toMap(oldInputs, InputDefinition::getName); + Map newPropsByName = MapUtil.toMap(newProps, T::getName); + Map newInputsByName = MapUtil.toMap(newInputs, InputDefinition::getName); + return buildMergeData(oldPropsByName, oldInputsByName, newPropsByName, newInputsByName); + + } + + private List buildMergeData(Map oldPropsByName, Map oldInputsByName, Map newPropsByName, Map newInputsByName) { + List mergeData = new ArrayList<>(); + newPropsByName.forEach((name, prop) -> { + if (oldPropsByName.containsKey(name)) { + mergeData.add(buildMergePropertyData(oldPropsByName.get(name), oldInputsByName, prop, newInputsByName)); + } + }); + return mergeData; + } + + private MergePropertyData buildMergePropertyData(PropertyDataDefinition oldProp, + Map oldInputsByName, + PropertyDataDefinition newProp, + Map newInputsByName) { + MergePropertyData mergePropertyData = new MergePropertyData(); + mergePropertyData.setOldProp(oldProp) + .setNewProp(newProp); + if (oldProp.isGetInputProperty()) { + setGetInputData(oldProp, oldInputsByName, newInputsByName, mergePropertyData); + + } + return mergePropertyData; + } + + private void setGetInputData(PropertyDataDefinition oldProp, Map oldInputsByName, Map newInputsByName, MergePropertyData mergePropertyData) { + List oldDeclaredByUserInputNames = getOldDeclaredInputsByUser(oldProp.getGetInputValues(), oldInputsByName); + List oldGetInputNamesWhichExistInNewVersion = getOldGetInputNamesWhichExistInNewVersion(oldProp.getGetInputValues(), newInputsByName); + mergePropertyData.addAddGetInputNamesToMerge(oldDeclaredByUserInputNames); + mergePropertyData.addAddGetInputNamesToMerge(oldGetInputNamesWhichExistInNewVersion); + } + + private List getOldGetInputNamesWhichExistInNewVersion(List getInputValues, Map newInputsByName) { + return getInputValues.stream().map(GetInputValueDataDefinition::getInputName).filter(newInputsByName::containsKey).collect(Collectors.toList()); + } + + private List getOldDeclaredInputsByUser(List getInputValues, Map oldInputsByName) { + return getInputValues.stream().map(GetInputValueDataDefinition::getInputName) + .map(oldInputsByName::get) + .filter(oldInput -> oldInput.getInstanceUniqueId() != null) + .map(PropertyDataDefinition::getName) + .collect(Collectors.toList()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java new file mode 100644 index 0000000000..88601bb521 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java @@ -0,0 +1,148 @@ +package org.openecomp.sdc.be.components.merge.property; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.commons.lang.StringUtils; +import org.openecomp.sdc.be.components.impl.ImportUtils; + +public abstract class PropertyValueMerger { + + abstract Object merge(Object oldVal, Object newVal, List someStrings); + + @SuppressWarnings("unchecked") + /** + * merges property value oldVal into property value newVal recursively + * @param oldVal - cannot be {@code Null} + */ + protected Object mergeValues(Object oldVal, Object newVal, List getInputNamesToMerge) { + if (isEmptyValue(newVal)) { + return removeUnwantedGetInputValues(oldVal, getInputNamesToMerge); + } + if (isMapTypeValues(oldVal, newVal)) { + return mergeMapValue((Map) oldVal, (Map) newVal, getInputNamesToMerge); + } + if (isListTypeValues(oldVal, newVal)) { + return mergeListValue((List) oldVal, (List) newVal, getInputNamesToMerge); + } + if (isSameTypeValues(oldVal, newVal)) { + return mergeScalarValue(oldVal, newVal); + } + return newVal; + + } + + private Map mergeMapValue(Map oldValMap, Map newValMap, List getInputNamesToMerge) { + mergeEntriesExistInNewValue(oldValMap, newValMap, getInputNamesToMerge);//continue the recursion + setOldEntriesNotExistInNewValue(oldValMap, newValMap, getInputNamesToMerge); + return newValMap; + } + + private void mergeEntriesExistInNewValue(Map oldValMap, Map newValMap, List getInputNamesToMerge) { + for (Map.Entry newValEntry : newValMap.entrySet()) { + Object oldVal = oldValMap.get(newValEntry.getKey()); + if (oldVal != null) { + newValMap.put(newValEntry.getKey(), merge(oldVal, newValEntry.getValue(), getInputNamesToMerge)); + } + } + } + + private void setOldEntriesNotExistInNewValue(Map oldVal, Map newVal, List getInputNamesToMerge) { + for (Map.Entry oldValEntry : oldVal.entrySet()) { + if (!isGetInputEntry(oldValEntry) || isGetInputToMerge(getInputNamesToMerge, oldValEntry)) { + Object oldValObj = oldValEntry.getValue(); + newVal.computeIfAbsent(oldValEntry.getKey(), key -> removeUnwantedGetInputValues(oldValObj, getInputNamesToMerge)); + } + } + } + + private List mergeListValue(List oldVal, List newVal, List getInputNamesToMerge) { + List mergedList = mergeLists(oldVal, newVal, getInputNamesToMerge); + copyRestOfBiggerList(oldVal, newVal, getInputNamesToMerge, mergedList); + return mergedList; + } + + private void copyRestOfBiggerList(List oldVal, List newVal, List getInputNamesToMerge, List mergedList) { + if (oldVal.size() == newVal.size()) { + return; + } + int maxListSize = Math.max(oldVal.size(), newVal.size()); + List greaterList = newVal.size() == maxListSize ? newVal : oldVal; + for (int i = mergedList.size(); i < maxListSize; i ++) { + Object listVal = greaterList.get(i); + Object listValToMerge = greaterList == oldVal ? removeUnwantedGetInputValues(listVal, getInputNamesToMerge) : listVal; + mergedList.add(listValToMerge); + } + } + + private List mergeLists(List oldVal, List newVal, List getInputNamesToMerge) { + int minListSize = Math.min(oldVal.size(), newVal.size()); + List mergedList = new ArrayList<>(); + for (int i = 0; i < minListSize; i++) { + Object mergedVal = merge(oldVal.get(i), newVal.get(i), getInputNamesToMerge); + mergedList.add(mergedVal); + } + return mergedList; + } + + Object mergeScalarValue(Object oldVal, Object newVal) { + return isEmptyValue(newVal) ? oldVal : newVal; + } + + @SuppressWarnings("unchecked") + Object removeUnwantedGetInputValues(Object val, List getInputNamesToMerge) { + if (val instanceof Map) { + return removeUnwantedGetInputValues((Map) val, getInputNamesToMerge); + } + if (val instanceof List) { + return removeUnwantedGetInputValues((List)val, getInputNamesToMerge); + } + return val; + } + + private List removeUnwantedGetInputValues(List listVal, List getInputNamesToMerge) { + return listVal.stream().map(val -> removeUnwantedGetInputValues(val, getInputNamesToMerge)).collect(Collectors.toList()); + } + + private Map removeUnwantedGetInputValues(Map val, List getInputNamesToMerge) { + return val.entrySet().stream().filter(entry -> !isGetInputEntry(entry) || isGetInputToMerge(getInputNamesToMerge, entry)) + .collect(Collectors.toMap(Map.Entry::getKey, entry -> removeUnwantedGetInputValues(entry.getValue(), getInputNamesToMerge))); + } + + private boolean isGetInputToMerge(List getInputNamesToMerge, Map.Entry entry) { + return getInputNamesToMerge.contains(retrieveGetInputInputName(entry.getValue())); + } + + private boolean isMapTypeValues(Object oldVal, Object newVal) { + return newVal instanceof Map && oldVal instanceof Map; + } + + private boolean isListTypeValues(Object oldVal, Object newVal) { + return newVal instanceof List && oldVal instanceof List; + } + + private boolean isSameTypeValues(Object oldVal, Object newVal) { + return oldVal.getClass().equals(newVal.getClass()); + } + + private String retrieveGetInputInputName(Object getInputValue) { + return getInputValue instanceof List ? (String)((List) getInputValue).get(0) : (String)getInputValue; + } + + private boolean isGetInputEntry(Map.Entry oldValEntry) { + return oldValEntry.getKey().equals(ImportUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); + } + + private boolean isEmptyValue(Object val) { + return val == null || + val instanceof String && StringUtils.isEmpty((String)val) || + val instanceof Map && ((Map) val).isEmpty() || + val instanceof List && ((List) val).isEmpty(); + + + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ScalarPropertyValueMerger.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ScalarPropertyValueMerger.java new file mode 100644 index 0000000000..39381e7322 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ScalarPropertyValueMerger.java @@ -0,0 +1,20 @@ +package org.openecomp.sdc.be.components.merge.property; + +import java.util.List; + +import org.springframework.stereotype.Component; + +@Component("scalar-prop-value-merger") +public class ScalarPropertyValueMerger extends PropertyValueMerger { + + private final static ScalarPropertyValueMerger INSTANCE = new ScalarPropertyValueMerger(); + + public static PropertyValueMerger getInstance() { + return INSTANCE; + } + + @Override + Object merge(Object oldVal, Object newVal, List getInputNamesToMerge) { + return mergeScalarValue(removeUnwantedGetInputValues(oldVal, getInputNamesToMerge), newVal); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBLFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBLFactory.java new file mode 100644 index 0000000000..9d11eb9aaf --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBLFactory.java @@ -0,0 +1,33 @@ +package org.openecomp.sdc.be.components.merge.resource; + + +import org.openecomp.sdc.be.components.merge.GlobalTypesMergeBusinessLogic; +import org.openecomp.sdc.be.components.merge.TopologyComparator; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Resource; +import org.springframework.stereotype.Component; + +import fj.data.Either; + +@Component +public class MergeResourceBLFactory { + + @javax.annotation.Resource + private ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic; + + @javax.annotation.Resource + private GlobalTypesMergeBusinessLogic globalTypesMergeBusinessLogic; + + @javax.annotation.Resource + private TopologyComparator topologyComparator; + + public Either getInstance(Resource oldResource, Resource newResource) { + Either isTopologyChangeEither = topologyComparator.isTopologyChanged(oldResource, newResource); + return isTopologyChangeEither.bimap(this::getInstance, actionStatus -> actionStatus); + } + + private MergeResourceBusinessLogic getInstance(boolean topologyChanged) { + return topologyChanged ? globalTypesMergeBusinessLogic : resourceDataMergeBusinessLogic; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBusinessLogic.java new file mode 100644 index 0000000000..f3bc0c2395 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBusinessLogic.java @@ -0,0 +1,10 @@ +package org.openecomp.sdc.be.components.merge.resource; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Resource; + +public interface MergeResourceBusinessLogic { + + ActionStatus mergeResourceEntities(Resource oldResource, Resource newResource); + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java new file mode 100644 index 0000000000..251fb1a64e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java @@ -0,0 +1,62 @@ +package org.openecomp.sdc.be.components.merge.resource; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL; +import org.openecomp.sdc.be.components.merge.property.ComponentInstanceInputsMergeBL; +import org.openecomp.sdc.be.components.merge.property.ComponentInstancePropertiesMergeBL; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class ResourceDataMergeBusinessLogic implements MergeResourceBusinessLogic { + + private final static Logger log = LoggerFactory.getLogger(ResourceDataMergeBusinessLogic.class.getName()); + + @javax.annotation.Resource + private ComponentInputsMergeBL inputsValuesMergeBL; + + @javax.annotation.Resource + private ComponentInstancePropertiesMergeBL instancePropertiesValueMergeBL; + + @javax.annotation.Resource + private ComponentInstanceInputsMergeBL instanceInputsValueMergeBL; + + @Override + public ActionStatus mergeResourceEntities(Resource oldResource, Resource newResource) { + if (oldResource == null) { + return ActionStatus.OK; + } + + ActionStatus mergeInstInputsStatus = instancePropertiesValueMergeBL.mergeComponentInstancesProperties(oldResource, newResource); + if (mergeInstInputsStatus != ActionStatus.OK) { + log.error("failed to merge instance properties of resource {} status is {}", newResource.getUniqueId(), mergeInstInputsStatus); + return mergeInstInputsStatus; + } + + ActionStatus mergeInstPropsStatus = instanceInputsValueMergeBL.mergeComponentInstancesInputs(oldResource, newResource); + if (mergeInstPropsStatus != ActionStatus.OK) { + log.error("failed to merge instance inputs of resource {} status is {}", newResource.getUniqueId(), mergeInstPropsStatus); + return mergeInstPropsStatus; + } + + ActionStatus mergeInputsStatus = mergeInputs(oldResource, newResource); + if (mergeInputsStatus != ActionStatus.OK) { + log.error("failed to merge inputs of resource {} status is {}", newResource.getUniqueId(), mergeInputsStatus); + return mergeInputsStatus; + } + return ActionStatus.OK; + } + + private ActionStatus mergeInputs(Resource oldResource, Resource newResource) { + List inputsToMerge = newResource.getInputs() != null ? newResource.getInputs() : new ArrayList<>(); + return inputsValuesMergeBL.mergeAndRedeclareComponentInputs(oldResource, newResource, inputsToMerge); + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java index 7964b4406c..15fff52ab9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java @@ -20,12 +20,12 @@ package org.openecomp.sdc.be.components.validation; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; - import java.util.Optional; import java.util.stream.Collectors; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; + public class ComponentValidations { public static boolean validateComponentInstanceExist(Component component, String instanceId) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/exception/SdcActionException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/exception/SdcActionException.java new file mode 100644 index 0000000000..5c6a437b3d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/exception/SdcActionException.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.exception; + +import org.openecomp.sdc.be.dao.api.ActionStatus; + +public class SdcActionException extends RuntimeException { + + private ActionStatus actionStatus; + + public SdcActionException(ActionStatus actionStatus) { + this.actionStatus = actionStatus; + } + + public ActionStatus getActionStatus() { + return actionStatus; + } +} 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 1c2f175cfb..f5fcf628cd 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 @@ -57,6 +57,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jcabi.aspects.Loggable; + +import fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; @@ -65,8 +67,6 @@ import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import fj.data.Either; - /** * This Servlet serves external users operations on artifacts. * 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 8c066c8fde..910521c8dc 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 @@ -21,8 +21,11 @@ package org.openecomp.sdc.be.impl; import java.lang.reflect.Type; -import java.security.cert.CollectionCertStoreParameters; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; import java.util.regex.Pattern; import javax.annotation.PostConstruct; @@ -39,20 +42,28 @@ 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.dao.utils.CollectionUtils; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.CapabilityTypeDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ConsumerDefinition; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.GroupTypeDefinition; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.PropertyConstraint; +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.User; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserialiser; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.tosca.ToscaError; 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.util.ThreadLocalsHolder; import org.openecomp.sdc.common.util.ValidationUtils; @@ -91,7 +102,6 @@ public class ComponentsUtils { public Either convertJsonToObject(String data, User user, Class clazz, AuditingActionEnum actionEnum) { if (data == null) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject"); BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); log.debug("object is null after converting from json"); ResponseFormat responseFormat = getInvalidContentErrorAndAudit(user, actionEnum); @@ -102,7 +112,6 @@ public class ComponentsUtils { return Either.left(obj); } catch (Exception e) { // INVALID JSON - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject"); BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); log.debug("failed to convert from json {}", data, e); ResponseFormat responseFormat = getInvalidContentErrorAndAudit(user, actionEnum); @@ -134,14 +143,12 @@ public class ComponentsUtils { component = mapper.readValue(data, clazz); if (component == null) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject"); BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); log.debug("object is null after converting from json"); ResponseFormat responseFormat = getInvalidContentErrorAndAuditComponent(user, actionEnum, typeEnum); return Either.right(responseFormat); } } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject"); BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); log.debug("failed to convert from json {}", data, e); ResponseFormat responseFormat = getInvalidContentErrorAndAuditComponent(user, actionEnum, typeEnum); @@ -160,6 +167,10 @@ public class ComponentsUtils { return responseFormatManager.getResponseFormat(actionStatus, params); } + public ResponseFormat getResponseFormat(StorageOperationStatus storageStatus, String... params) { + return responseFormatManager.getResponseFormat(this.convertFromStorageResponse(storageStatus), params); + } + /** * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus is anonymously converted from storage operation, and the caller doesn't know what actionStatus he * received. It's caller's Responsibility to fill the resource object passed to this function with needed fields. @@ -238,8 +249,8 @@ public class ComponentsUtils { switch (actionStatus) { case MISSING_CAPABILITY_TYPE: - if (obj instanceof List && org.apache.commons.collections.CollectionUtils.isNotEmpty((List) obj)){ - List list = (List)obj; + if (obj instanceof List && org.apache.commons.collections.CollectionUtils.isNotEmpty((List) obj)){ + List list = (List)obj; if ( list.get(0) instanceof RequirementDefinition ) { responseFormat = getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, ((RequirementDefinition) list.get(0)).getName()); //Arbitray index, all we need is single object return responseFormat; 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 cfa108ed80..ddc5ecabe7 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 @@ -43,7 +43,6 @@ import org.openecomp.sdc.be.info.ServletJsonResponse; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.config.EcompErrorName; -import org.openecomp.sdc.common.util.GeneralUtility; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java index 163d220871..dfdfeac741 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java @@ -21,7 +21,6 @@ package org.openecomp.sdc.be.info; import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; public class ArtifactDefinitionInfo { 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 0f1bf4603d..f78b7dfead 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 @@ -27,8 +27,8 @@ import java.util.Map; 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.ArtifactTypeConfig; +import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -177,13 +177,17 @@ public class ArtifactTemplateInfo { String correctType = type; if (type.equalsIgnoreCase(CSAR_NESTED)) correctType = ArtifactTypeEnum.HEAT_NESTED.getType(); - else if ((type.equalsIgnoreCase(CSAR_VOLUME))) + else if (type.equalsIgnoreCase(CSAR_VOLUME)) correctType = ArtifactTypeEnum.HEAT_VOL.getType(); - else if ((type.equalsIgnoreCase(CSAR_NETWORK))) + else if (type.equalsIgnoreCase(CSAR_NETWORK)) correctType = ArtifactTypeEnum.HEAT_NET.getType(); - else if ((type.equalsIgnoreCase(CSAR_ARTIFACT))) - correctType = ArtifactTypeEnum.HEAT_ARTIFACT.getType(); - else if ((type.equalsIgnoreCase(CSAR_HEAT))) + else if (type.equalsIgnoreCase(CSAR_ARTIFACT)){ + if( parentArtifact != null) + correctType = ArtifactTypeEnum.HEAT_ARTIFACT.getType(); + else + correctType = resourceInfo.type; + } + else if (type.equalsIgnoreCase(CSAR_HEAT)) correctType = ArtifactTypeEnum.HEAT.getType(); else correctType = ArtifactTypeEnum.OTHER.getType(); 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 05af87d789..ea495267bd 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 @@ -21,6 +21,7 @@ package org.openecomp.sdc.be.info; import java.util.List; + import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.GroupInstance; import org.openecomp.sdc.be.model.GroupProperty; 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 25b6b3564b..62ee5b6f81 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 @@ -23,14 +23,12 @@ package org.openecomp.sdc.be.info; import java.util.ArrayList; import java.util.HashSet; import java.util.List; -import java.util.Map; +import java.util.Optional; 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; 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 fa31989d87..83cda6ef87 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 @@ -20,6 +20,15 @@ package org.openecomp.sdc.be.listen; +import java.io.IOException; +import java.io.InputStream; +import java.util.jar.Attributes; +import java.util.jar.Manifest; + +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.impl.DownloadArtifactLogic; import org.openecomp.sdc.be.impl.WebAppContextWrapper; @@ -29,15 +38,6 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.listener.AppContextListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.web.context.WebApplicationContext; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import java.io.IOException; -import java.io.InputStream; -import java.util.jar.Attributes; -import java.util.jar.Manifest; public class BEAppContextListener extends AppContextListener implements ServletContextListener { 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 15b3eb20c6..ae103dbaca 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 @@ -51,14 +51,14 @@ import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; import com.jcabi.aspects.Loggable; + +import fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import fj.data.Either; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Additional Information Servlet", description = "Additional Information Servlet") 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 7c7da97ef0..5a26b7c4e6 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 @@ -53,14 +53,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jcabi.aspects.Loggable; + +import fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import fj.data.Either; - /** * Root resource (exposed at "/" path) */ 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 049212dd19..1b02e0afa4 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 @@ -49,14 +49,14 @@ import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.jcabi.aspects.Loggable; + +import fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import fj.data.Either; - /** * Web Servlet for actions on Attributes * 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 4278378bbc..7407a4dff3 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,7 +20,6 @@ package org.openecomp.sdc.be.servlets; -import java.util.EnumMap; import java.util.Map; import java.util.Map.Entry; import java.util.function.Supplier; @@ -57,7 +56,6 @@ 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; 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 8e08ecf600..81f1775a01 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 @@ -34,6 +34,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.apache.commons.lang3.tuple.Pair; import org.openecomp.sdc.be.components.impl.HealthCheckBusinessLogic; import org.openecomp.sdc.be.components.impl.MonitoringBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -41,8 +42,6 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.api.HealthCheckInfo; -import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckComponent; -import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; import org.openecomp.sdc.common.api.HealthCheckWrapper; import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.common.monitoring.MonitoringEvent; @@ -54,13 +53,13 @@ import org.springframework.web.context.WebApplicationContext; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.jcabi.aspects.Loggable; + +import fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import fj.data.Either; - @Loggable(prepend = true, value = Loggable.TRACE, trim = false) @Path("/") @Api(value = "BE Monitoring", description = "BE Monitoring") @@ -75,22 +74,20 @@ public class BeMonitoringServlet extends BeGenericServlet { @Path("/healthCheck") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "return aggregate BE health check of Titan, ES and BE", notes = "return BE health check", response = String.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Titan, ES and BE are all up"), @ApiResponse(code = 500, message = "One or more BE components (Titan, ES, BE) are down") }) + @ApiOperation(value = "Return aggregate BE health check of SDC BE components", notes = "return BE health check", response = String.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "SDC BE components are all up"), @ApiResponse(code = 500, message = "One or more SDC BE components are down") }) public Response getHealthCheck(@Context final HttpServletRequest request) { try { HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(request.getSession().getServletContext()); - List beHealthCheckInfos = healthCheckBusinessLogic.getBeHealthCheckInfosStatus(); - - // List beHealthCheckInfos = - // HealthCheckBusinessLogic.getInstance().getBeHealthCheckInfos(request.getSession().getServletContext()); - ActionStatus status = getAggregateBeStatus(beHealthCheckInfos); + Pair> beHealthCheckInfosStatus = healthCheckBusinessLogic.getBeHealthCheckInfosStatus(); + Boolean aggregateStatus = beHealthCheckInfosStatus.getLeft(); + ActionStatus status = aggregateStatus ? ActionStatus.OK : ActionStatus.GENERAL_ERROR; String sdcVersion = getVersionFromContext(request); if (sdcVersion == null || sdcVersion.isEmpty()) { sdcVersion = "UNKNOWN"; } String siteMode = healthCheckBusinessLogic.getSiteMode(); - HealthCheckWrapper healthCheck = new HealthCheckWrapper(beHealthCheckInfos, sdcVersion, siteMode); + HealthCheckWrapper healthCheck = new HealthCheckWrapper(beHealthCheckInfosStatus.getRight(), sdcVersion, siteMode); // The response can be either with 200 or 500 aggregate status - the // body of individual statuses is returned either way @@ -168,17 +165,6 @@ public class BeMonitoringServlet extends BeGenericServlet { return version; } - private ActionStatus getAggregateBeStatus(List beHealthCheckInfos) { - ActionStatus status = ActionStatus.OK; - for (HealthCheckInfo healthCheckInfo : beHealthCheckInfos) { - if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN) && healthCheckInfo.getHealthCheckComponent() != HealthCheckComponent.DE) { - status = ActionStatus.GENERAL_ERROR; - break; - } - } - return status; - } - protected MonitoringEvent convertContentToJson(String content, Class clazz) { MonitoringEvent object = null; 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 a89d8b109b..b5971670cf 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 @@ -22,6 +22,7 @@ package org.openecomp.sdc.be.servlets; import java.io.InputStream; import java.lang.reflect.Type; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -42,6 +43,7 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.map.ObjectMapper; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; @@ -78,12 +80,11 @@ import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; /** - * Root resource (exposed at "/" path) - * .json + * Root resource (exposed at "/" path) .json */ @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") -@Api(value = "Resource Instance Servlet", description = "Resource Instance Servlet") +@Api(value = "Resource Instance Servlet") @Singleton public class ComponentInstanceServlet extends AbstractValidationsServlet { @@ -227,9 +228,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { if (convertResponse.isRight()) { // Using both ECOMP error methods, show to Sofer BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance"); - /* - * BeEcompErrorManager.getInstance().processEcompError( EcompErrorName.BeSystemError, "Resource Instance - updateResourceInstance"); - */ log.debug("Failed to convert received data to BE format."); return buildErrorResponse(convertResponse.right().value()); } @@ -358,8 +356,8 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { public Response dissociateRIFromRI( @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam("containerComponentType") final String containerComponentType, - @ApiParam(value = "unique id of the container component") @PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "RelationshipInfo", required = true) String data, - @Context final HttpServletRequest request) { + @ApiParam(value = "unique id of the container component") @PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @ApiParam(value = "RelationshipInfo", required = true) String data, @Context final HttpServletRequest request) { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); @@ -517,7 +515,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } } - + @POST @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/input") @Consumes(MediaType.APPLICATION_JSON) @@ -535,8 +533,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { try { Wrapper dataWrapper = new Wrapper<>(); Wrapper errorWrapper = new Wrapper<>(); - Wrapper propertyWrapper = new Wrapper<>(); - + validateInputStream(request, dataWrapper, errorWrapper); ComponentInstanceInput property = null; @@ -544,21 +541,22 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { 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()){ + + 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(); @@ -743,7 +741,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } } - + @POST @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}/property") @Consumes(MediaType.APPLICATION_JSON) @@ -752,8 +750,8 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { @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) { + @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); @@ -803,15 +801,15 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } } - + @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) { + 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); @@ -836,22 +834,17 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } } - - //US831698 + + // 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) { - + @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); @@ -859,19 +852,15 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { try { ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum); - - Either, ResponseFormat> componentInstancePropertiesById = componentInstanceBL - .getComponentInstancePropertiesById(containerComponentType, containerComponentId, - componentInstanceUniqueId, userId); + + 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); + 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()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value()); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); log.debug("getGroupArtifactById unexpected exception", e); @@ -879,7 +868,102 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } } - + + // US330353 + @GET + @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get component instance capability properties", httpMethod = "GET", notes = "Returns component instance capability 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/Capability - not found") }) + public Response getInstanceCapabilityPropertiesById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId, + @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @PathParam("capabilityType") final String capabilityType, @PathParam("capabilityName") final String capabilityName, @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.getComponentInstanceCapabilityPropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, + capabilityType, capabilityName, 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, ResponseFormat> convertMultipleProperties(String dataList) { + if (StringUtils.isEmpty(dataList)) { + return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + Either convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceProperty[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE); + if (convertStatus.isRight()) { + return Either.right(convertStatus.right().value()); + } + return Either.left(Arrays.asList(convertStatus.left().value())); + } + + //US 331281 + @PUT + @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Instance Capabilty Property", httpMethod = "PUT", notes = "Returns updated property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance capabilty property updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "Component/Component Instance/Capability - not found") }) + public Response updateInstanceCapabilityProperty(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId, + @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @PathParam("capabilityType") final String capabilityType, @PathParam("capabilityName") final String capabilityName, + @ApiParam(value = "Instance capabilty property to update", 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(); + log.debug("(PUT) Start handle request of {}", url); + try { + Wrapper errorWrapper = new Wrapper<>(); + List propertiesToUpdate = new ArrayList<>(); + if (errorWrapper.isEmpty()) { + Either, ResponseFormat> propertiesToUpdateEither = convertMultipleProperties(data); + if (propertiesToUpdateEither.isRight()) { + errorWrapper.setInnerElement(propertiesToUpdateEither.right().value()); + } else { + propertiesToUpdate = propertiesToUpdateEither.left().value(); + } + } + + if (!errorWrapper.isEmpty()) { + return buildErrorResponse(errorWrapper.getInnerElement()); + } + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum); + + Either, ResponseFormat> updateCICapProperty = componentInstanceBL.updateInstanceCapabilityProperties(componentTypeEnum, containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, propertiesToUpdate, userId); + + if (updateCICapProperty.isRight()) { + log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}", componentInstanceUniqueId, containerComponentType, containerComponentId); + return buildErrorResponse(updateCICapProperty.right().value()); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateCICapProperty.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); + log.debug("getGroupArtifactById unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + @POST @Path("/{containerComponentType}/{containerComponentId}/serviceProxy") @Consumes(MediaType.APPLICATION_JSON) @@ -897,7 +981,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class); componentInstance.setInvariantName(null); ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - if(componentTypeEnum != ComponentTypeEnum.SERVICE){ + if (componentTypeEnum != ComponentTypeEnum.SERVICE) { log.debug("Unsupported container component type {}", containerComponentType); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } @@ -919,7 +1003,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } - + @DELETE @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}") @Consumes(MediaType.APPLICATION_JSON) @@ -956,7 +1040,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } - + @POST @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}/changeVersion/{newServiceId}") @Consumes(MediaType.APPLICATION_JSON) @@ -981,7 +1065,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } Either actionResponse = componentInstanceLogic.changeServiceProxyVersion(containerComponentType, containerComponentId, serviceProxyId, userId); - + if (actionResponse.isRight()) { return buildErrorResponse(actionResponse.right().value()); } @@ -993,11 +1077,50 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } + /** + * REST API GET relation by Id + * Allows to get relation contained in specified component according to received Id + * @param containerComponentType + * @param componentId + * @param relationId + * @param request + * @param userId + * @return Response + */ + @GET + @Path("/{containerComponentType}/{componentId}/relationId/{relationId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get relation", httpMethod = "GET", notes = "Returns relation metadata according to relationId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "relation found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Relation not found") }) + public Response getRelationById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, + @PathParam("relationId") final String relationId, @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 componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either actionResponse = componentInstanceLogic.getRelationById(componentId, relationId, userId, componentTypeEnum); + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getRelationById"); + log.debug("getRelationById unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } private Either convertToResourceInstance(String data) { - // Either convertStatus = - // convertJsonToObject(data, ComponentInstance.class); Either convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, new User(), ComponentInstance.class, null, ComponentTypeEnum.RESOURCE_INSTANCE); if (convertStatus.isRight()) { return Either.right(convertStatus.right().value()); 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 dff6cddbbb..0c955f4e5a 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,11 +20,8 @@ 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; @@ -44,41 +41,33 @@ 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; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jcabi.aspects.Loggable; + +import fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import fj.data.Either; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Component Servlet", description = "Component Servlet") 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 c207497a22..943ed59e87 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 @@ -51,14 +51,14 @@ import org.springframework.web.context.WebApplicationContext; import com.google.gson.Gson; import com.jcabi.aspects.Loggable; + +import fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import fj.data.Either; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/consumers") @Api(value = "Consumer Servlet", description = "Consumer Servlet") diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java index f9d6f6c754..4215560020 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java @@ -48,13 +48,13 @@ import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; import com.jcabi.aspects.Loggable; + +import fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import fj.data.Either; - /** * Root resource (exposed at "/" path) */ 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 da9b867041..7a42360355 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 @@ -20,8 +20,27 @@ package org.openecomp.sdc.be.servlets; -import com.jcabi.aspects.Loggable; -import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.inject.Singleton; +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.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + import org.openecomp.sdc.be.components.clean.ComponentsCleanBusinessLogic; import org.openecomp.sdc.be.components.impl.ElementBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -31,7 +50,12 @@ 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.ArtifactTypesInfo; -import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.ArtifactType; +import org.openecomp.sdc.be.model.Category; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.PropertyScope; +import org.openecomp.sdc.be.model.Tag; +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; @@ -43,21 +67,15 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Singleton; +import com.jcabi.aspects.Loggable; + +import fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.util.*; - @Path("/v1/") /**** @@ -467,6 +485,7 @@ public class ElementServlet extends BeGenericServlet { configuration.put("componentTypes", elementBL.getAllComponentTypesParamNames()); configuration.put("roles", elementBL.getAllSupportedRoles()); configuration.put("resourceTypes", resourceTypesMap.left().value()); + configuration.put("environmentContext", ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext()); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), configuration); } 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 f7e7ae2da1..22391bbdc1 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 @@ -46,7 +46,6 @@ 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; -import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -54,14 +53,14 @@ import org.slf4j.LoggerFactory; import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import com.jcabi.aspects.Loggable; + +import fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import fj.data.Either; - /** * Root resource (exposed at "/" path) */ @@ -106,7 +105,7 @@ public class GroupServlet extends AbstractValidationsServlet { return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - } catch (Throwable e) { + } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); log.debug("getGroupArtifactById unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); 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 448c31cf63..4de5488351 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,7 +30,6 @@ 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; @@ -40,7 +39,6 @@ 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; @@ -55,21 +53,20 @@ 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 org.springframework.web.context.WebApplicationContext; import com.jcabi.aspects.Loggable; + +import fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import fj.data.Either; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Input Catalog", description = "Input Servlet") 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 89b73eb3e4..c2d7c2a6a1 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 @@ -53,14 +53,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jcabi.aspects.Loggable; + +import fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import fj.data.Either; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Lifecycle Actions Servlet", description = "Lifecycle Actions Servlet") diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java index 209f38d8a4..c0c987b78a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java @@ -99,7 +99,7 @@ public class ProductServlet extends BeGenericServlet { response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result); return response; - } catch (Throwable e) { + } catch (Exception e) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Product"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Product"); log.debug("create product failed with error ", e); @@ -141,7 +141,7 @@ public class ProductServlet extends BeGenericServlet { Object product = RepresentationUtils.toRepresentation(actionResponse.left().value()); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product); - } catch (Throwable e) { + } catch (Exception e) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Product"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Product"); log.debug("get product failed with error ", e); @@ -221,7 +221,7 @@ public class ProductServlet extends BeGenericServlet { response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product); return response; - } catch (Throwable e) { + } catch (Exception e) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Resource"); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource"); log.debug("delete resource failed with error ", e); 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 04428aaa9a..bc5ad35c8f 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 @@ -68,14 +68,14 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.jcabi.aspects.Loggable; + +import fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import fj.data.Either; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Resource Property Servlet", description = "Resource Property Servlet") diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java index e59987fc55..fb4aba6af7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java @@ -39,6 +39,7 @@ import org.slf4j.LoggerFactory; import com.google.gson.JsonSyntaxException; import com.jcabi.aspects.Loggable; + import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; 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 35431c710c..3cf2a69fb5 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 @@ -54,6 +54,7 @@ import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; import com.jcabi.aspects.Loggable; + import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; 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 66da1d7150..8aa5093404 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 @@ -67,14 +67,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jcabi.aspects.Loggable; + +import fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import fj.data.Either; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Resources Catalog", description = "Resources Servlet") 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 f38cd85026..cb90d89ed9 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 @@ -70,14 +70,14 @@ import org.slf4j.LoggerFactory; import com.google.gson.reflect.TypeToken; import com.jcabi.aspects.Loggable; + +import fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import fj.data.Either; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Service Catalog", description = "Service Servlet") @@ -763,7 +763,6 @@ public class ServiceServlet extends AbstractValidationsServlet { } catch (Exception 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 2e961f294b..3ad15961e7 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 @@ -20,7 +20,6 @@ package org.openecomp.sdc.be.servlets; -import java.lang.reflect.Type; import java.util.Map; import javax.inject.Singleton; @@ -40,9 +39,7 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintSerialiser; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.common.datastructure.Wrapper; @@ -51,17 +48,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; import com.jcabi.aspects.Loggable; + +import fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import fj.data.Either; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Types Fetch Servlet", description = "Types Fetch Servlet") 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 f96d52adb1..bb0be372bf 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,8 +42,6 @@ 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; @@ -60,22 +58,22 @@ import org.openecomp.sdc.be.model.GroupTypeDefinition; import org.openecomp.sdc.be.model.PolicyTypeDefinition; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.datastructure.FunctionalInterfaces.ConsumerTwoParam; +import org.openecomp.sdc.common.datastructure.Wrapper; 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 fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import fj.data.Either; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog/uploadType") @Api(value = "Catalog Types Upload", description = "Upload Type from yaml") 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 67230470ff..a6f6359ac1 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 @@ -53,14 +53,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jcabi.aspects.Loggable; + +import fj.data.Either; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import fj.data.Either; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/user") @Api(value = "User Administration", description = "User admininstarator operations") 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 876066b9ba..faebb7614b 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 @@ -34,8 +34,8 @@ import javax.annotation.PreDestroy; import org.apache.commons.codec.binary.Base64; import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.Configuration.SwitchoverDetectorConfig; +import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.rest.HttpRestClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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 41268188f9..886b654b81 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 @@ -1,5 +1,4 @@ /*- - * ============LICENSE_START======================================================= * SDC * ================================================================================ @@ -81,9 +80,7 @@ public class CapabiltyRequirementConvertor { @Autowired private ToscaOperationFacade toscaOperationFacade; - protected CapabiltyRequirementConvertor() { - - } + protected CapabiltyRequirementConvertor() {} public static synchronized CapabiltyRequirementConvertor getInstance() { if (instance == null) { @@ -117,9 +114,8 @@ public class CapabiltyRequirementConvertor { } private void convertOverridenProperties(ComponentInstance componentInstance, Map dataTypes, Map capabilties, CapabilityDefinition c) { - List properties = c.getProperties(); - if (properties != null && !properties.isEmpty()) { - properties + if (CollectionUtils.isNotEmpty(c.getProperties())) { + c.getProperties() .stream() .filter(p -> p.getValue() != null || p.getDefaultValue() != null) .forEach(p -> convertOverridenProperty(componentInstance, dataTypes, capabilties, c, p)); @@ -331,7 +327,9 @@ public class CapabiltyRequirementConvertor { result = Either.right(false); } if(result == null){ - result = buildSubstitutedName(componentsCache, getOriginRes.left().value(), Lists.newArrayList(path.subList(0, path.size()-1)), name); + List reducedPath = getReducedPath(path); + reducedPath.remove(reducedPath.size()-1); + result = buildSubstitutedName(componentsCache, getOriginRes.left().value(), reducedPath, name); } return result; } @@ -432,12 +430,12 @@ public class CapabiltyRequirementConvertor { */ public Either, ToscaError> convertSubstitutionMappingCapabilities(Map componentsCache, Component component) { Map> capabilities = component.getCapabilities(); - Either, ToscaError> res = null; + Either, ToscaError> res; if (capabilities != null) { res = buildAddSubstitutionMappingsCapabilities(componentsCache, component, capabilities); } else { + res = Either.left(Maps.newHashMap()); logger.debug(NO_CAPABILITIES); - res = Either.left(new HashMap<>()); } return res; } @@ -483,7 +481,7 @@ public class CapabiltyRequirementConvertor { toscaCapability.setValid_source_types(c.getValidSourceTypes()); List properties = c.getProperties(); - if (properties != null && !properties.isEmpty()) { + if (CollectionUtils.isNotEmpty(properties)) { Map toscaProperties = new HashMap<>(); for (PropertyDefinition property : properties) { ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(dataTypes, property, true); @@ -493,15 +491,22 @@ public class CapabiltyRequirementConvertor { } toscaCapabilities.put(name, toscaCapability); } - - Either buildSubstitutedName(Map originComponents, Component originComponent, List path, String name) { + /** + * Allows to build substituted name of capability\requirement of the origin component instance according to the path + * @param componentsCache + * @param originComponent + * @param path + * @param name + * @return + */ + public Either buildSubstitutedName(Map componentsCache, Component originComponent, List path, String name) { StringBuilder substitutedName = new StringBuilder(); boolean nameBuiltSuccessfully = true; Either result; if(CollectionUtils.isNotEmpty(path) && !ToscaUtils.isComplexVfc(originComponent)){ - Collections.reverse(path); - Iterator instanceIdIter = path.iterator(); - nameBuiltSuccessfully = appendNameRecursively(originComponents, originComponent, instanceIdIter, substitutedName); + List reducedPath = getReducedPath(path); + Collections.reverse(reducedPath); + nameBuiltSuccessfully = appendNameRecursively(componentsCache, originComponent, reducedPath.iterator(), substitutedName); } if(nameBuiltSuccessfully){ result = Either.left(substitutedName.append(name).toString()); @@ -511,43 +516,57 @@ public class CapabiltyRequirementConvertor { return result; } - private boolean appendNameRecursively(Map originComponents, Component originComponent, Iterator instanceIdIter, StringBuilder substitutedName) { - if(CollectionUtils.isNotEmpty(originComponent.getComponentInstances()) && instanceIdIter.hasNext()){ + private List getReducedPath(List path) { + List pathCopy = Lists.newArrayList(); + path.stream().forEach(id -> {if(!pathCopy.contains(id))pathCopy.add(id);}); + return pathCopy; + } + + private boolean appendNameRecursively(Map componentsCache, Component originComponent, Iterator instanceIdIter, StringBuilder substitutedName) { + if(CollectionUtils.isNotEmpty(originComponent.getComponentInstances()) && instanceIdIter.hasNext() && !ToscaUtils.isComplexVfc(originComponent)){ String instanceId = instanceIdIter.next(); Optional instanceOpt = originComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); if(!instanceOpt.isPresent()){ logger.debug("Failed to find an instance with uniqueId {} on a component with uniqueId {}", instanceId, originComponent.getUniqueId()); return false; } - Either getOriginRes = getOriginComponent(originComponents, instanceOpt.get()); + substitutedName.append(instanceOpt.get().getNormalizedName()).append('.'); + Either getOriginRes = getOriginComponent(componentsCache, instanceOpt.get()); if(getOriginRes.isRight()){ return false; } - appendNameRecursively(originComponents, getOriginRes.left().value(), instanceIdIter, substitutedName); - substitutedName.append(instanceOpt.get().getNormalizedName()).append('.'); - return true; + appendNameRecursively(componentsCache, getOriginRes.left().value(), instanceIdIter, substitutedName); } return true; } - private Either getOriginComponent(Map originComponents, ComponentInstance instance) { + Either getOriginComponent(Map componentsCache, ComponentInstance instance) { Either result; Either getOriginRes; - if(originComponents.containsKey(instance.getComponentUid())){ - result = Either.left(originComponents.get(instance.getComponentUid())); + if(componentsCache.containsKey(instance.getActualComponentUid())){ + result = Either.left(componentsCache.get(instance.getActualComponentUid())); } else { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreComponentInstances(false); - getOriginRes = toscaOperationFacade.getToscaElement(instance.getComponentUid(), filter); + ComponentParametersView filter = getFilter(instance); + getOriginRes = toscaOperationFacade.getToscaElement(instance.getActualComponentUid(), filter); if(getOriginRes.isRight()){ - logger.debug("Failed to get an origin component with uniqueId {}", instance.getComponentUid()); + logger.debug("Failed to get an origin component with uniqueId {}", instance.getActualComponentUid()); result = Either.right(false); } else { result = Either.left(getOriginRes.left().value()); - originComponents.put(getOriginRes.left().value().getUniqueId(), getOriginRes.left().value()); + componentsCache.put(getOriginRes.left().value().getUniqueId(), getOriginRes.left().value()); } } return result; } + private ComponentParametersView getFilter(ComponentInstance instance) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreComponentInstances(false); + if(instance.getIsProxy()){ + filter.setIgnoreCapabilities(false); + filter.setIgnoreRequirements(false); + } + return filter; + } + } 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 2f4a385f69..f6ae79b26a 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,8 +20,26 @@ package org.openecomp.sdc.be.tosca; -import com.google.gson.Gson; -import fj.data.Either; +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.EnumMap; +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.ZipInputStream; +import java.util.zip.ZipOutputStream; + import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.output.ByteArrayOutputStream; @@ -61,7 +79,6 @@ import org.openecomp.sdc.be.tosca.model.ToscaTemplate; 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.api.Constants; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.util.GeneralUtility; import org.openecomp.sdc.common.util.ValidationUtils; @@ -75,25 +92,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import java.io.BufferedOutputStream; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.EnumMap; -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.ZipInputStream; -import java.util.zip.ZipOutputStream; +import com.google.gson.Gson; + +import fj.data.Either; /** @@ -254,7 +255,8 @@ public class CsarUtils { String cassandraId = artifactDefinition.getEsId(); Either fromCassandra = getFromCassandra(cassandraId); if (fromCassandra.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(fromCassandra.right().value()); + log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(fromCassandra.right().value()); return Either.right(responseFormat); } mainYaml = fromCassandra.left().value(); @@ -328,6 +330,12 @@ public class CsarUtils { // add component to zip Either entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent); + if (entryData.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); + log.debug("Failed adding to zip component {}, error {}", innerComponentTriple.getLeft(), + entryData.right().value()); + return Either.right(responseFormat); + } byte[] content = entryData.left().value(); zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName)); zip.write(content); @@ -394,7 +402,7 @@ public class CsarUtils { final int initSize = 2048; - log.debug("Starting coppy from Schema file zip to CSAR zip"); + log.debug("Starting copy from Schema file zip to CSAR zip"); try (ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip)); ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -657,7 +665,7 @@ public class CsarUtils { null, null, user, component, shouldLock, inTransaction, false); if (validateAndHandleArtifact.isRight()) { - if (ArtifactOperationEnum.Create == operationType.getArtifactOperationEnum() || ArtifactOperationEnum.Update == operationType.getArtifactOperationEnum()) { + if (ArtifactOperationEnum.isCreateOrLink(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); @@ -739,7 +747,7 @@ public class CsarUtils { } else { Either fromCassandra = getFromCassandra(cassandraId); if (fromCassandra.isRight()) { - return Either.right(fromCassandra.right().value()); + return Either.right(fromCassandra.right().value()); } else { content = fromCassandra.left().value(); } @@ -773,19 +781,16 @@ public class CsarUtils { 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 {} ", cassandraId, artifactResponse.right().value()); + log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value()); StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value()); ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); return Either.right(convertedFromStorageResponse); - } else { - ESArtifactData artifactData = artifactResponse.left().value(); - return Either.left(artifactData.getDataAsArray()); - } + ESArtifactData artifactData = artifactResponse.left().value(); + return Either.left(artifactData.getDataAsArray()); } - + private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) { final String BLOCK_0_TEMPLATE = "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n"; @@ -1201,18 +1206,20 @@ public class CsarUtils { for (ArtifactDefinition artifactDefinition : artifactDefinitionList) { if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE - && artifactDefinition.getArtifactType().equals(heatEnvType)){ + && artifactDefinition.getArtifactType().equals(heatEnvType) || + //this is placeholder + (artifactDefinition.getEsId() == null && artifactDefinition.getMandatory())){ continue; } - String esId = artifactDefinition.getEsId(); byte[] payloadData = artifactDefinition.getPayloadData(); String artifactFileName = artifactDefinition.getArtifactName(); if (payloadData == null) { - Either fromCassandra = getFromCassandra(esId); + Either fromCassandra = getFromCassandra(artifactDefinition.getEsId()); if (fromCassandra.isRight()) { + log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId()); log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value()); continue; } 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 22f6730eb1..083ea67769 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 @@ -145,7 +145,7 @@ public class PropertyConvertor { } innerConverter = type.getValueConverter(); - if (ToscaPropertyType.STRING.equals(type) && value.startsWith("/")) { + if (ToscaPropertyType.STRING.equals(type) && valueStartsWithNonJsonChar(value)) { return innerConverter.convertToToscaValue(value, innerType, dataTypes); } } @@ -192,4 +192,8 @@ public class PropertyConvertor { } + private boolean valueStartsWithNonJsonChar(String value) { + return value.startsWith("/") || value.startsWith(":"); + } + } 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 1f29eb2113..c37c15f694 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 @@ -57,7 +57,7 @@ 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.RelationshipInfo; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.Resource; @@ -110,7 +110,7 @@ public class ToscaExportHandler { @Autowired private CapabiltyRequirementConvertor capabiltyRequirementConvertor; private PropertyConvertor propertyConvertor = PropertyConvertor.getInstance(); - Map originComponents = new HashMap<>(); + Map originComponents = new HashMap<>(); private static Logger log = LoggerFactory.getLogger(ToscaExportHandler.class.getName()); @@ -127,7 +127,8 @@ public class ToscaExportHandler { public static final String VF_MODULE_TYPE_EXPANSION = "Expansion"; private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration"; private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}"; - protected static final List>> DEFAULT_IMPORTS = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultImports(); + protected static final List>> DEFAULT_IMPORTS = ConfigurationManager + .getConfigurationManager().getConfiguration().getDefaultImports(); public Either exportComponent(Component component) { @@ -229,7 +230,7 @@ public class ToscaExportHandler { return Either.right(importsRes.right().value()); } toscaNode = importsRes.left().value().left; - /*Either, ToscaError> nodeTypesMapEither = createProxyNodeTypes(component); + Either, ToscaError> nodeTypesMapEither = createProxyNodeTypes(component); if (nodeTypesMapEither.isRight()) { log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", nodeTypesMapEither.right().value()); @@ -237,7 +238,7 @@ public class ToscaExportHandler { } Map nodeTypesMap = nodeTypesMapEither.left().value(); if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) - toscaNode.setNode_types(nodeTypesMap);*/ + toscaNode.setNode_types(nodeTypesMap); Map componentCache = importsRes.left().value().right; Either, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); @@ -274,8 +275,17 @@ public class ToscaExportHandler { if (groups != null && !groups.isEmpty()) { groupsMap = new HashMap<>(); for (GroupDefinition group : groups) { - ToscaGroupTemplate toscaGroup = convertGroup(group); - groupsMap.put(group.getName(), toscaGroup); + boolean addToTosca = true; + if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) { + List artifacts = group.getArtifacts(); + if (artifacts == null || artifacts.isEmpty()) { + addToTosca = false; + } + } + if (addToTosca) { + ToscaGroupTemplate toscaGroup = convertGroup(group); + groupsMap.put(group.getName(), toscaGroup); + } } log.debug("groups converted"); @@ -343,10 +353,10 @@ public class ToscaExportHandler { private ToscaMetadata convertMetadata(Component component, boolean isInstance, ComponentInstance componentInstance) { ToscaMetadata toscaMetadata = new ToscaMetadata(); - toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); toscaMetadata.setInvariantUUID(component.getInvariantUUID()); toscaMetadata.setUUID(component.getUUID()); toscaMetadata.setDescription(component.getDescription()); + toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); List categories = component.getCategories(); CategoryDefinition categoryDefinition = categories.get(0); @@ -355,11 +365,26 @@ public class ToscaExportHandler { if (isInstance) { toscaMetadata.setVersion(component.getVersion()); toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID()); + if (componentInstance.getSourceModelInvariant() != null + && !componentInstance.getSourceModelInvariant().isEmpty()) { + toscaMetadata.setVersion(componentInstance.getComponentVersion()); + toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant()); + toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid()); + toscaMetadata.setSourceModelName(componentInstance.getSourceModelName()); + toscaMetadata.setName( + componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue()); + toscaMetadata.setDescription(componentInstance.getDescription()); + } + } switch (component.getComponentType()) { case RESOURCE: Resource resource = (Resource) component; - toscaMetadata.setType(resource.getResourceType().name()); + + if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) { + toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue()); + } else + toscaMetadata.setType(resource.getResourceType().name()); toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName()); toscaMetadata.setResourceVendor(resource.getVendorName()); toscaMetadata.setResourceVendorRelease(resource.getVendorRelease()); @@ -370,15 +395,16 @@ public class ToscaExportHandler { toscaMetadata.setType(component.getComponentType().getValue()); toscaMetadata.setServiceType(service.getServiceType()); toscaMetadata.setServiceRole(service.getServiceRole()); + toscaMetadata.setEnvironmentContext(service.getEnvironmentContext()); if (!isInstance) { // DE268546 - toscaMetadata.setServiceEcompNaming(((Service)component).isEcompGeneratedNaming()); - toscaMetadata.setEcompGeneratedNaming(((Service)component).isEcompGeneratedNaming()); - toscaMetadata.setNamingPolicy(((Service)component).getNamingPolicy()); + toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming()); + toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming()); + toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy()); } break; default: - log.debug("Not supported component type {}", component.getComponentType()); + log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); } return toscaMetadata; } @@ -472,7 +498,7 @@ public class ToscaExportHandler { } public static String getInterfaceFilename(String artifactName) { - return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME; + return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME; } private Either convertNodeType(Component component, ToscaTemplate toscaNode, @@ -539,7 +565,8 @@ 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()); } @@ -584,9 +611,15 @@ public class ToscaExportHandler { ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate(); nodeTemplate.setType(componentInstance.getToscaComponentName()); + Either originComponentRes = capabiltyRequirementConvertor + .getOriginComponent(componentCache, componentInstance); + if (originComponentRes.isRight()) { + convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); + break; + } Either requirements = convertComponentInstanceRequirements(component, componentInstance, component.getComponentInstancesRelations(), nodeTemplate, - componentCache.get(componentInstance.getComponentUid())); + originComponentRes.left().value()); if (requirements.isRight()) { convertNodeTemplatesRes = Either.right(requirements.right().value()); break; @@ -596,7 +629,7 @@ public class ToscaExportHandler { nodeTemplate = requirements.left().value(); - Component componentOfInstance = componentCache.get(componentInstance.getComponentUid()); + Component componentOfInstance = componentCache.get(componentInstance.getActualComponentUid()); nodeTemplate.setMetadata(convertMetadata(componentOfInstance, true, componentInstance)); Either capabilities = capabiltyRequirementConvertor @@ -634,9 +667,17 @@ public class ToscaExportHandler { groupsMap = new HashMap<>(); } for (GroupInstance groupInst : groupInstances) { - ToscaGroupTemplate toscaGroup = convertGroupInstance(groupInst); + boolean addToTosca = true; + + List artifacts = groupInst.getArtifacts(); + if (artifacts == null || artifacts.isEmpty()) { + addToTosca = false; + } - groupsMap.put(groupInst.getName(), toscaGroup); + if (addToTosca) { + ToscaGroupTemplate toscaGroup = convertGroupInstance(groupInst); + groupsMap.put(groupInst.getName(), toscaGroup); + } } } @@ -729,6 +770,7 @@ public class ToscaExportHandler { } private ToscaGroupTemplate convertGroup(GroupDefinition group) { + ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate(); Map members = group.getMembers(); if (members != null) @@ -845,7 +887,7 @@ public class ToscaExportHandler { return toscaNodeType; } - /*private Either, ToscaError> createProxyNodeTypes(Component container) { + private Either, ToscaError> createProxyNodeTypes(Component container) { Map nodeTypesMap = null; Either, ToscaError> res = Either.left(nodeTypesMap); @@ -855,13 +897,15 @@ public class ToscaExportHandler { if (componetInstances == null || componetInstances.isEmpty()) return res; Map serviceProxyInstanceList = new HashMap<>(); - List proxyInst = componetInstances.stream().filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name())).collect(Collectors.toList()); - if(proxyInst != null && !proxyInst.isEmpty()){ - for(ComponentInstance inst: proxyInst){ + List proxyInst = componetInstances.stream() + .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name())) + .collect(Collectors.toList()); + if (proxyInst != null && !proxyInst.isEmpty()) { + for (ComponentInstance inst : proxyInst) { serviceProxyInstanceList.put(inst.getToscaComponentName(), inst); } } - + if (serviceProxyInstanceList.isEmpty()) return res; ComponentParametersView filter = new ComponentParametersView(true); @@ -894,7 +938,7 @@ public class ToscaExportHandler { } return Either.left(nodeTypesMap); - }*/ + } private ToscaNodeType createProxyNodeType(Component origComponent, Component proxyComponent, ComponentInstance instance) { @@ -920,8 +964,9 @@ public class ToscaExportHandler { ToscaNodeTemplate nodeTypeTemplate, Component originComponent) { List> toscaRequirements = new ArrayList<>(); - if(!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements)){ - log.debug("Failed to convert component instance requirements for the component instance {}. ", componentInstance.getName()); + if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements)) { + log.debug("Failed to convert component instance requirements for the component instance {}. ", + componentInstance.getName()); return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); } if (!toscaRequirements.isEmpty()) { @@ -931,82 +976,114 @@ public class ToscaExportHandler { return Either.left(nodeTypeTemplate); } - private boolean addRequirements(Component component, ComponentInstance componentInstance, List relations, Component originComponent, + private boolean addRequirements(Component component, ComponentInstance componentInstance, + List relations, Component originComponent, List> toscaRequirements) { boolean result; - List filteredRelations = relations.stream().filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList()); - if(CollectionUtils.isEmpty(filteredRelations)){ + List filteredRelations = relations.stream() + .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList()); + if (CollectionUtils.isEmpty(filteredRelations)) { result = true; } else { - result = !filteredRelations.stream().filter(rel -> !addRequirement(component,componentInstance, originComponent, component.getComponentInstances(), rel, toscaRequirements)).findFirst().isPresent(); + result = !filteredRelations.stream().filter(rel -> !addRequirement(componentInstance, originComponent, + component.getComponentInstances(), rel, toscaRequirements)).findFirst().isPresent(); } return result; } - - private boolean addRequirement(Component component,ComponentInstance fromInstance, Component originComponent, List instancesList, RequirementCapabilityRelDef rel, List> toscaRequirements){ - + + private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent, + List instancesList, RequirementCapabilityRelDef rel, + List> toscaRequirements) { + boolean result = true; - Map originComponents = new HashMap<>(); - Map> reqMap = originComponent.getRequirements(); - RequirementAndRelationshipPair reqAndRelationshipPair = rel.getRelationships().get(0); + Map> reqMap = fromOriginComponent.getRequirements(); + RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation(); Either getOriginRes = null; Optional reqOpt = null; Component toOriginComponent = null; Optional cap = null; - Either buildCapNameRes = null; - Either buildReqNameRes = null; - - ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId())).findFirst().orElse(null); + + ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId())) + .findFirst().orElse(null); if (toInstance == null) { - log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(), rel.getToNode()); + log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(), + rel.getToNode()); result = false; } - if(result){ - - if(component.getComponentType().equals(ComponentTypeEnum.SERVICE)) { - reqOpt = findRequirement(reqMap, reqAndRelationshipPair); - } - else { - reqOpt = findRequirement(reqMap, reqAndRelationshipPair.getRequirementUid()); - } - if(!reqOpt.isPresent()){ - log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}", reqAndRelationshipPair.getRequirementUid(), originComponent.getUniqueId()); + if (result) { + reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, toInstance.getUniqueId()); + if (!reqOpt.isPresent()) { + log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}", + reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId()); result = false; } } - if(result){ + if (result) { ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnoreComponentInstances(false); filter.setIgnoreCapabilities(false); - getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getComponentUid(), filter); - if(getOriginRes.isRight()){ - log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}", reqOpt.get().getName(), toInstance.getComponentUid()); + getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter); + if (getOriginRes.isRight()) { + log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}", + reqOpt.get().getName(), toInstance.getActualComponentUid()); result = false; } } - if(result){ + if (result) { toOriginComponent = getOriginRes.left().value(); - cap = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream().filter(c -> c.getName().equals(reqAndRelationshipPair.getCapability())).findFirst(); - if(!cap.isPresent()){ - log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), originComponent.getUniqueId()); + cap = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream() + .filter(c -> c.getName().equals(reqAndRelationshipPair.getCapability())).findFirst(); + if (!cap.isPresent()) { + cap = findCapability(reqMap, reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get(), fromInstance); + if(!cap.isPresent()){ result = false; + log.debug("Failed to find a capability with name {} on a component with uniqueId {}", + reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); + } } } - if(result){ - buildCapNameRes = capabiltyRequirementConvertor.buildSubstitutedName(originComponents, toOriginComponent, cap.get().getPath(), reqAndRelationshipPair.getCapability()); - if(buildCapNameRes.isRight()){ - log.debug("Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), originComponent.getUniqueId()); - result = false; - } + if (result) { + result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, cap.get(), + reqOpt.get(), reqAndRelationshipPair, toInstance); } - if(result){ - buildReqNameRes = capabiltyRequirementConvertor.buildSubstitutedName(originComponents, originComponent, reqOpt.get().getPath(), reqAndRelationshipPair.getRequirement()); - if(buildReqNameRes.isRight()){ - log.debug("Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}", reqAndRelationshipPair.getRequirement(), originComponent.getUniqueId()); + return result; + } + + private Optional findCapability(Map> reqMap, RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement, ComponentInstance fromInstance) { + Optional cap = Optional.empty(); + Optional findAny = reqMap.values().stream().flatMap(e -> e.stream()).filter(e -> e.getName().equals(reqAndRelationshipPair.getRequirement())).findAny(); + if (findAny.isPresent()) { + RequirementDefinition reqDefinition = findAny.get(); + cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(reqDefinition.getCapability())).findFirst(); + if (!cap.isPresent()) { + log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); + } + } + return cap; + } + + private boolean buildAndAddRequirement(List> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance) { + boolean result = true; + Either buildReqNameRes = null; + Either buildCapNameRes = capabiltyRequirementConvertor.buildSubstitutedName(originComponents, + toOriginComponent, capability.getPath(), reqAndRelationshipPair.getCapability()); + if (buildCapNameRes.isRight()) { + log.debug( + "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}", + reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); + result = false; + } + if (result) { + buildReqNameRes = capabiltyRequirementConvertor.buildSubstitutedName(originComponents, fromOriginComponent, + requirement.getPath(), reqAndRelationshipPair.getRequirement()); + if (buildReqNameRes.isRight()) { + log.debug( + "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}", + reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId()); result = false; } } - if(result){ + if (result) { ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement(); Map toscaReqMap = new HashMap<>(); toscaRequirement.setNode(toInstance.getName()); @@ -1017,39 +1094,49 @@ public class ToscaExportHandler { return result; } - private Optional findRequirement(Map> reqMap, String reqId) { + private Optional findRequirement(Component fromOriginComponent, Map> reqMap, RelationshipInfo reqAndRelationshipPair, String toInstanceId) { for(List reqList: reqMap.values()){ - Optional reqOpt = reqList.stream().filter(r -> r.getUniqueId().equals(reqId)).findFirst(); + Optional reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, toInstanceId)).findFirst(); if(reqOpt.isPresent()){ return reqOpt; } } return Optional.empty(); } - - private Optional findRequirement(Map> reqMap, RequirementAndRelationshipPair reqAndRelationshipPair) { - for(List reqList: reqMap.values()){ - Optional reqOpt = reqList.stream().filter(r -> - isRequirmentBelongTo(reqAndRelationshipPair, r)) - .findFirst(); - if(reqOpt.isPresent()){ - return reqOpt; - } - } - return Optional.empty(); + + /** + * Allows detecting the requirement belonging to the received relationship + * The detection logic is: A requirement belongs to a relationship IF 1.The + * name of the requirement equals to the "requirement" field of the + * relation; AND 2. In case of a non-atomic resource, OwnerId of the + * requirement equals to requirementOwnerId of the relation OR uniqueId of + * toInstance equals to capabilityOwnerId of the relation + * + * @param fromOriginComponent + * @param reqAndRelationshipPair + * @param requirement + * @param toInstanceId + * @return + */ + private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String toInstanceId) { + if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) + return false; + if (!ModelConverter.isAtomicComponent(originComponent)) + return isRequirementBelongToOwner(reqAndRelationshipPair, requirement, toInstanceId); + return true; } - private boolean isRequirmentBelongTo(RequirementAndRelationshipPair reqAndRelationshipPair, RequirementDefinition r) { - return StringUtils.isNotEmpty(r.getOwnerId()) && r.getOwnerId().equals(reqAndRelationshipPair.getRequirementOwnerId()) - && StringUtils.isNotEmpty(r.getName()) && r.getName().equals(reqAndRelationshipPair.getRequirement()); + private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String toInstanceId) { + return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || StringUtils.equals(toInstanceId, reqAndRelationshipPair.getCapabilityOwnerId()); } - private Either convertCapabilities(Component component, SubstitutionMapping substitutionMappings) { - - Either result = Either.left(substitutionMappings);; + private Either convertCapabilities(Component component, + SubstitutionMapping substitutionMappings) { + + Either result = Either.left(substitutionMappings); Either, ToscaError> toscaCapabilitiesRes = capabiltyRequirementConvertor .convertSubstitutionMappingCapabilities(originComponents, component); - if(toscaCapabilitiesRes.isRight()){ + if (toscaCapabilitiesRes.isRight()) { result = Either.right(toscaCapabilitiesRes.right().value()); log.error("Failed convert capabilities for the component {}. ", component.getName()); } else if (MapUtils.isNotEmpty(toscaCapabilitiesRes.left().value())) { @@ -1108,6 +1195,7 @@ public class ToscaExportHandler { } private class RepresentNull implements Represent { + @Override public Node representData(Object data) { // possible values are here http://yaml.org/type/null.html return representScalar(Tag.NULL, ""); 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 604a52083b..4f91e211cc 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 @@ -38,7 +38,12 @@ public class ToscaMetadata implements IToscaMetadata { private Boolean serviceEcompNaming; private Boolean ecompGeneratedNaming; private String namingPolicy; - + private String sourceModelInvariant; + private String environmentContext; + private String sourceModelName; + private String sourceModelUuid; + + public String getName() { return name; } @@ -179,4 +184,37 @@ public class ToscaMetadata implements IToscaMetadata { this.customizationUUID = customizationUUID; } + public String getSourceModelInvariant() { + return sourceModelInvariant; + } + + public void setSourceModelInvariant(String sourceModelInvariant) { + this.sourceModelInvariant = sourceModelInvariant; + } + + public String getSourceModelName() { + return sourceModelName; + } + + public void setSourceModelName(String sourceModelName) { + this.sourceModelName = sourceModelName; + } + + public String getSourceModelUuid() { + return sourceModelUuid; + } + + public void setSourceModelUuid(String sourceModelUuid) { + this.sourceModelUuid = sourceModelUuid; + } + + + + public String getEnvironmentContext() { + return environmentContext; + } + + public void setEnvironmentContext(String environmentContext) { + this.environmentContext = environmentContext; + } } 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 7135bfb62e..90318a6259 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 @@ -34,7 +34,6 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.utils.UserStatusEnum; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java index 7485a8dc43..7098021d1f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java @@ -20,16 +20,16 @@ package org.openecomp.sdc.common.transaction.mngr; -import fj.P; -import fj.data.Either; -import fj.data.HashMap; -import fj.data.List; - import org.openecomp.sdc.common.transaction.api.RollbackHandler; import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; import org.openecomp.sdc.common.util.MethodActivationStatusEnum; +import fj.P; +import fj.data.Either; +import fj.data.HashMap; +import fj.data.List; + public class RollbackManager { private final HashMap rollbackHandlersMap; private final Integer transactionId; -- cgit 1.2.3-korg