Search in sources :

Example 66 with SyncException

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

the class ShoppingListSync method updateShoppinglist.

@Nonnull
private CompletionStage<Void> updateShoppinglist(@Nonnull final ShoppingList oldShoppingList, @Nonnull final ShoppingListDraft newShoppingListDraft, @Nonnull final List<UpdateAction<ShoppingList>> updateActionsAfterCallback) {
    return shoppingListService.updateShoppingList(oldShoppingList, updateActionsAfterCallback).handle(ImmutablePair::of).thenCompose(updateResponse -> {
        final Throwable exception = updateResponse.getValue();
        if (exception != null) {
            return executeSupplierIfConcurrentModificationException(exception, () -> fetchAndUpdate(oldShoppingList, newShoppingListDraft), () -> {
                final String errorMessage = format(CTP_SHOPPING_LIST_UPDATE_FAILED, newShoppingListDraft.getKey(), exception.getMessage());
                handleError(new SyncException(errorMessage, exception), 1);
                return CompletableFuture.completedFuture(null);
            });
        } else {
            statistics.incrementUpdated();
            return CompletableFuture.completedFuture(null);
        }
    });
}
Also used : SyncException(com.commercetools.sync.commons.exceptions.SyncException) Nonnull(javax.annotation.Nonnull)

Example 67 with SyncException

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

the class ShoppingListSync method syncBatch.

@Nonnull
private CompletionStage<Void> syncBatch(@Nonnull final Set<ShoppingList> oldShoppingLists, @Nonnull final Set<ShoppingListDraft> newShoppingListDrafts) {
    Map<String, ShoppingList> keyShoppingListsMap = oldShoppingLists.stream().collect(toMap(ShoppingList::getKey, identity()));
    return CompletableFuture.allOf(newShoppingListDrafts.stream().map(shoppingListDraft -> shoppingListReferenceResolver.resolveReferences(shoppingListDraft).thenCompose(resolvedShoppingListDraft -> syncDraft(keyShoppingListsMap, resolvedShoppingListDraft)).exceptionally(completionException -> {
        final String errorMessage = format(FAILED_TO_PROCESS, shoppingListDraft.getKey(), completionException.getMessage());
        handleError(new SyncException(errorMessage, completionException), 1);
        return null;
    })).map(CompletionStage::toCompletableFuture).toArray(CompletableFuture[]::new));
}
Also used : CustomerServiceImpl(com.commercetools.sync.services.impl.CustomerServiceImpl) SyncException(com.commercetools.sync.commons.exceptions.SyncException) BaseSync(com.commercetools.sync.commons.BaseSync) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) UpdateAction(io.sphere.sdk.commands.UpdateAction) CompletableFuture(java.util.concurrent.CompletableFuture) ShoppingList(io.sphere.sdk.shoppinglists.ShoppingList) Collectors.toMap(java.util.stream.Collectors.toMap) TypeService(com.commercetools.sync.services.TypeService) Map(java.util.Map) SyncUtils.batchElements(com.commercetools.sync.commons.utils.SyncUtils.batchElements) ShoppingListBatchValidator(com.commercetools.sync.shoppinglists.helpers.ShoppingListBatchValidator) Nonnull(javax.annotation.Nonnull) Collectors.toSet(java.util.stream.Collectors.toSet) CustomerService(com.commercetools.sync.services.CustomerService) ShoppingListReferenceResolver(com.commercetools.sync.shoppinglists.helpers.ShoppingListReferenceResolver) ShoppingListSyncStatistics(com.commercetools.sync.shoppinglists.helpers.ShoppingListSyncStatistics) Set(java.util.Set) ShoppingListService(com.commercetools.sync.services.ShoppingListService) ShoppingListServiceImpl(com.commercetools.sync.services.impl.ShoppingListServiceImpl) TypeServiceImpl(com.commercetools.sync.services.impl.TypeServiceImpl) String.format(java.lang.String.format) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) CustomerSyncOptionsBuilder(com.commercetools.sync.customers.CustomerSyncOptionsBuilder) ShoppingListDraft(io.sphere.sdk.shoppinglists.ShoppingListDraft) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) ShoppingListSyncUtils.buildActions(com.commercetools.sync.shoppinglists.utils.ShoppingListSyncUtils.buildActions) Function.identity(java.util.function.Function.identity) Optional(java.util.Optional) CompletableFuture(java.util.concurrent.CompletableFuture) ShoppingList(io.sphere.sdk.shoppinglists.ShoppingList) SyncException(com.commercetools.sync.commons.exceptions.SyncException) CompletionStage(java.util.concurrent.CompletionStage) Nonnull(javax.annotation.Nonnull)

Example 68 with SyncException

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

the class ShoppingListSync method fetchAndUpdate.

