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-jbang-examples.git


The following commit(s) were added to refs/heads/main by this push:
     new c54d176  route/scatter-gather - ask three suppliers at once, wait two 
seconds, pick the best quote (#147)
c54d176 is described below

commit c54d1761bddf58cf36188d400f8b47f279c260cf
Author: Claus Ibsen <[email protected]>
AuthorDate: Mon Nov 30 06:56:47 2026 +0100

    route/scatter-gather - ask three suppliers at once, wait two seconds, pick 
the best quote (#147)
    
    Closes #146
    
    
    Claude-Session: https://claude.ai/code/session_016Y4dDi5iQNgtHrDdz2NpwF
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 .github/workflows/build.yml                        |   2 +
 README.md                                          |   1 +
 camel-jbang-example-catalog.json                   |  53 +++++++++
 route/README.md                                    |   1 +
 route/scatter-gather/README.md                     |  96 ++++++++++++++++
 route/scatter-gather/application.properties        |  21 ++++
 route/scatter-gather/metadata.json                 |  42 +++++++
 route/scatter-gather/restock/restock-1001.json     |   1 +
 route/scatter-gather/restock/restock-1002.json     |   1 +
 route/scatter-gather/scatter-gather.camel.yaml     | 128 +++++++++++++++++++++
 route/scatter-gather/suppliers.camel.yaml          |  55 +++++++++
 .../test/scatter-gather.citrus.it.yaml             |  45 ++++++++
 12 files changed, 446 insertions(+)

diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index e257d4c..87c4163 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -89,6 +89,8 @@ jobs:
             path: route/dynamic-routing
           - name: Batch file
             path: route/batch-file
+          - name: Scatter-gather
+            path: route/scatter-gather
           - name: Error handling
             path: fail-well/error-handling
           - name: Circuit breaker
diff --git a/README.md b/README.md
index 42e4f57..3b06066 100644
--- a/README.md
+++ b/README.md
@@ -78,6 +78,7 @@ The routing patterns: content-based router, splitter, 
aggregator, filter and mul
 | [Enrich and deduplicate](route/enrich-and-dedupe/) | The three orders and a 
resent copy of ORD-1001 are read; an idempotent consumer accepts each order id 
once and logs the resent one as a duplicate, each accepted order is enriched 
with its customer's name and tier from customers/ with pollEnrich, and a wire 
tap writes a copy to audit/ without holding the order up. | nothing |
 | [Dynamic routing](route/dynamic-routing/) | Each of the three orders goes to 
the warehouse of its country and to the billing of its status through a 
recipient list computed from the order; billing a paid order fails over from a 
primary invoice service that is down to a backup one, the pending order gets no 
invoice, and the US warehouse is throttled to one order per second. | nothing |
 | [Batch file](route/batch-file/) | Two settlement files of the payment 
provider, 5000 payments each, are read line by line with a streaming split; 
each payment of 500 EUR or more is logged, the two lines whose amount is not a 
number go to rejects/ while the rest of the file goes on, and a summary line is 
logged when a file is done. | nothing |
+| [Scatter-gather](route/scatter-gather/) | Two restock requests are sent to 
three suppliers at the same time with a multicast that waits at most two 
seconds; the slow supplier is left out, a supplier that answers 404 is logged 
and skipped, and Groovy picks the lowest price, with the shorter delivery time 
on the same price. | nothing |
 
 ### [Fail well](fail-well/)
 
diff --git a/camel-jbang-example-catalog.json b/camel-jbang-example-catalog.json
index 33c2074..d25ba9f 100644
--- a/camel-jbang-example-catalog.json
+++ b/camel-jbang-example-catalog.json
@@ -1548,6 +1548,59 @@
         ],
         "order": 2
     },
