Search in sources :

Example 6 with SyncException

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

the class InventorySyncIT method sync_WithCustomErrorCallback_ShouldExecuteCallbackOnError.

@Test
void sync_WithCustomErrorCallback_ShouldExecuteCallbackOnError() {
    // Fetch new inventories from source project. Convert them to drafts.
    final List<InventoryEntry> inventoryEntries = CTP_SOURCE_CLIENT.execute(InventoryEntryQuery.of().withExpansionPaths(InventoryEntryExpansionModel::supplyChannel).plusExpansionPaths(ExpansionPath.of("custom.type"))).toCompletableFuture().join().getResults();
    final List<InventoryEntryDraft> newInventories = InventoryTransformUtils.toInventoryEntryDrafts(CTP_SOURCE_CLIENT, REFERENCE_ID_TO_KEY_CACHE, inventoryEntries).join();
    // Prepare sync options and perform sync of draft to target project.
    final AtomicInteger invocationCounter = new AtomicInteger(0);
    QuadConsumer<SyncException, Optional<InventoryEntryDraft>, Optional<InventoryEntry>, List<UpdateAction<InventoryEntry>>> countingErrorCallback = (exception, newResource, oldResource, updateActions) -> invocationCounter.incrementAndGet();
    final InventorySyncOptions inventorySyncOptions = InventorySyncOptionsBuilder.of(CTP_TARGET_CLIENT).errorCallback(countingErrorCallback).ensureChannels(false).build();
    final InventorySync inventorySync = new InventorySync(inventorySyncOptions);
    final InventorySyncStatistics inventorySyncStatistics = inventorySync.sync(newInventories).toCompletableFuture().join();
    assertThat(inventorySyncStatistics).hasValues(3, 0, 1, 1);
    assertThat(invocationCounter.get()).isEqualTo(1);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) SUPPLY_CHANNEL_KEY_2(com.commercetools.sync.integration.inventories.utils.InventoryITUtils.SUPPLY_CHANNEL_KEY_2) SUPPLY_CHANNEL_KEY_1(com.commercetools.sync.integration.inventories.utils.InventoryITUtils.SUPPLY_CHANNEL_KEY_1) Reference(io.sphere.sdk.models.Reference) CTP_SOURCE_CLIENT(com.commercetools.sync.integration.commons.utils.SphereClientUtils.CTP_SOURCE_CLIENT) SyncException(com.commercetools.sync.commons.exceptions.SyncException) InventoryEntryDraft(io.sphere.sdk.inventory.InventoryEntryDraft) ITUtils.deleteTypesFromTargetAndSource(com.commercetools.sync.integration.commons.utils.ITUtils.deleteTypesFromTargetAndSource) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ZonedDateTime(java.time.ZonedDateTime) InventorySyncOptionsBuilder(com.commercetools.sync.inventories.InventorySyncOptionsBuilder) UpdateAction(io.sphere.sdk.commands.UpdateAction) QuadConsumer(com.commercetools.sync.commons.utils.QuadConsumer) Disabled(org.junit.jupiter.api.Disabled) Channel(io.sphere.sdk.channels.Channel) Collections.singletonList(java.util.Collections.singletonList) ExpansionPath(io.sphere.sdk.expansion.ExpansionPath) AfterAll(org.junit.jupiter.api.AfterAll) SKU_2(com.commercetools.sync.integration.inventories.utils.InventoryITUtils.SKU_2) SKU_1(com.commercetools.sync.integration.inventories.utils.InventoryITUtils.SKU_1) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ChannelQuery(io.sphere.sdk.channels.queries.ChannelQuery) InventoryEntry(io.sphere.sdk.inventory.InventoryEntry) RESTOCKABLE_IN_DAYS_1(com.commercetools.sync.integration.inventories.utils.InventoryITUtils.RESTOCKABLE_IN_DAYS_1) RESTOCKABLE_IN_DAYS_2(com.commercetools.sync.integration.inventories.utils.InventoryITUtils.RESTOCKABLE_IN_DAYS_2) InventoryITUtils.populateSourceProject(com.commercetools.sync.integration.inventories.utils.InventoryITUtils.populateSourceProject) Test(org.junit.jupiter.api.Test) InventoryITUtils.populateTargetProject(com.commercetools.sync.integration.inventories.utils.InventoryITUtils.populateTargetProject) InventoryEntryDraftBuilder(io.sphere.sdk.inventory.InventoryEntryDraftBuilder) List(java.util.List) InventorySyncOptions(com.commercetools.sync.inventories.InventorySyncOptions) Optional(java.util.Optional) CTP_TARGET_CLIENT(com.commercetools.sync.integration.commons.utils.SphereClientUtils.CTP_TARGET_CLIENT) ResourceIdentifier(io.sphere.sdk.models.ResourceIdentifier) IntStream(java.util.stream.IntStream) AssertionsForStatistics.assertThat(com.commercetools.sync.commons.asserts.statistics.AssertionsForStatistics.assertThat) CompletableFuture(java.util.concurrent.CompletableFuture) InventoryEntryQuery(io.sphere.sdk.inventory.queries.InventoryEntryQuery) Nonnull(javax.annotation.Nonnull) InventoryITUtils.getChannelByKey(com.commercetools.sync.integration.inventories.utils.InventoryITUtils.getChannelByKey) Nullable(javax.annotation.Nullable) InventoryITUtils.getInventoryEntryBySkuAndSupplyChannel(com.commercetools.sync.integration.inventories.utils.InventoryITUtils.getInventoryEntryBySkuAndSupplyChannel) ChannelRole(io.sphere.sdk.channels.ChannelRole) LongStream(java.util.stream.LongStream) EXPECTED_DELIVERY_1(com.commercetools.sync.integration.inventories.utils.InventoryITUtils.EXPECTED_DELIVERY_1) EXPECTED_DELIVERY_2(com.commercetools.sync.integration.inventories.utils.InventoryITUtils.EXPECTED_DELIVERY_2) ChannelITUtils.deleteChannelsFromTargetAndSource(com.commercetools.sync.integration.commons.utils.ChannelITUtils.deleteChannelsFromTargetAndSource) REFERENCE_ID_TO_KEY_CACHE(com.commercetools.sync.integration.inventories.utils.InventoryITUtils.REFERENCE_ID_TO_KEY_CACHE) InventoryITUtils.deleteInventoryEntriesFromTargetAndSource(com.commercetools.sync.integration.inventories.utils.InventoryITUtils.deleteInventoryEntriesFromTargetAndSource) InventorySync(com.commercetools.sync.inventories.InventorySync) QUANTITY_ON_STOCK_1(com.commercetools.sync.integration.inventories.utils.InventoryITUtils.QUANTITY_ON_STOCK_1) Collectors.toList(java.util.stream.Collectors.toList) InventoryEntryExpansionModel(io.sphere.sdk.inventory.expansion.InventoryEntryExpansionModel) InventoryTransformUtils(com.commercetools.sync.inventories.utils.InventoryTransformUtils) QUANTITY_ON_STOCK_2(com.commercetools.sync.integration.inventories.utils.InventoryITUtils.QUANTITY_ON_STOCK_2) InventorySyncStatistics(com.commercetools.sync.inventories.helpers.InventorySyncStatistics) Optional(java.util.Optional) InventorySync(com.commercetools.sync.inventories.InventorySync) InventoryEntry(io.sphere.sdk.inventory.InventoryEntry) SyncException(com.commercetools.sync.commons.exceptions.SyncException) InventorySyncOptions(com.commercetools.sync.inventories.InventorySyncOptions) InventoryEntryDraft(io.sphere.sdk.inventory.InventoryEntryDraft) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InventorySyncStatistics(com.commercetools.sync.inventories.helpers.InventorySyncStatistics) Collections.singletonList(java.util.Collections.singletonList) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Test(org.junit.jupiter.api.Test)