@Nonnull
private CompletionStage<Void> fetchAndUpdate(@Nonnull final ShoppingList oldShoppingList, @Nonnull final ShoppingListDraft newShoppingListDraft) {
    final String shoppingListKey = oldShoppingList.getKey();
    return shoppingListService.fetchShoppingList(shoppingListKey).handle(ImmutablePair::of).thenCompose(fetchResponse -> {
        final Optional<ShoppingList> fetchedShoppingListOptional = fetchResponse.getKey();
        final Throwable exception = fetchResponse.getValue();
        if (exception != null) {
            final String errorMessage = format(CTP_SHOPPING_LIST_UPDATE_FAILED, shoppingListKey, "Failed to fetch from CTP while retrying after concurrency modification.");
            handleError(new SyncException(errorMessage, exception), 1);
            return CompletableFuture.completedFuture(null);
        }
        return fetchedShoppingListOptional.map(fetchedShoppingList -> buildActionsAndUpdate(fetchedShoppingList, newShoppingListDraft)).orElseGet(() -> {
            final String errorMessage = format(CTP_SHOPPING_LIST_UPDATE_FAILED, shoppingListKey, "Not found when attempting to fetch while retrying after concurrency modification.");
            handleError(new SyncException(errorMessage, null), 1);
            return CompletableFuture.completedFuture(null);
        });
    });
}
Also used : CustomerServiceImpl(com.commercetools.sync.services.impl.CustomerServiceImpl) SyncException(com.commercetools.sync.commons.exceptions.SyncException) BaseSync(com.commercetools.sync.commons.BaseSync) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) UpdateAction(io.sphere.sdk.commands.UpdateAction) CompletableFuture(java.util.concurrent.CompletableFuture) ShoppingList(io.sphere.sdk.shoppinglists.ShoppingList) Collectors.toMap(java.util.stream.Collectors.toMap) TypeService(com.commercetools.sync.services.TypeService) Map(java.util.Map) SyncUtils.batchElements(com.commercetools.sync.commons.utils.SyncUtils.batchElements) ShoppingListBatchValidator(com.commercetools.sync.shoppinglists.helpers.ShoppingListBatchValidator) Nonnull(javax.annotation.Nonnull) Collectors.toSet(java.util.stream.Collectors.toSet) CustomerService(com.commercetools.sync.services.CustomerService) ShoppingListReferenceResolver(com.commercetools.sync.shoppinglists.helpers.ShoppingListReferenceResolver) ShoppingListSyncStatistics(com.commercetools.sync.shoppinglists.helpers.ShoppingListSyncStatistics) Set(java.util.Set) ShoppingListService(com.commercetools.sync.services.ShoppingListService) ShoppingListServiceImpl(com.commercetools.sync.services.impl.ShoppingListServiceImpl) TypeServiceImpl(com.commercetools.sync.services.impl.TypeServiceImpl) String.format(java.lang.String.format) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) CustomerSyncOptionsBuilder(com.commercetools.sync.customers.CustomerSyncOptionsBuilder) ShoppingListDraft(io.sphere.sdk.shoppinglists.ShoppingListDraft) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) ShoppingListSyncUtils.buildActions(com.commercetools.sync.shoppinglists.utils.ShoppingListSyncUtils.buildActions) Function.identity(java.util.function.Function.identity) Optional(java.util.Optional) ShoppingList(io.sphere.sdk.shoppinglists.ShoppingList) SyncException(com.commercetools.sync.commons.exceptions.SyncException) Nonnull(javax.annotation.Nonnull)

Example 69 with SyncException

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

the class LineItemUpdateActionUtils method buildUpdateActions.

/**
 * The decisions in the calculating update actions are documented on the
 * `docs/adr/0002-shopping-lists-lineitem-and-textlineitem-update-actions.md`
 */
