Search in sources :

Example 56 with SyncException

use of com.commercetools.sync.commons.exceptions.SyncException in project commercetools-sync-java by commercetools.

the class ProductSyncIT method sync_withProductContainingAttributeChanges_shouldSyncProductCorrectly.

@Test
void sync_withProductContainingAttributeChanges_shouldSyncProductCorrectly() {
    // preparation
    final List<UpdateAction<Product>> updateActions = new ArrayList<>();
    final TriConsumer<SyncException, Optional<ProductDraft>, Optional<ProductProjection>> warningCallBack = (exception, newResource, oldResource) -> warningCallBackMessages.add(exception.getMessage());
    final ProductSyncOptions customOptions = ProductSyncOptionsBuilder.of(CTP_TARGET_CLIENT).errorCallback((exception, oldResource, newResource, actions) -> collectErrors(exception.getMessage(), exception.getCause())).warningCallback(warningCallBack).beforeUpdateCallback((actions, draft, old) -> {
        updateActions.addAll(actions);
        return actions;
    }).build();
    final ProductDraft productDraft = createProductDraftBuilder(PRODUCT_KEY_1_RESOURCE_PATH, ProductType.referenceOfId(productType.getKey())).categories(emptyList()).taxCategory(null).state(null).build();
    // Creating the attribute draft with the changes
    final AttributeDraft priceInfoAttrDraft = AttributeDraft.of("priceInfo", JsonNodeFactory.instance.textNode("100/kg"));
    final AttributeDraft angebotAttrDraft = AttributeDraft.of("angebot", JsonNodeFactory.instance.textNode("big discount"));
    final AttributeDraft unknownAttrDraft = AttributeDraft.of("unknown", JsonNodeFactory.instance.textNode("unknown"));
    // Creating the product variant draft with the product reference attribute
    final List<AttributeDraft> attributes = asList(priceInfoAttrDraft, angebotAttrDraft, unknownAttrDraft);
    final ProductVariantDraft masterVariant = ProductVariantDraftBuilder.of(productDraft.getMasterVariant()).attributes(attributes).build();
    final ProductDraft productDraftWithChangedAttributes = ProductDraftBuilder.of(productDraft).masterVariant(masterVariant).build();
    // test
    final ProductSync productSync = new ProductSync(customOptions);
    final ProductSyncStatistics syncStatistics = executeBlocking(productSync.sync(singletonList(productDraftWithChangedAttributes)));
    // assertion
    assertThat(syncStatistics).hasValues(1, 0, 1, 0, 0);
    final String causeErrorMessage = format(ATTRIBUTE_NOT_IN_ATTRIBUTE_METADATA, unknownAttrDraft.getName());
    final String expectedErrorMessage = format(FAILED_TO_BUILD_ATTRIBUTE_UPDATE_ACTION, unknownAttrDraft.getName(), productDraft.getMasterVariant().getKey(), productDraft.getKey(), causeErrorMessage);
    assertThat(errorCallBackExceptions).hasSize(1);
    assertThat(errorCallBackExceptions.get(0).getMessage()).isEqualTo(expectedErrorMessage);
    assertThat(errorCallBackExceptions.get(0).getCause().getMessage()).isEqualTo(causeErrorMessage);
    assertThat(errorCallBackMessages).containsExactly(expectedErrorMessage);
    assertThat(warningCallBackMessages).isEmpty();
    assertThat(updateActions).filteredOn(updateAction -> !(updateAction instanceof SetTaxCategory)).filteredOn(updateAction -> !(updateAction instanceof RemoveFromCategory)).containsExactlyInAnyOrder(SetAttributeInAllVariants.of(priceInfoAttrDraft, true), SetAttribute.of(1, angebotAttrDraft, true), SetAttributeInAllVariants.ofUnsetAttribute("size", true), SetAttributeInAllVariants.ofUnsetAttribute("rinderrasse", true), SetAttributeInAllVariants.ofUnsetAttribute("herkunft", true), SetAttributeInAllVariants.ofUnsetAttribute("teilstueck", true), SetAttributeInAllVariants.ofUnsetAttribute("fuetterung", true), SetAttributeInAllVariants.ofUnsetAttribute("reifung", true), SetAttributeInAllVariants.ofUnsetAttribute("haltbarkeit", true), SetAttributeInAllVariants.ofUnsetAttribute("verpackung", true), SetAttributeInAllVariants.ofUnsetAttribute("anlieferung", true), SetAttributeInAllVariants.ofUnsetAttribute("zubereitung", true), SetAttribute.ofUnsetAttribute(1, "localisedText", true), Publish.of());
}
Also used : ProductProjectionQuery(io.sphere.sdk.products.queries.ProductProjectionQuery) BeforeEach(org.junit.jupiter.api.BeforeEach) Reference(io.sphere.sdk.models.Reference) ProductVariantDraft(io.sphere.sdk.products.ProductVariantDraft) PRODUCT_TYPE_RESOURCE_PATH(com.commercetools.sync.products.ProductSyncMockUtils.PRODUCT_TYPE_RESOURCE_PATH) SyncException(com.commercetools.sync.commons.exceptions.SyncException) MoneyImpl(io.sphere.sdk.utils.MoneyImpl) StateITUtils.createState(com.commercetools.sync.integration.commons.utils.StateITUtils.createState) CategoryITUtils.getCategoryDrafts(com.commercetools.sync.integration.commons.utils.CategoryITUtils.getCategoryDrafts) TaxCategoryITUtils.createTaxCategory(com.commercetools.sync.integration.commons.utils.TaxCategoryITUtils.createTaxCategory) Channel(io.sphere.sdk.channels.Channel) Collections.singletonList(java.util.Collections.singletonList) AfterAll(org.junit.jupiter.api.AfterAll) BeforeAll(org.junit.jupiter.api.BeforeAll) Arrays.asList(java.util.Arrays.asList) OLD_CATEGORY_CUSTOM_TYPE_NAME(com.commercetools.sync.integration.commons.utils.CategoryITUtils.OLD_CATEGORY_CUSTOM_TYPE_NAME) SphereClient(io.sphere.sdk.client.SphereClient) StateType(io.sphere.sdk.states.StateType) TriConsumer(com.commercetools.sync.commons.utils.TriConsumer) ProductProjection(io.sphere.sdk.products.ProductProjection) PRODUCT_KEY_1_RESOURCE_PATH(com.commercetools.sync.products.ProductSyncMockUtils.PRODUCT_KEY_1_RESOURCE_PATH) ProductTypeITUtils.createProductType(com.commercetools.sync.integration.commons.utils.ProductTypeITUtils.createProductType) BadGatewayException(io.sphere.sdk.client.BadGatewayException) SetAttributeInAllVariants(io.sphere.sdk.products.commands.updateactions.SetAttributeInAllVariants) Price(io.sphere.sdk.products.Price) Set(java.util.Set) ProductSyncStatistics(com.commercetools.sync.products.helpers.ProductSyncStatistics) ProductSyncOptionsBuilder(com.commercetools.sync.products.ProductSyncOptionsBuilder) JsonNodeFactory(com.fasterxml.jackson.databind.node.JsonNodeFactory) ProductUpdateCommand(io.sphere.sdk.products.commands.ProductUpdateCommand) CTP_TARGET_CLIENT(com.commercetools.sync.integration.commons.utils.SphereClientUtils.CTP_TARGET_CLIENT) ResourceIdentifier(io.sphere.sdk.models.ResourceIdentifier) TaxCategory(io.sphere.sdk.taxcategories.TaxCategory) AssertionsForStatistics.assertThat(com.commercetools.sync.commons.asserts.statistics.AssertionsForStatistics.assertThat) ProductITUtils.deleteAllProducts(com.commercetools.sync.integration.commons.utils.ProductITUtils.deleteAllProducts) Mockito.spy(org.mockito.Mockito.spy) DuplicateFieldError(io.sphere.sdk.models.errors.DuplicateFieldError) ArrayList(java.util.ArrayList) PriceDraftBuilder(io.sphere.sdk.products.PriceDraftBuilder) CategoryITUtils.replaceCategoryOrderHintCategoryIdsWithKeys(com.commercetools.sync.integration.commons.utils.CategoryITUtils.replaceCategoryOrderHintCategoryIdsWithKeys) ProductSync(com.commercetools.sync.products.ProductSync) ProductDraftBuilder(io.sphere.sdk.products.ProductDraftBuilder) ChannelByIdGet(io.sphere.sdk.channels.queries.ChannelByIdGet) PRODUCT_KEY_1_CHANGED_RESOURCE_PATH(com.commercetools.sync.products.ProductSyncMockUtils.PRODUCT_KEY_1_CHANGED_RESOURCE_PATH) CategoryITUtils.geResourceIdentifiersWithKeys(com.commercetools.sync.integration.commons.utils.CategoryITUtils.geResourceIdentifiersWithKeys) FAILED_TO_BUILD_ATTRIBUTE_UPDATE_ACTION(com.commercetools.sync.products.utils.ProductVariantUpdateActionUtils.FAILED_TO_BUILD_ATTRIBUTE_UPDATE_ACTION) PagedQueryResult(io.sphere.sdk.queries.PagedQueryResult) ConcurrentModificationException(io.sphere.sdk.client.ConcurrentModificationException) RemoveFromCategory(io.sphere.sdk.products.commands.updateactions.RemoveFromCategory) ProductVariantDraftBuilder(io.sphere.sdk.products.ProductVariantDraftBuilder) PRODUCT_KEY_2_RESOURCE_PATH(com.commercetools.sync.products.ProductSyncMockUtils.PRODUCT_KEY_2_RESOURCE_PATH) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ProductSyncMockUtils.createProductDraftBuilder(com.commercetools.sync.products.ProductSyncMockUtils.createProductDraftBuilder) UpdateAction(io.sphere.sdk.commands.UpdateAction) ProductITUtils.deleteProductSyncTestData(com.commercetools.sync.integration.commons.utils.ProductITUtils.deleteProductSyncTestData) SetTaxCategory(io.sphere.sdk.products.commands.updateactions.SetTaxCategory) Locale(java.util.Locale) ProductDraft(io.sphere.sdk.products.ProductDraft) OLD_CATEGORY_CUSTOM_TYPE_KEY(com.commercetools.sync.integration.commons.utils.CategoryITUtils.OLD_CATEGORY_CUSTOM_TYPE_KEY) CompletionStageUtil.executeBlocking(com.commercetools.tests.utils.CompletionStageUtil.executeBlocking) Collections.emptyList(java.util.Collections.emptyList) Category(io.sphere.sdk.categories.Category) Product(io.sphere.sdk.products.Product) CategoryITUtils.getReferencesWithIds(com.commercetools.sync.integration.commons.utils.CategoryITUtils.getReferencesWithIds) State(io.sphere.sdk.states.State) String.format(java.lang.String.format) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) LocalizedString(io.sphere.sdk.models.LocalizedString) List(java.util.List) Publish(io.sphere.sdk.products.commands.updateactions.Publish) ProductSyncMockUtils.createProductDraft(com.commercetools.sync.products.ProductSyncMockUtils.createProductDraft) Optional(java.util.Optional) ProductVariantDraftDsl(io.sphere.sdk.products.ProductVariantDraftDsl) ProductCreateCommand(io.sphere.sdk.products.commands.ProductCreateCommand) ProductSyncOptions(com.commercetools.sync.products.ProductSyncOptions) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) CategoryITUtils.createCategories(com.commercetools.sync.integration.commons.utils.CategoryITUtils.createCategories) ProductByKeyGet(io.sphere.sdk.products.queries.ProductByKeyGet) CategoryOrderHints(io.sphere.sdk.products.CategoryOrderHints) ProductType(io.sphere.sdk.producttypes.ProductType) ProductQuery(io.sphere.sdk.products.queries.ProductQuery) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) CompletableFutureUtils(io.sphere.sdk.utils.CompletableFutureUtils) CategoryDraft(io.sphere.sdk.categories.CategoryDraft) SetAttribute(io.sphere.sdk.products.commands.updateactions.SetAttribute) Nonnull(javax.annotation.Nonnull) ChannelRole(io.sphere.sdk.channels.ChannelRole) PriceDraftDsl(io.sphere.sdk.products.PriceDraftDsl) QueryPredicate(io.sphere.sdk.queries.QueryPredicate) ATTRIBUTE_NOT_IN_ATTRIBUTE_METADATA(com.commercetools.sync.products.utils.ProductVariantAttributeUpdateActionUtils.ATTRIBUTE_NOT_IN_ATTRIBUTE_METADATA) CategoryITUtils.createCategoriesCustomType(com.commercetools.sync.integration.commons.utils.CategoryITUtils.createCategoriesCustomType) Mockito.when(org.mockito.Mockito.when) Collectors.toList(java.util.stream.Collectors.toList) AttributeDraft(io.sphere.sdk.products.attributes.AttributeDraft) ErrorResponseException(io.sphere.sdk.client.ErrorResponseException) ProductSyncMockUtils.createRandomCategoryOrderHints(com.commercetools.sync.products.ProductSyncMockUtils.createRandomCategoryOrderHints) Collections(java.util.Collections) RemoveFromCategory(io.sphere.sdk.products.commands.updateactions.RemoveFromCategory) Optional(java.util.Optional) UpdateAction(io.sphere.sdk.commands.UpdateAction) AttributeDraft(io.sphere.sdk.products.attributes.AttributeDraft) ArrayList(java.util.ArrayList) ProductVariantDraft(io.sphere.sdk.products.ProductVariantDraft) ProductSync(com.commercetools.sync.products.ProductSync) SyncException(com.commercetools.sync.commons.exceptions.SyncException) LocalizedString(io.sphere.sdk.models.LocalizedString) SetTaxCategory(io.sphere.sdk.products.commands.updateactions.SetTaxCategory) ProductSyncStatistics(com.commercetools.sync.products.helpers.ProductSyncStatistics) ProductDraft(io.sphere.sdk.products.ProductDraft) ProductSyncMockUtils.createProductDraft(com.commercetools.sync.products.ProductSyncMockUtils.createProductDraft) ProductSyncOptions(com.commercetools.sync.products.ProductSyncOptions) Test(org.junit.jupiter.api.Test)