Example 7 with SyncException

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

the class ProductSync method handleError.

/**
 * Given a {@link String} {@code errorMessage} and a {@link Throwable} {@code exception}, this
 * method calls the optional error callback specified in the {@code syncOptions} and updates the
 * {@code statistics} instance by incrementing the total number of failed products to sync.
 *
 * @param errorMessage The error message describing the reason(s) of failure.
 * @param exception The exception that called caused the failure, if any.
 * @param oldProduct the ProductProjection which could be updated.
 * @param newProduct the ProductProjection draft where we get the new data.
 * @param updateActions the update actions to update the {@link Product} with.
 */
private void handleError(@Nonnull final String errorMessage, @Nullable final Throwable exception, @Nullable final ProductProjection oldProduct, @Nullable final ProductDraft newProduct, @Nullable final List<UpdateAction<Product>> updateActions) {
    SyncException syncException = exception != null ? new SyncException(errorMessage, exception) : new SyncException(errorMessage);
    syncOptions.applyErrorCallback(syncException, oldProduct, newProduct, updateActions);
    statistics.incrementFailed();
}
Also used : SyncException(com.commercetools.sync.commons.exceptions.SyncException)

Example 8 with SyncException

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

the class ProductSync method syncBatch.

@Nonnull
private CompletionStage<Void> syncBatch(@Nonnull final Set<ProductDraft> productDrafts, @Nonnull final Map<String, String> keyToIdCache) {
    if (productDrafts.isEmpty()) {
        return CompletableFuture.completedFuture(null);
    }
    final Set<String> productDraftKeys = productDrafts.stream().map(ProductDraft::getKey).collect(Collectors.toSet());
    return productService.fetchMatchingProductsByKeys(productDraftKeys).handle(ImmutablePair::new).thenCompose(fetchResponse -> {
        final Throwable fetchException = fetchResponse.getValue();
        if (fetchException != null) {
            final String errorMessage = format(CTP_PRODUCT_FETCH_FAILED, productDraftKeys);
            handleError(new SyncException(errorMessage, fetchException), productDraftKeys.size());
            return CompletableFuture.completedFuture(null);
        } else {
            final Set<ProductProjection> matchingProducts = fetchResponse.getKey();
            return syncOrKeepTrack(productDrafts, matchingProducts, keyToIdCache).thenCompose(aVoid -> resolveNowReadyReferences(keyToIdCache));
        }
    });
}
Also used : ProductProjection(io.sphere.sdk.products.ProductProjection) SyncException(com.commercetools.sync.commons.exceptions.SyncException) Nonnull(javax.annotation.Nonnull)