@Nonnull
private static List<UpdateAction<ShoppingList>> buildUpdateActions(@Nonnull final ShoppingList oldShoppingList, @Nonnull final ShoppingListDraft newShoppingList, @Nonnull final List<LineItem> oldLineItems, @Nonnull final List<LineItemDraft> newlineItems, @Nonnull final ShoppingListSyncOptions syncOptions) {
    final List<UpdateAction<ShoppingList>> updateActions = new ArrayList<>();
    final int minSize = Math.min(oldLineItems.size(), newlineItems.size());
    int indexOfFirstDifference = minSize;
    for (int i = 0; i < minSize; i++) {
        final LineItem oldLineItem = oldLineItems.get(i);
        final LineItemDraft newLineItem = newlineItems.get(i);
        if (oldLineItem.getVariant() == null || StringUtils.isBlank(oldLineItem.getVariant().getSku())) {
            syncOptions.applyErrorCallback(new SyncException(format("LineItem at position '%d' of the ShoppingList with key '%s' has no SKU set. " + "Please make sure all line items have SKUs.", i, oldShoppingList.getKey())), oldShoppingList, newShoppingList, updateActions);
            return emptyList();
        } else if (StringUtils.isBlank(newLineItem.getSku())) {
            syncOptions.applyErrorCallback(new SyncException(format("LineItemDraft at position '%d' of the ShoppingListDraft with key '%s' has no SKU set. " + "Please make sure all line item drafts have SKUs.", i, newShoppingList.getKey())), oldShoppingList, newShoppingList, updateActions);
            return emptyList();
        }
        if (oldLineItem.getVariant().getSku().equals(newLineItem.getSku())) {
            updateActions.addAll(buildLineItemUpdateActions(oldShoppingList, newShoppingList, oldLineItem, newLineItem, syncOptions));
        } else {
            // different sku means the order is different.
            // To be able to ensure the order, we need to remove and add this line item back
            // with the up to date values.
            indexOfFirstDifference = i;
            break;
        }
    }
    // expected: remove from old li-2, add from draft li-3, li-2 starting from the index.
    for (int i = indexOfFirstDifference; i < oldLineItems.size(); i++) {
        updateActions.add(RemoveLineItem.of(oldLineItems.get(i).getId()));
    }
    for (int i = indexOfFirstDifference; i < newlineItems.size(); i++) {
        if (hasQuantity(newlineItems.get(i))) {
            updateActions.add(AddLineItem.of(newlineItems.get(i)));
        }
    }
    return updateActions;
}
Also used : UpdateAction(io.sphere.sdk.commands.UpdateAction) CommonTypeUpdateActionUtils.buildUpdateAction(com.commercetools.sync.commons.utils.CommonTypeUpdateActionUtils.buildUpdateAction) ArrayList(java.util.ArrayList) LineItem(io.sphere.sdk.shoppinglists.LineItem) AddLineItem(io.sphere.sdk.shoppinglists.commands.updateactions.AddLineItem) RemoveLineItem(io.sphere.sdk.shoppinglists.commands.updateactions.RemoveLineItem) SyncException(com.commercetools.sync.commons.exceptions.SyncException) LineItemDraft(io.sphere.sdk.shoppinglists.LineItemDraft) Nonnull(javax.annotation.Nonnull)

Example 70 with SyncException

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

the class CustomUpdateActionUtilsTest method buildCustomUpdateActions_WithNullIds_ShouldCallSyncOptionsCallBack.

