This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new 6ee07102fbdc CAMEL-28121: camel-alibaba-oss - pass a failed delete of 
a consumed object to the exception handler (#31396)
6ee07102fbdc is described below

commit 6ee07102fbdcb58b1a6a031454a360edc380b4e1
Author: Saravanakumar Selvaraj <[email protected]>
AuthorDate: Sun Dec 6 02:27:03 2026 +0530

    CAMEL-28121: camel-alibaba-oss - pass a failed delete of a consumed object 
to the exception handler (#31396)
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../camel/catalog/docs/alibaba-oss-component.adoc  |   1 +
 .../src/main/docs/alibaba-oss-component.adoc       |   1 +
 .../camel/component/alibaba/oss/OSSConsumer.java   |  22 ++-
 .../alibaba/oss/OSSConsumerFailedDeleteTest.java   | 178 +++++++++++++++++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_25.adoc    |  15 ++
 5 files changed, 210 insertions(+), 7 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/alibaba-oss-component.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/alibaba-oss-component.adoc
index 6566fd4d5e3b..aaef7111591f 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/alibaba-oss-component.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/alibaba-oss-component.adoc
@@ -62,6 +62,7 @@ include::partial$component-endpoint-headers.adoc[]
 
 The consumer polls objects from a bucket using `listObjectsV2`, downloads each 
object body, and optionally deletes objects after they have been processed when 
`deleteAfterRead` is enabled.
 The consumer deletes the object it consumed, whatever the route does with the 
`CamelAlibabaOssBucketName` and `CamelAlibabaOssObjectKey` headers.
+A failed delete goes to the exception handler of the consumer.
 A route can set the bucket name header to write a copy of the object to 
another bucket.
 
 By default (`includeBody=true`) the consumer reads the content of each object 
into a `byte[]`, which is the body, so an object needs as much memory as its 
size.
diff --git 
a/components/camel-alibaba/camel-alibaba-oss/src/main/docs/alibaba-oss-component.adoc
 
b/components/camel-alibaba/camel-alibaba-oss/src/main/docs/alibaba-oss-component.adoc
index 6566fd4d5e3b..aaef7111591f 100644
--- 
a/components/camel-alibaba/camel-alibaba-oss/src/main/docs/alibaba-oss-component.adoc
+++ 
b/components/camel-alibaba/camel-alibaba-oss/src/main/docs/alibaba-oss-component.adoc
@@ -62,6 +62,7 @@ include::partial$component-endpoint-headers.adoc[]
 
 The consumer polls objects from a bucket using `listObjectsV2`, downloads each 
object body, and optionally deletes objects after they have been processed when 
`deleteAfterRead` is enabled.
 The consumer deletes the object it consumed, whatever the route does with the 
`CamelAlibabaOssBucketName` and `CamelAlibabaOssObjectKey` headers.
+A failed delete goes to the exception handler of the consumer.
 A route can set the bucket name header to write a copy of the object to 
another bucket.
 
 By default (`includeBody=true`) the consumer reads the content of each object 
into a `byte[]`, which is the body, so an object needs as much memory as its 
size.
diff --git 
a/components/camel-alibaba/camel-alibaba-oss/src/main/java/org/apache/camel/component/alibaba/oss/OSSConsumer.java
 
b/components/camel-alibaba/camel-alibaba-oss/src/main/java/org/apache/camel/component/alibaba/oss/OSSConsumer.java
index f78e45b2443d..5db3cfede85b 100644
--- 
a/components/camel-alibaba/camel-alibaba-oss/src/main/java/org/apache/camel/component/alibaba/oss/OSSConsumer.java
+++ 
b/components/camel-alibaba/camel-alibaba-oss/src/main/java/org/apache/camel/component/alibaba/oss/OSSConsumer.java
@@ -133,7 +133,7 @@ public class OSSConsumer extends 
ScheduledBatchPollingConsumer {
                 @Override
                 public void onComplete(Exchange exchange) {
                     try {
-                        processComplete(bucketName, objectKey);
+                        processComplete(exchange, bucketName, objectKey);
                     } finally {
                         inProgress.remove(objectKey);
                     }
@@ -291,18 +291,26 @@ public class OSSConsumer extends 
ScheduledBatchPollingConsumer {
     }
 
     /**
-     * Deletes the consumed object, with {@code deleteAfterRead}.
+     * Deletes the consumed object, with {@code deleteAfterRead}. A failed 
delete goes to the exception handler of the
+     * consumer.
      *
+     * @param exchange   the exchange of the consumed object
      * @param bucketName the bucket the object was consumed from
      * @param objectKey  the key of the consumed object
      */
-    private void processComplete(String bucketName, String objectKey) {
+    private void processComplete(Exchange exchange, String bucketName, String 
objectKey) {
         if (endpoint.isDeleteAfterRead()) {
             if (ObjectHelper.isNotEmpty(bucketName) && 
ObjectHelper.isNotEmpty(objectKey)) {
-                ossClient.deleteObject(DeleteObjectRequest.newBuilder()
-                        .bucket(bucketName)
-                        .key(objectKey)
-                        .build());
+                try {
+                    ossClient.deleteObject(DeleteObjectRequest.newBuilder()
+                            .bucket(bucketName)
+                            .key(objectKey)
+                            .build());
+                } catch (Exception e) {
+                    getExceptionHandler().handleException("Error deleting 
object " + objectKey + " from bucket "
+                                                          + bucketName + ". A 
later poll may consume the object again.",
+                            exchange, e);
+                }
             }
         }
     }
diff --git 
a/components/camel-alibaba/camel-alibaba-oss/src/test/java/org/apache/camel/component/alibaba/oss/OSSConsumerFailedDeleteTest.java
 
b/components/camel-alibaba/camel-alibaba-oss/src/test/java/org/apache/camel/component/alibaba/oss/OSSConsumerFailedDeleteTest.java
new file mode 100644
index 000000000000..b897acb85375
--- /dev/null
+++ 
b/components/camel-alibaba/camel-alibaba-oss/src/test/java/org/apache/camel/component/alibaba/oss/OSSConsumerFailedDeleteTest.java
@@ -0,0 +1,178 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.alibaba.oss;
+
+import java.io.ByteArrayInputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ConcurrentSkipListSet;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import com.aliyun.sdk.service.oss2.OSSClient;
+import com.aliyun.sdk.service.oss2.exceptions.OperationException;
+import com.aliyun.sdk.service.oss2.exceptions.ServiceException;
+import com.aliyun.sdk.service.oss2.models.DeleteObjectRequest;
+import com.aliyun.sdk.service.oss2.models.GetObjectRequest;
+import com.aliyun.sdk.service.oss2.models.GetObjectResult;
+import com.aliyun.sdk.service.oss2.models.ListObjectsV2Request;
+import com.aliyun.sdk.service.oss2.models.ListObjectsV2Result;
+import com.aliyun.sdk.service.oss2.models.ObjectSummary;
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.alibaba.oss.constants.OSSHeaders;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.spi.ExceptionHandler;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
+/**
+ * With deleteAfterRead, the exception handler of the consumer gets a failed 
delete with the exchange of the object.
+ * With bridgeErrorHandler, the error handler of the route gets it. The object 
stays, so a later poll consumes it again.
+ */
+class OSSConsumerFailedDeleteTest extends CamelTestSupport {
+
+    private final Set<String> objects = new ConcurrentSkipListSet<>();
+    private final OperationException deleteError = new OperationException(
+            "DeleteObject", 
ServiceException.newBuilder().statusCode(403).build());
+    private final AtomicInteger deletes = new AtomicInteger();
+    // the calls of the exception handler of the consumer
+    private final List<HandledException> handled = new 
CopyOnWriteArrayList<>();
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        CamelContext context = super.createCamelContext();
+        context.getRegistry().bind("ossClient", ossClient());
+        context.getRegistry().bind("recordingHandler", new 
RecordingExceptionHandler());
+        return context;
+    }
+
+    @Test
+    void failedDeleteGoesToTheExceptionHandlerOfTheConsumer() throws Exception 
{
+        objects.add("a.txt");
+        MockEndpoint mock = getMockEndpoint("mock:result");
+        // the first delete fails, so a later poll consumes the object again, 
and deletes it
+        mock.expectedBodiesReceived("a.txt", "a.txt");
+        mock.setAssertPeriod(500);
+
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                
from("alibaba-oss:bucket?ossClient=#ossClient&initialDelay=0&delay=10&deleteAfterRead=true"
+                     + "&exceptionHandler=#recordingHandler")
+                        .convertBodyTo(String.class)
+                        .to("mock:result");
+            }
+        });
+
+        mock.assertIsSatisfied();
+        await().atMost(10, TimeUnit.SECONDS).until(objects::isEmpty);
+        assertThat(handled).as("the calls of the exception 
handler").hasSize(1);
+        assertThat(handled.get(0).exception()).isSameAs(deleteError);
+        assertThat(handled.get(0).objectKey()).as("the object key of the 
exchange").isEqualTo("a.txt");
+        assertThat(handled.get(0).message()).contains("a.txt");
+    }
+
+    @Test
+    void failedDeleteGoesToTheErrorHandlerOfTheRouteWithBridgeErrorHandler() 
throws Exception {
+        objects.add("a.txt");
+        MockEndpoint mock = getMockEndpoint("mock:result");
+        // the first delete fails, so a later poll consumes the object again, 
and deletes it
+        mock.expectedBodiesReceived("a.txt", "a.txt");
+        mock.setAssertPeriod(500);
+        MockEndpoint dead = getMockEndpoint("mock:dead");
+        dead.expectedMessageCount(1);
+        dead.setAssertPeriod(500);
+
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                errorHandler(deadLetterChannel("mock:dead"));
+
+                
from("alibaba-oss:bucket?ossClient=#ossClient&initialDelay=0&delay=10&deleteAfterRead=true"
+                     + "&bridgeErrorHandler=true")
+                        .convertBodyTo(String.class)
+                        .to("mock:result");
+            }
+        });
+
+        MockEndpoint.assertIsSatisfied(context);
+        await().atMost(10, TimeUnit.SECONDS).until(objects::isEmpty);
+        Exchange bridged = dead.getReceivedExchanges().get(0);
+        
assertThat(bridged.getProperty(Exchange.EXCEPTION_CAUGHT)).isSameAs(deleteError);
+        assertThat(bridged.getProperty(Exchange.ERRORHANDLER_BRIDGE, 
Boolean.class)).isTrue();
+        
assertThat(bridged.getIn().getHeader(OSSHeaders.OBJECT_KEY)).isEqualTo("a.txt");
+        assertThat(bridged.getIn().getBody(String.class)).as("the error 
message").contains("a.txt");
+    }
+
+    private OSSClient ossClient() {
+        OSSClient client = Mockito.mock(OSSClient.class);
+        
Mockito.when(client.listObjectsV2(Mockito.any(ListObjectsV2Request.class))).thenAnswer(i
 -> {
+            List<ObjectSummary> contents = objects.stream().map(key -> {
+                ObjectSummary summary = Mockito.mock(ObjectSummary.class);
+                Mockito.when(summary.key()).thenReturn(key);
+                return summary;
+            }).toList();
+            ListObjectsV2Result result = 
Mockito.mock(ListObjectsV2Result.class);
+            Mockito.when(result.contents()).thenReturn(contents);
+            return result;
+        });
+        
Mockito.when(client.getObject(Mockito.any(GetObjectRequest.class))).thenAnswer(i
 -> {
+            String key = i.<GetObjectRequest> getArgument(0).key();
+            GetObjectResult result = Mockito.mock(GetObjectResult.class);
+            Mockito.when(result.body()).thenReturn(new 
ByteArrayInputStream(key.getBytes(StandardCharsets.UTF_8)));
+            return result;
+        });
+        
Mockito.when(client.deleteObject(Mockito.any(DeleteObjectRequest.class))).thenAnswer(i
 -> {
+            if (deletes.incrementAndGet() == 1) {
+                throw deleteError;
+            }
+            objects.remove(i.<DeleteObjectRequest> getArgument(0).key());
+            return null;
+        });
+        return client;
+    }
+
+    private record HandledException(String message, String objectKey, 
Throwable exception) {
+    }
+
+    private final class RecordingExceptionHandler implements ExceptionHandler {
+        @Override
+        public void handleException(Throwable exception) {
+            handleException(null, null, exception);
+        }
+
+        @Override
+        public void handleException(String message, Throwable exception) {
+            handleException(message, null, exception);
+        }
+
+        @Override
+        public void handleException(String message, Exchange exchange, 
Throwable exception) {
+            // the handler reads the key now, as a pooled exchange factory may 
reuse the exchange after this call
+            String objectKey = exchange != null ? 
exchange.getIn().getHeader(OSSHeaders.OBJECT_KEY, String.class) : null;
+            handled.add(new HandledException(message, objectKey, exception));
+        }
+    }
+}
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc
index aafcdc617a64..41af1f64a5c5 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc
@@ -341,6 +341,21 @@ A route that tests the `code` key of the body for an error 
needs `onException`,
 handler that redelivers now sends such a request again. A test that mocks the 
client must return a body with the `Code`
 `OK` for a send that succeeds.
 
+=== camel-alibaba-oss - a failed delete of a consumed object goes to the 
exception handler
+
+With `deleteAfterRead=true`, a failed delete of a consumed object now goes to 
the exception handler of the `alibaba-oss`
+consumer. The handler gets the exchange of the object. Before, a failed delete 
reached no exception handler, and Camel
+only logged it at WARN level. The default exception handler of the consumer 
logs it at WARN level too. A later poll may
+consume the object again, as before. So a delete that always fails reaches the 
handler at every poll that lists the
+object.
+
+With `bridgeErrorHandler=true`, the error handler of the route now gets a copy 
of that exchange. Its body is the error
+message, which names the bucket and the key. The `CamelExceptionCaught` 
exchange property holds the exception, and the
+`CamelErrorHandlerBridge` exchange property is `true`. The default error 
handler logs the copy at ERROR level, and a
+dead letter channel receives it. An error handler that reads the body as the 
content of an object must allow for these
+copies. For an exchange that the route ended with `stop()`, the copy reaches 
no error handler, and nothing logs the
+failure.
+
 === camel-alibaba-oss - listBuckets returns every bucket, and listObjects uses 
ListObjectsV2
 
 The `listBuckets` operation of `alibaba-oss` now returns every bucket of the 
account. Before, it returned only the

Reply via email to