Example 57 with SyncException

use of com.commercetools.sync.commons.exceptions.SyncException in project commercetools-sync-java by commercetools.

the class CategoryUpdateActionUtilsTest method buildChangeParentUpdateAction_WithNullValues_ShouldNotBuildUpdateActionAndCallCallback.

@Test
void buildChangeParentUpdateAction_WithNullValues_ShouldNotBuildUpdateActionAndCallCallback() {
    when(MOCK_OLD_CATEGORY.getId()).thenReturn("oldCatId");
    final CategoryDraft newCategory = mock(CategoryDraft.class);
    when(newCategory.getParent()).thenReturn(null);
    final ArrayList<Object> callBackResponse = new ArrayList<>();
    final TriConsumer<SyncException, Optional<CategoryDraft>, Optional<Category>> updateActionWarningCallBack = (exception, newResource, oldResource) -> callBackResponse.add(exception.getMessage());
    final CategorySyncOptions categorySyncOptions = CategorySyncOptionsBuilder.of(CTP_CLIENT).warningCallback(updateActionWarningCallBack).build();
    final Optional<UpdateAction<Category>> changeParentUpdateAction = buildChangeParentUpdateAction(MOCK_OLD_CATEGORY, newCategory, categorySyncOptions);
    assertThat(changeParentUpdateAction).isNotNull();
    assertThat(changeParentUpdateAction).isNotPresent();
    assertThat(callBackResponse).hasSize(1);
    assertThat(callBackResponse.get(0)).isEqualTo("Cannot unset 'parent' field of category with id 'oldCatId'.");
}
Also used : CategoryUpdateActionUtils.buildSetMetaDescriptionUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildSetMetaDescriptionUpdateAction) CategoryUpdateActionUtils.buildSetMetaTitleUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildSetMetaTitleUpdateAction) SphereJsonUtils.readObjectFromResource(io.sphere.sdk.json.SphereJsonUtils.readObjectFromResource) SetExternalId(io.sphere.sdk.categories.commands.updateactions.SetExternalId) CategoryUpdateActionUtils.buildSetMetaKeywordsUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildSetMetaKeywordsUpdateAction) SyncException(com.commercetools.sync.commons.exceptions.SyncException) CategoryUpdateActionUtils.buildChangeNameUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildChangeNameUpdateAction) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SetDescription(io.sphere.sdk.categories.commands.updateactions.SetDescription) UpdateAction(io.sphere.sdk.commands.UpdateAction) CategorySyncMockUtils.getMockCategory(com.commercetools.sync.categories.CategorySyncMockUtils.getMockCategory) CategoryUpdateActionUtils.buildChangeParentUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildChangeParentUpdateAction) CategoryDraft(io.sphere.sdk.categories.CategoryDraft) ChangeName(io.sphere.sdk.categories.commands.updateactions.ChangeName) SetMetaDescription(io.sphere.sdk.categories.commands.updateactions.SetMetaDescription) SetMetaKeywords(io.sphere.sdk.categories.commands.updateactions.SetMetaKeywords) ArrayList(java.util.ArrayList) SetMetaTitle(io.sphere.sdk.categories.commands.updateactions.SetMetaTitle) Locale(java.util.Locale) SphereClient(io.sphere.sdk.client.SphereClient) CategoryUpdateActionUtils.buildChangeOrderHintUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildChangeOrderHintUpdateAction) TriConsumer(com.commercetools.sync.commons.utils.TriConsumer) CategoryUpdateActionUtils.buildSetExternalIdUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildSetExternalIdUpdateAction) Category(io.sphere.sdk.categories.Category) ChangeOrderHint(io.sphere.sdk.categories.commands.updateactions.ChangeOrderHint) Mockito.when(org.mockito.Mockito.when) CategorySyncOptionsBuilder(com.commercetools.sync.categories.CategorySyncOptionsBuilder) ChangeSlug(io.sphere.sdk.categories.commands.updateactions.ChangeSlug) CategorySyncOptions(com.commercetools.sync.categories.CategorySyncOptions) Test(org.junit.jupiter.api.Test) LocalizedString(io.sphere.sdk.models.LocalizedString) CategoryUpdateActionUtils.buildSetDescriptionUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildSetDescriptionUpdateAction) CATEGORY_KEY_1_RESOURCE_PATH(com.commercetools.sync.products.ProductSyncMockUtils.CATEGORY_KEY_1_RESOURCE_PATH) Optional(java.util.Optional) ChangeParent(io.sphere.sdk.categories.commands.updateactions.ChangeParent) CategoryUpdateActionUtils.buildChangeSlugUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildChangeSlugUpdateAction) Mockito.mock(org.mockito.Mockito.mock) ResourceIdentifier(io.sphere.sdk.models.ResourceIdentifier) Optional(java.util.Optional) CategoryUpdateActionUtils.buildSetMetaDescriptionUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildSetMetaDescriptionUpdateAction) CategoryUpdateActionUtils.buildSetMetaTitleUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildSetMetaTitleUpdateAction) CategoryUpdateActionUtils.buildSetMetaKeywordsUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildSetMetaKeywordsUpdateAction) CategoryUpdateActionUtils.buildChangeNameUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildChangeNameUpdateAction) UpdateAction(io.sphere.sdk.commands.UpdateAction) CategoryUpdateActionUtils.buildChangeParentUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildChangeParentUpdateAction) CategoryUpdateActionUtils.buildChangeOrderHintUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildChangeOrderHintUpdateAction) CategoryUpdateActionUtils.buildSetExternalIdUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildSetExternalIdUpdateAction) CategoryUpdateActionUtils.buildSetDescriptionUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildSetDescriptionUpdateAction) CategoryUpdateActionUtils.buildChangeSlugUpdateAction(com.commercetools.sync.categories.utils.CategoryUpdateActionUtils.buildChangeSlugUpdateAction) CategoryDraft(io.sphere.sdk.categories.CategoryDraft) ArrayList(java.util.ArrayList) CategorySyncOptions(com.commercetools.sync.categories.CategorySyncOptions) SyncException(com.commercetools.sync.commons.exceptions.SyncException) Test(org.junit.jupiter.api.Test)