@Test
void buildCustomUpdateActions_WithNullIds_ShouldCallSyncOptionsCallBack() {
    final Reference<Type> assetCustomTypeReference = Type.referenceOfId(null);
    // Mock old CustomFields
    final CustomFields oldCustomFieldsMock = mock(CustomFields.class);
    when(oldCustomFieldsMock.getType()).thenReturn(assetCustomTypeReference);
    // Mock new CustomFieldsDraft
    final CustomFieldsDraft newCustomFieldsMock = mock(CustomFieldsDraft.class);
    when(newCustomFieldsMock.getType()).thenReturn(assetCustomTypeReference);
    // Mock old Asset
    final Asset oldAsset = mock(Asset.class);
    final String oldAssetId = "oldAssetId";
    when(oldAsset.getId()).thenReturn(oldAssetId);
    when(oldAsset.getCustom()).thenReturn(oldCustomFieldsMock);
    final AssetDraft newAssetDraft = AssetDraftBuilder.of(emptyList(), ofEnglish("assetName")).custom(newCustomFieldsMock).build();
    // Mock custom options error callback
    final ArrayList<Object> callBackResponses = new ArrayList<>();
    final QuadConsumer<SyncException, Optional<ProductDraft>, Optional<ProductProjection>, List<UpdateAction<Product>>> errorCallback = (exception, newResource, oldResource, updateActions) -> {
        callBackResponses.add(exception.getMessage());
        callBackResponses.add(exception.getCause());
    };
    // Mock sync options
    final ProductSyncOptions productSyncOptions = ProductSyncOptionsBuilder.of(CTP_CLIENT).errorCallback(errorCallback).build();
    final List<UpdateAction<Product>> updateActions = buildCustomUpdateActions(maiNewResource, oldAsset, newAssetDraft, new AssetCustomActionBuilder(), 10, Asset::getId, asset -> Asset.resourceTypeId(), Asset::getKey, productSyncOptions);
    assertThat(callBackResponses).hasSize(2);
    assertThat(callBackResponses.get(0)).isEqualTo("Failed to build custom fields update actions on the asset" + " with id 'oldAssetId'. Reason: Custom type ids are not set for both the old and new asset.");
    assertThat((Exception) callBackResponses.get(1)).isInstanceOf(BuildUpdateActionException.class);
    assertThat(updateActions).isEmpty();
}
Also used : CustomUpdateActionUtils.buildCustomUpdateActions(com.commercetools.sync.commons.utils.CustomUpdateActionUtils.buildCustomUpdateActions) SetProductPriceCustomType(io.sphere.sdk.products.commands.updateactions.SetProductPriceCustomType) AssetCustomActionBuilder(com.commercetools.sync.products.helpers.AssetCustomActionBuilder) Reference(io.sphere.sdk.models.Reference) SyncException(com.commercetools.sync.commons.exceptions.SyncException) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) UpdateAction(io.sphere.sdk.commands.UpdateAction) Map(java.util.Map) CategoryCustomActionBuilder(com.commercetools.sync.categories.helpers.CategoryCustomActionBuilder) SphereClient(io.sphere.sdk.client.SphereClient) JsonNode(com.fasterxml.jackson.databind.JsonNode) ProductDraft(io.sphere.sdk.products.ProductDraft) ProductProjection(io.sphere.sdk.products.ProductProjection) AssetDraft(io.sphere.sdk.models.AssetDraft) AssetDraftBuilder(io.sphere.sdk.models.AssetDraftBuilder) Collections.emptyList(java.util.Collections.emptyList) Category(io.sphere.sdk.categories.Category) Price(io.sphere.sdk.products.Price) CustomFieldsDraft.ofTypeKeyAndJson(io.sphere.sdk.types.CustomFieldsDraft.ofTypeKeyAndJson) Product(io.sphere.sdk.products.Product) UUID(java.util.UUID) String.format(java.lang.String.format) Test(org.junit.jupiter.api.Test) List(java.util.List) LocalizedString.ofEnglish(io.sphere.sdk.models.LocalizedString.ofEnglish) ProductSyncOptionsBuilder(com.commercetools.sync.products.ProductSyncOptionsBuilder) JsonNodeFactory(com.fasterxml.jackson.databind.node.JsonNodeFactory) Optional(java.util.Optional) BuildUpdateActionException(com.commercetools.sync.commons.exceptions.BuildUpdateActionException) ProductSyncOptions(com.commercetools.sync.products.ProductSyncOptions) Mockito.mock(org.mockito.Mockito.mock) ResourceIdentifier(io.sphere.sdk.models.ResourceIdentifier) CustomFields(io.sphere.sdk.types.CustomFields) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CustomUpdateActionUtils.buildNonNullCustomFieldsUpdateActions(com.commercetools.sync.commons.utils.CustomUpdateActionUtils.buildNonNullCustomFieldsUpdateActions) SetAssetCustomField(io.sphere.sdk.products.commands.updateactions.SetAssetCustomField) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) SetAssetCustomType(io.sphere.sdk.products.commands.updateactions.SetAssetCustomType) CustomUpdateActionUtils.buildSetCustomFieldsUpdateActions(com.commercetools.sync.commons.utils.CustomUpdateActionUtils.buildSetCustomFieldsUpdateActions) Mockito.when(org.mockito.Mockito.when) CategorySyncOptionsBuilder(com.commercetools.sync.categories.CategorySyncOptionsBuilder) Resource(io.sphere.sdk.models.Resource) CategorySyncOptions(com.commercetools.sync.categories.CategorySyncOptions) CustomFieldsDraft(io.sphere.sdk.types.CustomFieldsDraft) PriceCustomActionBuilder(com.commercetools.sync.products.helpers.PriceCustomActionBuilder) SetProductPriceCustomField(io.sphere.sdk.products.commands.updateactions.SetProductPriceCustomField) Asset(io.sphere.sdk.models.Asset) Type(io.sphere.sdk.types.Type) Optional(java.util.Optional) UpdateAction(io.sphere.sdk.commands.UpdateAction) ArrayList(java.util.ArrayList) AssetCustomActionBuilder(com.commercetools.sync.products.helpers.AssetCustomActionBuilder) Product(io.sphere.sdk.products.Product) SyncException(com.commercetools.sync.commons.exceptions.SyncException) SyncException(com.commercetools.sync.commons.exceptions.SyncException) BuildUpdateActionException(com.commercetools.sync.commons.exceptions.BuildUpdateActionException) SetProductPriceCustomType(io.sphere.sdk.products.commands.updateactions.SetProductPriceCustomType) SetAssetCustomType(io.sphere.sdk.products.commands.updateactions.SetAssetCustomType) Type(io.sphere.sdk.types.Type) CustomFields(io.sphere.sdk.types.CustomFields) AssetDraft(io.sphere.sdk.models.AssetDraft) Asset(io.sphere.sdk.models.Asset) Collections.emptyList(java.util.Collections.emptyList) List(java.util.List) ArrayList(java.util.ArrayList) ProductSyncOptions(com.commercetools.sync.products.ProductSyncOptions) CustomFieldsDraft(io.sphere.sdk.types.CustomFieldsDraft) Test(org.junit.jupiter.api.Test)

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