Example 9 with SyncException

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

the class AssetsUpdateActionUtils method buildAssetsUpdateActionsWithNewAssetDrafts.

/**
 * Compares a list of {@link Asset}s with a list of {@link AssetDraft}s. The method serves as a
 * generic implementation for assets syncing. The method takes in functions for building the
 * required update actions ( AddAsset, RemoveAsset, ChangeAssetOrder and 1-1 update actions on
 * assets (e.g. changeAssetName, setAssetDescription, etc..) for the required resource.
 *
 * @param oldAssets the old list of assets.
 * @param newAssetDrafts the new list of asset drafts.
 * @param assetActionFactory factory responsible for building asset update actions.
 * @param <T> the type of the resource the asset update actions are built for.
 * @param syncOptions responsible for supplying the sync options to the sync utility method. It is
 *     used for triggering the warn callback within the utility
 * @return a list of asset update actions on the resource of type T if the list of assets is not
 *     identical. Otherwise, if the assets are identical, an empty list is returned.
 * @throws BuildUpdateActionException in case there are asset drafts with duplicate keys.
 */
@SuppressWarnings("unchecked")
@Nonnull
private static <T extends Resource, D> List<UpdateAction<T>> buildAssetsUpdateActionsWithNewAssetDrafts(@Nonnull final D newResource, @Nonnull final List<Asset> oldAssets, @Nonnull final List<AssetDraft> newAssetDrafts, @Nonnull final AssetActionFactory<T, D> assetActionFactory, @Nonnull final BaseSyncOptions syncOptions) throws BuildUpdateActionException {
    // Asset set that has only the keys of the assets which should be removed, this is used in the
    // method
    // #buildChangeAssetOrderUpdateAction in order to compare the state of the asset lists after the
    // remove actions
    // have already been applied.
    final HashSet<String> removedAssetKeys = new HashSet<>();
    final Map<String, Asset> oldAssetsKeyMap = new HashMap<>();
    oldAssets.forEach(asset -> {
        String assetKey = asset.getKey();
        if (isNotBlank(assetKey)) {
            oldAssetsKeyMap.put(assetKey, asset);
        } else {
            syncOptions.applyWarningCallback(new SyncException(format(ASSET_KEY_NOT_SET, "id: " + asset.getId())), asset, null);
        }
    });
    final Map<String, AssetDraft> newAssetDraftsKeyMap = new HashMap<>();
    try {
        newAssetDrafts.forEach(newAsset -> {
            String assetKey = newAsset.getKey();
            if (isNotBlank(assetKey)) {
                newAssetDraftsKeyMap.merge(assetKey, newAsset, (assetDraftA, assetDraftB) -> {
                    throw new DuplicateKeyException("Supplied asset drafts have duplicate keys. Asset keys are" + " expected to be unique inside their container (a product variant or a category).");
                });
            } else {
                syncOptions.applyWarningCallback(new SyncException(format(ASSET_KEY_NOT_SET, "name: " + newAsset.getName())), null, newAsset);
            }
        });
    } catch (final DuplicateKeyException exception) {
        throw new BuildUpdateActionException(exception);
    }
    // It is important to have a changeAssetOrder action before an addAsset action, since
    // changeAssetOrder requires
    // asset ids for sorting them, and new assets don't have ids yet since they are generated
    // by CTP after an asset is created. Therefore, the order of update actions must be:
    // 1. Remove or compare if matching.
    final List<UpdateAction<T>> updateActions = buildRemoveAssetOrAssetUpdateActions(newResource, oldAssets, removedAssetKeys, newAssetDraftsKeyMap, assetActionFactory);
    // 2. Compare ordering of assets and add a ChangeAssetOrder action if needed.
    buildChangeAssetOrderUpdateAction(oldAssets, newAssetDrafts, removedAssetKeys, assetActionFactory).ifPresent(updateActions::add);
    // For every new asset draft, If it doesn't exist in the old assets, then add an AddAsset action
    // to the list
    // of update actions.
    updateActions.addAll(buildAddAssetUpdateActions(newAssetDrafts, oldAssetsKeyMap, assetActionFactory));
    return updateActions;
}
Also used : HashMap(java.util.HashMap) UpdateAction(io.sphere.sdk.commands.UpdateAction) CommonTypeUpdateActionUtils.buildUpdateAction(com.commercetools.sync.commons.utils.CommonTypeUpdateActionUtils.buildUpdateAction) SyncException(com.commercetools.sync.commons.exceptions.SyncException) BuildUpdateActionException(com.commercetools.sync.commons.exceptions.BuildUpdateActionException) DuplicateKeyException(com.commercetools.sync.commons.exceptions.DuplicateKeyException) AssetDraft(io.sphere.sdk.models.AssetDraft) Asset(io.sphere.sdk.models.Asset) HashSet(java.util.HashSet) Nonnull(javax.annotation.Nonnull)

Example 10 with SyncException

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

the class InventorySync method processFetchedInventories.

private CompletionStage<Void> processFetchedInventories(@Nonnull final Set<InventoryEntryDraft> resolvedDrafts, @Nonnull final Set<InventoryEntryIdentifier> identifiers, @Nonnull final ImmutablePair<Set<InventoryEntry>, Throwable> fetchResponse) {
    final Set<InventoryEntry> fetchedInventoryEntries = fetchResponse.getKey();
    final Throwable exception = fetchResponse.getValue();
    if (exception != null) {
        final String errorMessage = format(CTP_INVENTORY_FETCH_FAILED, identifiers);
        handleError(new SyncException(errorMessage, exception), identifiers.size());
        return CompletableFuture.completedFuture(null);
    } else {
        return syncBatch(fetchedInventoryEntries, resolvedDrafts);
    }
}
Also used : InventoryEntry(io.sphere.sdk.inventory.InventoryEntry) SyncException(com.commercetools.sync.commons.exceptions.SyncException)

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