Example 58 with SyncException

use of com.commercetools.sync.commons.exceptions.SyncException in project commercetools-sync-java by commercetools.

the class ProductVariantPriceUpdateActionUtils method buildChangePriceUpdateAction.

/**
 * Builds a {@link ChangePrice} action based on the comparison of the following fields of the
 * supplied {@link Price} and {@link PriceDraft}:
 *
 * <ul>
 *   <li>{@link Price#getValue()} and {@link PriceDraft#getValue()}
 *   <li>{@link Price#getTiers()} and {@link PriceDraft#getTiers()}
 * </ul>
 *
 * <p>If any of the aforementioned fields are different a {@link ChangePrice} update action will
 * be returned in an {@link Optional}, otherwise if both are identical in the {@link Price} and
 * the {@link PriceDraft}, then no update action is needed and hence an empty {@link Optional} is
 * returned.
 *
 * @param oldPrice the price which should be updated.
 * @param newPrice the price draft where we get the new name.
 * @param syncOptions responsible for supplying the sync options to the sync utility method. It is
 *     used for triggering the error callback within the utility, in case of errors.
 * @return A filled optional with the update action or an empty optional if the names are
 *     identical.
 */
@Nonnull
public static Optional<ChangePrice> buildChangePriceUpdateAction(@Nonnull final Price oldPrice, @Nonnull final PriceDraft newPrice, @Nonnull final ProductSyncOptions syncOptions) {
    final MonetaryAmount oldPriceValue = oldPrice.getValue();
    final MonetaryAmount newPriceValue = newPrice.getValue();
    if (newPriceValue == null) {
        syncOptions.applyWarningCallback(new SyncException(format(VARIANT_CHANGE_PRICE_EMPTY_VALUE, oldPrice.getId())), null, null);
        return Optional.empty();
    }
    final Optional<ChangePrice> actionAfterValuesDiff = buildUpdateAction(oldPriceValue, newPriceValue, () -> ChangePrice.of(oldPrice, newPrice, true));
    return actionAfterValuesDiff.map(Optional::of).orElseGet(() -> buildUpdateAction(oldPrice.getTiers(), newPrice.getTiers(), () -> ChangePrice.of(oldPrice, newPrice, true)));
}
Also used : ChangePrice(io.sphere.sdk.products.commands.updateactions.ChangePrice) MonetaryAmount(javax.money.MonetaryAmount) SyncException(com.commercetools.sync.commons.exceptions.SyncException) Nonnull(javax.annotation.Nonnull)

