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);
}
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();
}
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));
}
});
}
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;
}
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);
}
}
Aggregations