+    {
+        "name": "route/scatter-gather",
+        "title": "Scatter-gather",
+        "description": "Two restock requests are sent to three suppliers at 
the same time with a multicast that waits at most two seconds; the slow 
supplier is left out, a supplier that answers 404 is logged and skipped, and 
Groovy picks the lowest price, with the shorter delivery time on the same 
price.",
+        "level": "route",
+        "teaches": {
+            "components": [
+                "file",
+                "direct",
+                "http",
+                "platform-http",
+                "log"
+            ],
+            "eips": [
+                "multicast",
+                "doTry",
+                "choice",
+                "delay",
+                "setVariable",
+                "setBody",
+                "toD",
+                "unmarshal",
+                "marshal"
+            ],
+            "languages": [
+                "simple",
+                "groovy"
+            ],
+            "dataformats": [
+                "json"
+            ]
+        },
+        "tags": [
+            "shop",
+            "eip",
+            "scatter-gather",
+            "parallel",
+            "timeout",
+            "quotes"
+        ],
+        "bundled": true,
+        "requiresDocker": false,
+        "hasCitrusTests": true,
+        "files": [
+            "README.md",
+            "application.properties",
+            "restock/restock-1001.json",
+            "restock/restock-1002.json",
+            "scatter-gather.camel.yaml",
+            "suppliers.camel.yaml"
+        ],
+        "order": 8
+    },
     {
         "name": "run/nightly-report",
         "title": "Nightly report",
diff --git a/route/README.md b/route/README.md
index 7fa60a3..a60a931 100644
--- a/route/README.md
+++ b/route/README.md
@@ -12,6 +12,7 @@ The routing patterns: content-based router, splitter, 
aggregator, filter and mul
 | [Enrich and deduplicate](enrich-and-dedupe/) | The three orders and a resent 
copy of ORD-1001 are read; an idempotent consumer accepts each order id once 
and logs the resent one as a duplicate, each accepted order is enriched with 
its customer's name and tier from customers/ with pollEnrich, and a wire tap 
writes a copy to audit/ without holding the order up. | nothing |
 | [Dynamic routing](dynamic-routing/) | Each of the three orders goes to the 
warehouse of its country and to the billing of its status through a recipient 
list computed from the order; billing a paid order fails over from a primary 
invoice service that is down to a backup one, the pending order gets no 
invoice, and the US warehouse is throttled to one order per second. | nothing |
 | [Batch file](batch-file/) | Two settlement files of the payment provider, 
5000 payments each, are read line by line with a streaming split; each payment 
of 500 EUR or more is logged, the two lines whose amount is not a number go to 
rejects/ while the rest of the file goes on, and a summary line is logged when 
a file is done. | nothing |
+| [Scatter-gather](scatter-gather/) | Two restock requests are sent to three 
suppliers at the same time with a multicast that waits at most two seconds; the 
slow supplier is left out, a supplier that answers 404 is logged and skipped, 
and Groovy picks the lowest price, with the shorter delivery time on the same 
price. | nothing |
 
 Start with [Content-based router](content-based-router/); the examples read 
best in the order above, each one building on what the one before it set up.
 
diff --git a/route/scatter-gather/README.md b/route/scatter-gather/README.md
new file mode 100644
index 0000000..45f3398
--- /dev/null
+++ b/route/scatter-gather/README.md
@@ -0,0 +1,96 @@
+# Scatter-gather
+
+The shop restocks its products. For each restock request it asks three 
suppliers for a quote at the same time, waits
+at most two seconds, and picks the best price: a slow supplier and a supplier 
that fails do not hold the shop up.
+
+## What you will see
+
+```text
+INFO ... scatter-gather.camel.yaml:25 : Restock RST-1001: asking 3 suppliers 
for 50 x CAMEL-MUG
+INFO ... scatter-gather.camel.yaml:117 : Supplier A quotes 4.25 (2-day 
delivery)
+INFO ... scatter-gather.camel.yaml:117 : Supplier C quotes 4.25 (1-day 
delivery)
+INFO ... scatter-gather.camel.yaml:45 : Restock RST-1001: 2 quote(s) in time
+INFO ... scatter-gather.camel.yaml:52 : Restock RST-1001: best price 4.25 from 
C (1-day delivery)
+INFO ... scatter-gather.camel.yaml:117 : Supplier B quotes 3.95 (3-day 
delivery)
+INFO ... scatter-gather.camel.yaml:25 : Restock RST-1002: asking 3 suppliers 
for 20 x CAMEL-HOODIE
+INFO ... scatter-gather.camel.yaml:117 : Supplier A quotes 4.25 (2-day 
delivery)
+INFO ... scatter-gather.camel.yaml:123 : Supplier C failed: HTTP operation 
failed invoking http://localhost:8080/supplier/C with statusCode: 404
+INFO ... scatter-gather.camel.yaml:45 : Restock RST-1002: 1 quote(s) in time
+INFO ... scatter-gather.camel.yaml:52 : Restock RST-1002: best price 4.25 from 
A (2-day delivery)
+INFO ... scatter-gather.camel.yaml:117 : Supplier B quotes 3.95 (3-day 
delivery)
+```
+
+Supplier B is the cheapest, but its quote comes after three seconds, too late 
for the two-second limit: it is logged
+after the shop has chosen.
+
+## Install Camel CLI
+
+Install [JBang](https://www.jbang.dev/download/) and the Camel CLI as 
described in the
+[root README](../../README.md#install-the-camel-cli); `camel --version` 
confirms the install.
+
+## Run it
+
+```shell
+camel run *
+```
+
+This runs the shop's routes and the three suppliers in one app, on port 8080. 
Stop the example with `ctrl` + `c`.
+
+## How it works
+
+- `restock/` holds two restock requests: 50 mugs and 20 hoodies.
+- `suppliers.camel.yaml` plays the three suppliers, so the example needs no 
other service. They answer
+  `POST /supplier/{supplier}` with a quote: A at once, B with a lower price 
after 3 seconds, C with the same price as A
+  and a shorter delivery time. C does not sell hoodies and answers 404.
+- `scatter-gather.camel.yaml` reads one request at a time 
(`maxMessagesPerPoll: 1`, sorted by name with
+  `eagerMaxMessagesPerPoll: false`). A `multicast` with `parallelProcessing: 
true` sends a copy of the request to the
+  three suppliers at the same time. `timeout` (two seconds, `quote.timeout`) 
stops the waiting; a quote that comes later
+  is left out. `GroupedBodyAggregationStrategy` collects the quotes into a 
list.
+- Each supplier has a small `direct` route that sets its name, then 
`ask-supplier` posts the request with `toD`. Its
+  `doTry` catches a failure, logs it and returns an empty body instead of a 
quote, so one failing supplier does not
+  fail the restock.
+- Groovy removes the empty bodies and picks the lowest price; on the same 
price, the shorter delivery time
+  (`min` with a comparator).
+- `application.properties` holds the suppliers' address and the timeout.
+
+## Build it step by step
+
+Ask your assistant, or type it yourself, one step at a time, and run after 
each:
+
+1. Three supplier routes on `platform-http` that answer `POST 
/supplier/{supplier}` with a quote, and a file route
+   on `restock` that asks supplier A, B and C one after another and logs each 
quote.
+2. Ask the three suppliers at the same time, and wait at most two seconds. Log 
how many quotes came in time.
+3. Supplier C does not sell hoodies and answers 404. Go on with the other 
quotes, and log
+   "Supplier C failed: ..." with the reason.
+4. Pick the lowest price. On the same price, pick the shorter delivery time, 
and log
+   "Restock RST-1001: best price 4.25 from C (1-day delivery)".
+
+## Try changing
+
+- Set `quote.timeout=4000`: supplier B is in time, and its lower price wins.
+- Remove `parallelProcessing: true`: the suppliers are asked one after 
another, and the timeout no longer helps,
+  as it applies only to parallel processing.
+- Make supplier A fail too, for example by changing its path: the restock then 
gets one quote or none, and Groovy's
+  `min` gives `null` for an empty list.
+
+## Integration testing
+
+The example comes with a test in the [Citrus](https://citrusframework.org/) 
YAML DSL,
+`test/scatter-gather.citrus.it.yaml`, which the Camel CLI runs:
+
+```shell
+camel test run test/scatter-gather.citrus.it.yaml
+```
+
+The test runs the suppliers and the shop as two integrations, and verifies the 
quotes in time, the best price, the
+tie on price and the failing supplier.
+
+## Help and contributions
+
+If you hit any problem using Camel or have some feedback, then please
+[let us know](https://camel.apache.org/community/support/).
+
+We also love contributors, so
+[get involved](https://camel.apache.org/community/contributing/) :-)
+
+The Camel riders!
diff --git a/route/scatter-gather/application.properties 
b/route/scatter-gather/application.properties
new file mode 100644
index 0000000..59f8dfc
--- /dev/null
+++ b/route/scatter-gather/application.properties
@@ -0,0 +1,21 @@
+# 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.
+
+# where the three suppliers answer; in this example they are routes of the 
same app
+shop.suppliers.url=http://localhost:8080/supplier
+# how long to wait for the quotes, in milliseconds
+quote.timeout=2000
diff --git a/route/scatter-gather/metadata.json 
b/route/scatter-gather/metadata.json
new file mode 100644
index 0000000..74e7d88
--- /dev/null
+++ b/route/scatter-gather/metadata.json
@@ -0,0 +1,42 @@
+{
+    "title": "Scatter-gather",
+    "description": "Two restock requests are sent to three suppliers at the 
same time with a multicast that waits at most two seconds; the slow supplier is 
left out, a supplier that answers 404 is logged and skipped, and Groovy picks 
the lowest price, with the shorter delivery time on the same price.",
+    "level": "route",
+    "order": 8,
+    "teaches": {
+        "components": [
+            "file",
+            "direct",
+            "http",
+            "platform-http",
+            "log"
+        ],
+        "eips": [
+            "multicast",
+            "doTry",
+            "choice",
+            "delay",
+            "setVariable",
+            "setBody",
+            "toD",
+            "unmarshal",
+            "marshal"
+        ],
+        "languages": [
+            "simple",
+            "groovy"
+        ],
+        "dataformats": [
+            "json"
+        ]
+    },
+    "tags": [
+        "shop",
+        "eip",
+        "scatter-gather",
+        "parallel",
+        "timeout",
+        "quotes"
+    ],
+    "bundled": true
+}
diff --git a/route/scatter-gather/restock/restock-1001.json 
b/route/scatter-gather/restock/restock-1001.json
new file mode 100644
index 0000000..4aea983
--- /dev/null
+++ b/route/scatter-gather/restock/restock-1001.json
@@ -0,0 +1 @@
+{"restockId": "RST-1001", "sku": "CAMEL-MUG", "qty": 50}
diff --git a/route/scatter-gather/restock/restock-1002.json 
b/route/scatter-gather/restock/restock-1002.json
new file mode 100644
index 0000000..7e20037
--- /dev/null
+++ b/route/scatter-gather/restock/restock-1002.json
@@ -0,0 +1 @@
+{"restockId": "RST-1002", "sku": "CAMEL-HOODIE", "qty": 20}
diff --git a/route/scatter-gather/scatter-gather.camel.yaml 
b/route/scatter-gather/scatter-gather.camel.yaml
new file mode 100644
index 0000000..9614824
--- /dev/null
+++ b/route/scatter-gather/scatter-gather.camel.yaml
@@ -0,0 +1,128 @@
+# The shop restocks: for each request in restock/ it asks three suppliers for 
a quote at the same time, waits at
+# most two seconds, and picks the best price. Supplier B is slow, and supplier 
C does not sell hoodies.
+- route:
+    id: restock
+    from:
+      uri: file
+      parameters:
+        directoryName: restock
+        noop: true
+        sortBy: "file:name"
+        # one request at a time, a few seconds apart, so the log reads in order
+        maxMessagesPerPoll: 1
+        # sort all files before taking the first one
+        eagerMaxMessagesPerPoll: false
+        delay: 4000
+      steps:
+        - unmarshal:
+            json:
+              library: Jackson
+        - setVariable:
+            name: restockId
+            expression:
+              simple:
+                expression: "${body[restockId]}"
+        - log:
+            message: "Restock ${variable.restockId}: asking 3 suppliers for 
${body[qty]} x ${body[sku]}"
+        # each supplier gets a copy of the request at the same time; the 
quotes that arrive within the timeout are
+        # collected into a list, a late quote is left out
+        - multicast:
+            parallelProcessing: true
+            timeout: "{{quote.timeout}}"
+            aggregationStrategy: 
"#class:org.apache.camel.processor.aggregate.GroupedBodyAggregationStrategy"
+            steps:
+              - to:
+                  uri: direct:supplier-a
+              - to:
+                  uri: direct:supplier-b
+              - to:
+                  uri: direct:supplier-c
+        # a supplier that failed gives an empty body instead of a quote
+        - setBody:
+            expression:
+              groovy:
+                expression: "body.findAll { it instanceof Map }"
+        - log:
+            message: "Restock ${variable.restockId}: ${body.size()} quote(s) 
in time"
+        # the lowest price wins; on the same price, the shortest delivery time
+        - setBody:
+            expression:
+              groovy:
+                expression: "body.min { a, b -> a.price <=> b.price ?: a.days 
<=> b.days }"
+        - log:
+            message: "Restock ${variable.restockId}: best price ${body[price]} 
from ${body[supplier]} (${body[days]}-day delivery)"
+
+# One route per supplier: it sets the supplier's name and asks it for a quote
+- route:
+    id: supplier-a
+    from:
+      uri: direct
+      parameters:
+        name: supplier-a
+      steps:
+        - setVariable:
+            name: supplier
+            expression:
+              constant:
+                expression: A
+        - to:
+            uri: direct:ask-supplier
+- route:
+    id: supplier-b
+    from:
+      uri: direct
+      parameters:
+        name: supplier-b
+      steps:
+        - setVariable:
+            name: supplier
+            expression:
+              constant:
+                expression: B
+        - to:
+            uri: direct:ask-supplier
+- route:
+    id: supplier-c
+    from:
+      uri: direct
+      parameters:
+        name: supplier-c
+      steps:
+        - setVariable:
+            name: supplier
+            expression:
+              constant:
+                expression: C
+        - to:
+            uri: direct:ask-supplier
+
+# Posts the request to the supplier and returns its quote; a supplier that 
fails is logged and gives no quote
+- route:
+    id: ask-supplier
+    from:
+      uri: direct
+      parameters:
+        name: ask-supplier
+      steps:
+        - doTry:
+            steps:
+              - marshal:
+                  json:
+                    library: Jackson
+              - toD:
+                  uri: 
"{{shop.suppliers.url}}/${variable.supplier}?httpMethod=POST"
+              - unmarshal:
+                  json:
+                    library: Jackson
+              - log:
+                  message: "Supplier ${body[supplier]} quotes ${body[price]} 
(${body[days]}-day delivery)"
+            doCatch:
+              - exception:
+                  - java.lang.Exception
+                steps:
+                  - log:
+                      message: "Supplier ${variable.supplier} failed: 
${exception.message}"
+                  - setBody:
+                      expression:
+                        constant:
+                          expression: ""
diff --git a/route/scatter-gather/suppliers.camel.yaml 
b/route/scatter-gather/suppliers.camel.yaml
new file mode 100644
index 0000000..f06b933
--- /dev/null
+++ b/route/scatter-gather/suppliers.camel.yaml
@@ -0,0 +1,55 @@
+# The three suppliers, as routes of the same app, so the example needs no 
other service.
+# A answers at once, B is cheaper but takes 3 seconds, C is as cheap as A with 
a shorter delivery
+# time, but does not sell hoodies.
+- route:
+    id: suppliers
+    from:
+      uri: platform-http
+      parameters:
+        path: "/supplier/{supplier}"
+        httpMethodRestrict: POST
+      steps:
+        - unmarshal:
+            json:
+              library: Jackson
+        - choice:
+            when:
+              - expression:
+                  simple:
+                    expression: "${header.supplier} == 'A'"
+                steps:
+                  - setBody:
+                      expression:
+                        simple:
+                          expression: '{"supplier": "A", "sku": 
"${body[sku]}", "price": 4.25, "days": 2}'
+              - expression:
+                  simple:
+                    expression: "${header.supplier} == 'B'"
+                steps:
+                  - delay:
+                      expression:
+                        constant:
+                          expression: "3000"
+                  - setBody:
+                      expression:
+                        simple:
+                          expression: '{"supplier": "B", "sku": 
"${body[sku]}", "price": 3.95, "days": 3}'
+              - expression:
+                  simple:
+                    expression: "${header.supplier} == 'C' && ${body[sku]} != 
'CAMEL-HOODIE'"
+                steps:
+                  - setBody:
+                      expression:
+                        simple:
+                          expression: '{"supplier": "C", "sku": 
"${body[sku]}", "price": 4.25, "days": 1}'
+            otherwise:
+              steps:
+                - setHeader:
+                    name: CamelHttpResponseCode
+                    expression:
+                      constant:
+                        expression: "404"
+                - setBody:
+                    expression:
+                      simple:
+                        expression: '{"error": "supplier ${header.supplier} 
does not sell ${body[sku]}"}'
diff --git a/route/scatter-gather/test/scatter-gather.citrus.it.yaml 
b/route/scatter-gather/test/scatter-gather.citrus.it.yaml
new file mode 100644
index 0000000..460a5a2
--- /dev/null
+++ b/route/scatter-gather/test/scatter-gather.citrus.it.yaml
@@ -0,0 +1,45 @@
+name: scatter-gather-test
+description: The scatter-gather example picks the best quote as its README 
shows
+actions:
+  - camel:
+      cli:
+        run:
+          integration:
+            name: "suppliers"
+            file: "../suppliers.camel.yaml"
+  - camel:
+      cli:
+        verify:
+          integration: "suppliers"
+          logMessage: "(suppliers) started"
+  - camel:
+      cli:
+        run:
+          integration:
+            name: "scatter-gather"
+            file: "../scatter-gather.camel.yaml"
+            systemProperties:
+              file: "../application.properties"
+          resources:
+            - "restock/restock-1001.json"
+            - "restock/restock-1002.json"
+  - camel:
+      cli:
+        verify:
+          integration: "scatter-gather"
+          logMessage: "Restock RST-1001: 2 quote(s) in time"
+  - camel:
+      cli:
+        verify:
+          integration: "scatter-gather"
+          logMessage: "Restock RST-1001: best price 4.25 from C (1-day 
delivery)"
+  - camel:
+      cli:
+        verify:
+          integration: "scatter-gather"
+          logMessage: "Supplier C failed: HTTP operation failed invoking 
http://localhost:8080/supplier/C with statusCode: 404"
+  - camel:
+      cli:
+        verify:
+          integration: "scatter-gather"
+          logMessage: "Restock RST-1002: best price 4.25 from A (2-day 
delivery)"

Reply via email to