Example 59 with SyncException

use of com.commercetools.sync.commons.exceptions.SyncException in project commercetools-sync-java by commercetools.

the class ProductTypeSync method syncBatch.

/**
 * Given a set of product type drafts, attempts to sync the drafts with the existing products
 * types in the target CTP project. The product type and the draft are considered to match if they
 * have the same key.
 *
 * <p>Note: In order to support syncing product types with nested references in any order, this
 * method will remove any attribute which contains a nested reference on the drafts and keep track
 * of it to be resolved as soon as the referenced product type becomes available.
 *
 * @param oldProductTypes old product types.
 * @param newProductTypes drafts that need to be synced.
 * @return a {@link CompletionStage} which contains an empty result after execution of the update
 */
@Nonnull
private CompletionStage<Void> syncBatch(@Nonnull final Set<ProductType> oldProductTypes, @Nonnull final Set<ProductTypeDraft> newProductTypes, @Nonnull final Map<String, String> keyToIdCache) {
    final Map<String, ProductType> oldProductTypeMap = oldProductTypes.stream().collect(toMap(ProductType::getKey, identity()));
    return CompletableFuture.allOf(newProductTypes.stream().map(newProductType -> removeAndKeepTrackOfMissingNestedAttributes(newProductType, keyToIdCache)).map(draftWithoutMissingRefAttrs -> referenceResolver.resolveReferences(draftWithoutMissingRefAttrs).thenCompose(resolvedDraft -> syncDraft(oldProductTypeMap, resolvedDraft)).exceptionally(completionException -> {
        final String errorMessage = format(FAILED_TO_PROCESS, draftWithoutMissingRefAttrs.getKey(), completionException.getMessage());
        handleError(new SyncException(errorMessage, completionException), 1);
        return null;
    })).map(CompletionStage::toCompletableFuture).toArray(CompletableFuture[]::new));
}
Also used : SyncException(com.commercetools.sync.commons.exceptions.SyncException) BaseSync(com.commercetools.sync.commons.BaseSync) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) ProductTypeReferenceResolver(com.commercetools.sync.producttypes.helpers.ProductTypeReferenceResolver) ProductType(io.sphere.sdk.producttypes.ProductType) UpdateAction(io.sphere.sdk.commands.UpdateAction) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AddAttributeDefinition(io.sphere.sdk.producttypes.commands.updateactions.AddAttributeDefinition) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Collectors.toMap(java.util.stream.Collectors.toMap) ProductTypeBatchValidator.getProductTypeKey(com.commercetools.sync.producttypes.helpers.ProductTypeBatchValidator.getProductTypeKey) ProductTypeService(com.commercetools.sync.services.ProductTypeService) Map(java.util.Map) SyncUtils.batchElements(com.commercetools.sync.commons.utils.SyncUtils.batchElements) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) ProductTypeDraftBuilder(io.sphere.sdk.producttypes.ProductTypeDraftBuilder) Optional.ofNullable(java.util.Optional.ofNullable) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) ProductTypeDraft(io.sphere.sdk.producttypes.ProductTypeDraft) InvalidReferenceException(com.commercetools.sync.commons.exceptions.InvalidReferenceException) ProductTypeBatchValidator(com.commercetools.sync.producttypes.helpers.ProductTypeBatchValidator) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) List(java.util.List) ProductTypeSyncUtils.buildActions(com.commercetools.sync.producttypes.utils.ProductTypeSyncUtils.buildActions) CompletionStage(java.util.concurrent.CompletionStage) ProductTypeServiceImpl(com.commercetools.sync.services.impl.ProductTypeServiceImpl) AttributeType(io.sphere.sdk.products.attributes.AttributeType) AttributeDefinitionReferenceResolver(com.commercetools.sync.producttypes.helpers.AttributeDefinitionReferenceResolver) Function.identity(java.util.function.Function.identity) Optional(java.util.Optional) AttributeDefinitionDraft(io.sphere.sdk.products.attributes.AttributeDefinitionDraft) ProductTypeSyncStatistics(com.commercetools.sync.producttypes.helpers.ProductTypeSyncStatistics) CompletableFuture(java.util.concurrent.CompletableFuture) ProductType(io.sphere.sdk.producttypes.ProductType) SyncException(com.commercetools.sync.commons.exceptions.SyncException) CompletionStage(java.util.concurrent.CompletionStage) Nonnull(javax.annotation.Nonnull)

Example 60 with SyncException

use of com.commercetools.sync.commons.exceptions.SyncException in project commercetools-sync-java by commercetools.

the class ProductTypeSync method removeAndKeepTrackOfMissingNestedAttribute.

/**
 * Attempts to find a nested product type in the attribute type of {@code
 * attributeDefinitionDraft}, if it has a nested type. It checks if the key, of the productType
 * reference, is cached in {@code keyToIdCache}. If it is, then it means the referenced product
 * type exists in the target project, so there is no need to remove or keep track of it. However,
 * if it is not, it means it doesn't exist yet, which means we need to keep track of it as a
 * missing reference and also remove this attribute definition from the supplied {@code draftCopy}
 * to be able to create product type without this attribute containing the missing reference.
 *
 * <p>Note: This method mutates in the supplied {@code productTypeDraft} attribute definition list
 * by removing the attribute containing a missing reference.
 *
 * @param attributeDefinitionDraft the attribute definition being checked for any product
 *     references.
 * @param productTypeDraft the productTypeDraft containing the attribute which should be updated
 *     by removing the attribute which contains the missing reference.
 * @param keyToIdCache a map of productType key to id. It represents a cache of the existing
 *     productTypes in the target project.
 */
@SuppressWarnings(// since the batch is validate before, key is assured to be non-blank
"ConstantConditions")
private // here.
void removeAndKeepTrackOfMissingNestedAttribute(@Nonnull final AttributeDefinitionDraft attributeDefinitionDraft, @Nonnull final ProductTypeDraft productTypeDraft, @Nonnull final Map<String, String> keyToIdCache) {
    final AttributeType attributeType = attributeDefinitionDraft.getAttributeType();
    try {
        getProductTypeKey(attributeType).ifPresent(key -> {
            if (!keyToIdCache.keySet().contains(key)) {
                productTypeDraft.getAttributes().remove(attributeDefinitionDraft);
                statistics.putMissingNestedProductType(key, productTypeDraft.getKey(), attributeDefinitionDraft);
            }
        });
    } catch (InvalidReferenceException invalidReferenceException) {
        handleError(new SyncException("This exception is unexpectedly thrown since the draft batch has been" + "already validated for blank keys at an earlier stage, which means this draft should" + " have a valid reference. Please communicate this error with the maintainer of the library.", invalidReferenceException), 1);
    }
}
Also used : AttributeType(io.sphere.sdk.products.attributes.AttributeType) SyncException(com.commercetools.sync.commons.exceptions.SyncException) InvalidReferenceException(com.commercetools.sync.commons.exceptions.InvalidReferenceException)

Aggregations

SyncException (com.commercetools.sync.commons.exceptions.SyncException)74 Nonnull (javax.annotation.Nonnull)47 UpdateAction (io.sphere.sdk.commands.UpdateAction)45 Optional (java.util.Optional)39 List (java.util.List)37 CompletionStage (java.util.concurrent.CompletionStage)25 SphereClient (io.sphere.sdk.client.SphereClient)24 String.format (java.lang.String.format)23 ArrayList (java.util.ArrayList)21 Map (java.util.Map)20 Test (org.junit.jupiter.api.Test)20 TriConsumer (com.commercetools.sync.commons.utils.TriConsumer)18 Set (java.util.Set)17 CompletableFuture (java.util.concurrent.CompletableFuture)17 Nullable (javax.annotation.Nullable)16 ImmutablePair (org.apache.commons.lang3.tuple.ImmutablePair)14 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)14 Category (io.sphere.sdk.categories.Category)13 BaseSync (com.commercetools.sync.commons.BaseSync)12 QuadConsumer (com.commercetools.sync.commons.utils.QuadConsumer)12