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 ea215a3da23a CAMEL-25200: camel-jbang - camel overview shows where
each route's message body comes from (#30803)
ea215a3da23a is described below
commit ea215a3da23a78944cb40b8c69d1ea35ce1215b8
Author: Claus Ibsen <[email protected]>
AuthorDate: Thu Nov 26 07:09:53 2026 +0100
CAMEL-25200: camel-jbang - camel overview shows where each route's message
body comes from (#30803)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../modules/ROOT/pages/camel-jbang-ai.adoc | 11 +-
.../jbang/core/commands/ai/IntegrationSummary.java | 58 ++++
.../dsl/jbang/core/commands/ai/ProjectBodies.java | 107 ++++++
.../jbang/core/commands/ai/ProjectOverview.java | 45 ++-
.../core/commands/ai/IntegrationSummaryTest.java | 109 +++++++
.../commands/ai/OverviewValidateParityTest.java | 96 ++++++
.../camel/dsl/yaml/validator/BodyOrigin.java | 59 ++++
.../camel/dsl/yaml/validator/BodyTypeFlow.java | 276 ++++++++++++----
.../camel/dsl/yaml/validator/RouteGraph.java | 66 +++-
.../camel/dsl/yaml/validator/YamlValidator.java | 43 ++-
.../camel/dsl/yaml/validator/BodyOriginTest.java | 360 +++++++++++++++++++++
11 files changed, 1150 insertions(+), 80 deletions(-)
diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-ai.adoc
b/docs/user-manual/modules/ROOT/pages/camel-jbang-ai.adoc
index 869f1828d9ba..e45fb4b4c9fc 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-ai.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-ai.adoc
@@ -167,11 +167,20 @@ a project directory, read from the route sources (no
running integration needed)
(with the file and line) and where it sends failures, the routes with error
handling of their own (such as
a dead letter channel) and where it sends failures, and the routes with
`noErrorHandler`, whose failures go
back to their caller, or to their own consumer when no route calls them;
+* the *message bodies*: where the body of each YAML route comes from. It is
the consumer (with *no body* for a
+ `timer`, `cron` and the like), a REST operation (a `GET`, `DELETE` or `HEAD`
carries no body, also an operation of
+ an OpenAPI contract beside the route), the routes that call it, the failed
message of a dead letter channel or an
+ `onException`, an `onCompletion`, or a saga that compensates or completes.
For a route that starts with no body,
+ the first step that may set one. This is the analysis of the body check of
`camel validate`, made the same way:
+ per file, and only for a file that passes the schema, so a caller in another
file is named but its body is not
+ followed;
* the *external systems* grouped by category (AI, databases, messaging, files,
email, HTTP, cloud), taken
from the component labels of the Camel catalog;
* *findings*: a `direct`, `seda` or `disruptor` endpoint that no route
consumes (by the same rules as
`camel validate`), also when a dead letter channel or an `onException` sends
there, routes that call each
- other in a cycle, duplicate route ids, routes without a description, and
mistakes in the error handling:
+ other in a cycle, duplicate route ids, routes without a description, a step
that reads a body the route can
+ never have (`body-never-set`, such as a `jsonpath` or an `unmarshal` in a
route a timer calls, with the same message
+ as `camel validate`), and mistakes in the error handling:
a route that receives the failures of an error handler and uses that error
handler too (a failure in it
goes back to it), and a route with `noErrorHandler` that no route calls (its
failures go back to its own
consumer, and no error handler acts on them);
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/IntegrationSummary.java
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/IntegrationSummary.java
index 7eb8552647bd..81ff33d3f6ce 100644
---
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/IntegrationSummary.java
+++
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/IntegrationSummary.java
@@ -27,6 +27,7 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
@@ -39,6 +40,7 @@ import
org.apache.camel.dsl.jbang.core.commands.ai.ProjectOverview.Overview;
import org.apache.camel.dsl.jbang.core.commands.ai.ProjectOverview.SystemUse;
import org.apache.camel.dsl.jbang.core.commands.ai.ProjectRoutes.Endpoint;
import org.apache.camel.dsl.jbang.core.commands.ai.ProjectRoutes.Route;
+import org.apache.camel.dsl.yaml.validator.BodyOrigin;
import org.apache.camel.util.SensitiveUtils;
/**
@@ -470,6 +472,8 @@ public final class IntegrationSummary {
sb.append('\n');
}
+ renderBodies(sb, overview);
+
if (!overview.systems().isEmpty()) {
sb.append("## External systems\n\n");
Map<String, Map<String, Set<String>[]>> byCategory = new
TreeMap<>();
@@ -507,6 +511,60 @@ public final class IntegrationSummary {
return sb.toString();
}
+ /**
+ * Where the message body of each YAML route comes from, as camel validate
reads it (CAMEL-25200): per file, so a
+ * route called from another file says so, without following the body
there.
+ */
+ static void renderBodies(StringBuilder sb, Overview overview) {
+ List<Route> routes = overview.flows().stream().filter(r ->
overview.bodies().containsKey(r.key())).toList();
+ if (routes.isEmpty()) {
+ return;
+ }
+ sb.append("## Message bodies\n\n");
+ sb.append("Where the body of each YAML route comes from, read from the
source as camel validate checks it:"
+ + " the routes of each file; a caller in another file is not
followed.\n\n");
+ sb.append("| Route | Body from | First step that sets it
|\n|---|---|---|\n");
+ for (Route r : routes) {
+ BodyOrigin body = overview.bodies().get(r.key());
+ String setBy = !body.noBody() ? "" : body.setBy() != null
+ ? "`" + body.setBy() + "` (step " + body.setAt() + ")" :
"-";
+ sb.append("| `").append(cell(r.key())).append("` | ")
+ .append(cell(bodyFrom(overview, r, body))).append(" | ")
+ .append(setBy).append(" |\n");
+ }
+ sb.append('\n');
+ }
+
+ /** Where the body of a route comes from, in words. */
+ static String bodyFrom(Overview overview, Route route, BodyOrigin body) {
+ String none = body.noBody() ? ": **no body**" : "";
+ String callers = String.join(", ", body.callers().stream().map(c ->
"`" + c + "`").toList());
+ return switch (body.origin()) {
+ case BodyOrigin.CONSUMER -> "consumer " + (route.from() != null ?
"`" + route.from().uri() + "`" : "")
+ + none;
+ case BodyOrigin.REST -> (body.via() != null ? "REST `" +
body.via() + "`" : "an OpenAPI operation") + none;
+ case BodyOrigin.CALLER -> "called by " + callers + " over `" +
body.via() + "`" + none;
+ case BodyOrigin.ERROR_HANDLER -> "the failed message, from "
+ +
("onException".equals(body.via()) ? "an onException" : "a dead letter channel")
+ + (callers.isEmpty() ? "" : " of
" + callers);
+ case BodyOrigin.ON_COMPLETION -> "the completed message, from an
onCompletion"
+ + (callers.isEmpty() ? "" : " of
" + callers);
+ case BodyOrigin.SAGA -> "the saga service, to " +
("completion".equals(body.via()) ? "complete" : "compensate")
+ + (callers.isEmpty() ? "" : " " + callers);
+ default -> {
+ // called over an endpoint of a route in another file: the
overview links them, the body is not followed
+ List<String> elsewhere = overview.links().stream()
+ .filter(l -> l.to().equals(route.key()))
+ .map(l -> overview.route(l.from()))
+ .filter(from -> from != null &&
!Objects.equals(from.file(), route.file()))
+ .map(from -> "`" + from.key() +
"`").distinct().toList();
+ yield elsewhere.isEmpty()
+ ? "not known: no route of this file calls it (a route
of another file, or code, may)"
+ : "called from another file by " + String.join(", ",
elsewhere);
+ }
+ };
+ }
+
/**
* The architecture: the routes grouped by what they do, with the facts of
each group. A group an AI decided is
* marked; a group from the source's route group is not. Utility routes
are listed last, briefly.
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ProjectBodies.java
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ProjectBodies.java
new file mode 100644
index 000000000000..dab6d2d047a6
--- /dev/null
+++
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ProjectBodies.java
@@ -0,0 +1,107 @@
+/*
+ * 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.dsl.jbang.core.commands.ai;
+
+import java.nio.file.Path;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.camel.catalog.CamelCatalog;
+import org.apache.camel.dsl.jbang.core.commands.ai.ProjectRoutes.Route;
+import org.apache.camel.dsl.yaml.validator.BodyOrigin;
+import org.apache.camel.dsl.yaml.validator.ProjectFacts;
+import org.apache.camel.dsl.yaml.validator.YamlValidator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Where the message body of each YAML route of a project comes from, for
{@code camel overview} (CAMEL-25200). It is
+ * the analysis of the body check of {@code camel validate}, made the way
{@code camel validate} makes it: per file,
+ * with the same schema validator, only for a file that passes the schema, and
with the GET operations of an OpenAPI
+ * contract beside the route known to carry no body. So the {@code
body-never-set} findings of the two are the same.
+ */
+final class ProjectBodies {
+
+ private static final Logger LOG =
LoggerFactory.getLogger(ProjectBodies.class);
+
+ private ProjectBodies() {
+ }
+
+ /**
+ * The body origin of each YAML route, by the key of the route in the
overview.
+ *
+ * @param dir the project directory, for the OpenAPI contracts the
routes bind to; may be null
+ * @param sources the content of each route file by its path relative to
the directory
+ * @param routes the routes of the overview
+ */
+ static Map<String, BodyOrigin> analyze(
+ Path dir, Map<String, String> sources, List<Route> routes,
CamelCatalog catalog) {
+ Map<String, BodyOrigin> answer = new LinkedHashMap<>();
+ YamlValidator validator = null;
+ for (Map.Entry<String, String> e : sources.entrySet()) {
+ String file = e.getKey();
+ String name = file.toLowerCase(Locale.ROOT);
+ if (!name.endsWith(".yaml") && !name.endsWith(".yml")) {
+ continue;
+ }
+ List<BodyOrigin> origins;
+ try {
+ if (validator == null) {
+ validator = catalog != null
+ ? SourceValidator.yamlValidator(catalog) :
SourceValidator.yamlValidator();
+ }
+ Set<String> bodyless = dir != null ?
OpenApiVerbs.bodylessEndpoints(e.getValue(), dir) : Set.of();
+ origins = validator.bodyOrigins(e.getValue(), new
ProjectFacts(bodyless, Map.of(), null));
+ } catch (Exception ex) {
+ // the overview is still an overview without the bodies
+ LOG.debug("Cannot analyze the message bodies of {}: {}", file,
ex.getMessage(), ex);
+ continue;
+ }
+ if (!origins.isEmpty()) {
+ match(file, origins, routes, answer);
+ }
+ }
+ return answer;
+ }
+
+ /**
+ * Gives each origin the route of the overview it is about: by its id,
else by its place among the routes of the
+ * file, when the overview has the same routes for the file.
+ */
+ private static void match(String file, List<BodyOrigin> origins,
List<Route> routes, Map<String, BodyOrigin> answer) {
+ List<Route> ofFile = routes.stream()
+ .filter(r -> file.equals(r.file()) && "route".equals(r.kind()))
+ .sorted(Comparator.comparingInt(Route::line))
+ .toList();
+ boolean sameRoutes = ofFile.size() == origins.size();
+ for (BodyOrigin o : origins) {
+ Route route = null;
+ if (o.route() != null && !o.route().isBlank()) {
+ route = ofFile.stream().filter(r ->
o.route().equals(r.id())).findFirst().orElse(null);
+ } else if (sameRoutes) {
+ route = ofFile.get(o.index());
+ }
+ if (route != null) {
+ answer.putIfAbsent(route.key(), o);
+ }
+ }
+ }
+}
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ProjectOverview.java
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ProjectOverview.java
index 61286b446972..3965913c5798 100644
---
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ProjectOverview.java
+++
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ProjectOverview.java
@@ -23,6 +23,7 @@ import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.LinkedHashMap;
@@ -38,6 +39,7 @@ import java.util.function.Supplier;
import org.apache.camel.catalog.CamelCatalog;
import org.apache.camel.dsl.jbang.core.commands.ai.ProjectRoutes.Endpoint;
import org.apache.camel.dsl.jbang.core.commands.ai.ProjectRoutes.Route;
+import org.apache.camel.dsl.yaml.validator.BodyOrigin;
import org.apache.camel.dsl.yaml.validator.EndpointRules;
import org.apache.camel.tooling.model.ComponentModel;
import org.apache.camel.util.json.JsonArray;
@@ -97,10 +99,13 @@ public final class ProjectOverview {
* The overview of a project.
*
* @param files the route files read, relative to the directory
+ * @param bodies where the message body of each YAML route comes
from, by the key of the route, as the body
+ * check of camel validate reads it (CAMEL-25200)
* @param fingerprint a hash of the route files, to tell whether a summary
written earlier is still up to date
*/
public record Overview(Path directory, List<String> files, List<Route>
routes, List<Link> links,
- List<SystemUse> systems, List<EntryPoint> entryPoints,
List<Finding> findings, String fingerprint) {
+ List<SystemUse> systems, List<EntryPoint> entryPoints,
List<Finding> findings,
+ Map<String, BodyOrigin> bodies, String fingerprint) {
/**
* The routes, templates and templated routes; REST operations are
entry points and error handlers are how
@@ -186,11 +191,13 @@ public final class ProjectOverview {
List<Link> links = links(routes, catalog);
List<SystemUse> systems = systems(routes, catalog);
List<EntryPoint> entryPoints = entryPoints(routes, links, catalog);
+ // where the body of each YAML route comes from, as camel validate
reads it (CAMEL-25200)
+ Map<String, BodyOrigin> bodies = ProjectBodies.analyze(dir, sources,
routes, catalog);
List<Finding> findings
- = findings(routes, links, catalog, sources.size() > 0 &&
routes.size() == MAX_ROUTES);
+ = findings(routes, links, bodies, catalog, sources.size() > 0
&& routes.size() == MAX_ROUTES);
return new Overview(
dir, List.copyOf(sources.keySet()), List.copyOf(routes),
links, systems, entryPoints,
- findings, fingerprint(sources));
+ findings, Collections.unmodifiableMap(bodies),
fingerprint(sources));
}
// ---- categories ----
@@ -404,7 +411,9 @@ public final class ProjectOverview {
return EndpointRules.endpoint(e.key()) != null;
}
- private static List<Finding> findings(List<Route> routes, List<Link>
links, CamelCatalog catalog, boolean truncated) {
+ private static List<Finding> findings(
+ List<Route> routes, List<Link> links, Map<String, BodyOrigin>
bodies, CamelCatalog catalog,
+ boolean truncated) {
List<Finding> answer = new ArrayList<>();
Map<String, List<Route>> byId = new LinkedHashMap<>();
Set<String> consumed = new LinkedHashSet<>();
@@ -452,6 +461,12 @@ public final class ProjectOverview {
}
}
}
+ // a step that reads a body the route cannot have, with the message of
camel validate
+ bodies.forEach((key, origin) -> {
+ if (origin.problem() != null) {
+ answer.add(new Finding("warning", "body-never-set",
origin.problem(), key));
+ }
+ });
errorRouteLoops(routes, links, answer);
unhandledFailures(routes, links, catalog, answer);
for (List<String> cycle : cycles(links)) {
@@ -640,6 +655,24 @@ public final class ProjectOverview {
// ---- JSON ----
+ /** Where the body of a route comes from, as the JSON of the overview has
it (CAMEL-25200). */
+ static JsonObject bodyJson(BodyOrigin body) {
+ JsonObject jo = new JsonObject();
+ jo.put("origin", body.origin());
+ if (body.via() != null) {
+ jo.put("via", body.via());
+ }
+ if (!body.callers().isEmpty()) {
+ jo.put("callers", new JsonArray(body.callers()));
+ }
+ jo.put("noBody", body.noBody());
+ if (body.setBy() != null) {
+ jo.put("setBy", body.setBy());
+ jo.put("setAt", body.setAt());
+ }
+ return jo;
+ }
+
/** The overview as the tools answer it, with what an existing summary
file adds. */
public static JsonObject toJson(Overview overview,
IntegrationSummary.Summary summary) {
JsonObject out = new JsonObject();
@@ -660,6 +693,10 @@ public final class ProjectOverview {
if (r.from() != null) {
jo.put("from", r.from().uri());
}
+ BodyOrigin body = overview.bodies().get(r.key());
+ if (body != null) {
+ jo.put("bodyFrom", bodyJson(body));
+ }
JsonArray to = new JsonArray();
r.produces().forEach(e -> to.add(e.uri()));
if (!to.isEmpty()) {
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/IntegrationSummaryTest.java
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/IntegrationSummaryTest.java
index 8fe94874de5d..e8ce87a66da8 100644
---
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/IntegrationSummaryTest.java
+++
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/IntegrationSummaryTest.java
@@ -241,6 +241,115 @@ class IntegrationSummaryTest {
.contains("- no error handler in `payment-provider`: failures
go back to the caller");
}
+ @Test
+ void messageBodiesSayWhereTheBodyOfEachYamlRouteComesFrom() {
+ String orders = """
+ - rest:
+ path: /stock
+ get:
+ - path: /{sku}
+ to: direct:getStock
+ - route:
+ id: get-stock
+ from:
+ uri: direct:getStock
+ steps:
+ - log: "${header.sku}"
+ - setBody:
+ constant: "{}"
+ - route:
+ id: receive-order
+ errorHandler:
+ deadLetterChannel:
+ deadLetterUri: direct:dlq
+ from:
+ uri: platform-http:/orders
+ steps:
+ - to: direct:validate
+ - to: direct:audit
+ - route:
+ id: validate-order
+ from:
+ uri: direct:validate
+ steps:
+ - log: "${body}"
+ - route:
+ id: dlq
+ from:
+ uri: direct:dlq
+ steps:
+ - log: "${body}"
+ """;
+ String report = """
+ - route:
+ id: nightly-report
+ from:
+ uri: timer:nightly
+ steps:
+ - to: direct:buildReport
+ - route:
+ id: build-report
+ from:
+ uri: direct:buildReport
+ steps:
+ - setBody:
+ expression:
+ jsonpath:
+ expression: "$.total"
+ - route:
+ id: audit
+ from:
+ uri: direct:audit
+ steps:
+ - log: "${body}"
+ """;
+ Overview o = ProjectOverview.analyze(
+ Path.of("shop"), Map.of("orders.camel.yaml", orders,
"report.camel.yaml", report),
+ ProjectOverviewTest.CATALOG);
+ String md = IntegrationSummary.render(o, null, null, null,
"2026-11-25");
+
+ String bodies = md.substring(md.indexOf("## Message bodies"),
md.indexOf("## External systems"));
+ assertThat(bodies)
+ .contains("| `get-stock` | REST `GET /stock/{sku}`: **no
body** | `setBody` (step 2) |")
+ .contains("| `receive-order` | consumer
`platform-http:/orders` | |")
+ .contains("| `validate-order` | called by `receive-order` over
`direct:validate` | |")
+ .contains("| `dlq` | the failed message, from a dead letter
channel of `receive-order` | |")
+ // the reply of the route it calls is the first body of the
timer route
+ .contains("| `nightly-report` | consumer `timer:nightly`: **no
body** | `to` (step 1) |")
+ .contains("| `build-report` | called by `nightly-report` over
`direct:buildReport`: **no body**"
+ + " | `setBody` (step 1) |")
+ .contains("| `audit` | called from another file by
`receive-order` | |");
+ assertThat(md.substring(md.indexOf("## Findings")))
+ .contains("- warning: route build-report: jsonpath reads the
message body, and the message reaching"
+ + " this route has none - the routes that call it do
not set one either");
+
+ String json = ProjectOverview.toJson(o, null).toJson();
+
assertThat(json).contains("\"bodyFrom\":{\"origin\":\"caller\",\"via\":\"direct:buildReport\","
+ +
"\"callers\":[\"nightly-report\"],\"noBody\":true,\"setBy\":\"setBody\",\"setAt\":1}")
+ .contains("\"bodyFrom\":{\"origin\":\"rest\",\"via\":\"GET
\\/stock\\/{sku}\",\"noBody\":true,"
+ + "\"setBy\":\"setBody\",\"setAt\":2}")
+
.contains("\"bodyFrom\":{\"origin\":\"errorHandler\",\"via\":\"deadLetterChannel\","
+ +
"\"callers\":[\"receive-order\"],\"noBody\":false}")
+ .contains("\"kind\":\"body-never-set\"");
+ }
+
+ @Test
+ void noMessageBodiesWithoutYamlRoutes() {
+ String java = """
+ import org.apache.camel.builder.RouteBuilder;
+
+ public class Orders extends RouteBuilder {
+ @Override
+ public void configure() {
+ from("timer:tick").routeId("tick").to("direct:lookup");
+ }
+ }
+ """;
+ Overview o = ProjectOverview.analyze(Path.of("shop"),
Map.of("Orders.java", java), ProjectOverviewTest.CATALOG);
+ assertThat(o.bodies()).isEmpty();
+ assertThat(IntegrationSummary.render(o, null, null, null,
"2026-11-25")).doesNotContain("## Message bodies");
+ }
+
@Test
void
errorHandlingNamesWhatNoRouteConsumesAndTheConsumersOfUncalledRoutes() {
// a dead letter queue on a broker, and a route with no error handler
that no route calls (CAMEL-25467)
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/OverviewValidateParityTest.java
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/OverviewValidateParityTest.java
index 61a5312f2efb..60bb51f3cc41 100644
---
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/OverviewValidateParityTest.java
+++
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/OverviewValidateParityTest.java
@@ -155,6 +155,102 @@ class OverviewValidateParityTest {
.noneMatch(m -> VALIDATE.matcher(m).find());
}
+ @Test
+ void overviewAndValidateReportTheSameBodyNeverSet() throws Exception {
+ // a GET of an OpenAPI contract, a timer chain in one file, a call
written with slashes, a call from another
+ // file (not followed by either), and a dead letter route (the failed
message: nothing is said)
+ Files.writeString(dir.resolve("stock-api.json"), """
+ {
+ "openapi": "3.0.2",
+ "paths": {
+ "/stock/{sku}": {
+ "get": { "operationId": "getStock", "responses": {
"200": { "description": "ok" } } }
+ }
+ }
+ }
+ """);
+ Files.writeString(dir.resolve("stock.camel.yaml"), """
+ - rest:
+ openApi:
+ specification: stock-api.json
+ - route:
+ id: getStock
+ from:
+ uri: direct:getStock
+ steps:
+ - setBody:
+ expression:
+ jsonpath:
+ expression: "$.sku"
+ - errorHandler:
+ deadLetterChannel:
+ deadLetterUri: direct:dlq
+ - route:
+ id: dlq
+ from:
+ uri: direct:dlq
+ steps:
+ - setBody:
+ expression:
+ jsonpath:
+ expression: "$.id"
+ """);
+ Files.writeString(dir.resolve("report.camel.yaml"), """
+ - route:
+ id: nightly
+ from:
+ uri: timer:nightly
+ steps:
+ - to: direct://buildReport
+ - to: direct:remote
+ - route:
+ id: buildReport
+ from:
+ uri: direct:buildReport
+ steps:
+ - unmarshal:
+ json: {}
+ """);
+ Files.writeString(dir.resolve("remote.camel.yaml"), """
+ - route:
+ id: remote
+ from:
+ uri: direct:remote
+ steps:
+ - setBody:
+ expression:
+ jsonpath:
+ expression: "$.x"
+ """);
+
+ Set<String> overview = new TreeSet<>();
+ for (Finding f : ProjectOverview.analyze(dir, CATALOG).findings()) {
+ if ("body-never-set".equals(f.kind())) {
+ overview.add(f.message());
+ }
+ }
+ Set<String> validate = new TreeSet<>();
+ try (Stream<Path> files = Files.list(dir)) {
+ for (Path p : files.toList()) {
+ String name = p.getFileName().toString();
+ if (!name.endsWith(".yaml")) {
+ continue;
+ }
+ for (String msg : SourceValidator.validate(name,
Files.readString(p), CATALOG, null, dir)) {
+ if (msg.contains("the message reaching this route has
none")) {
+ // validate prefixes the line and the location of the
route
+ validate.add(msg.substring(msg.indexOf("route ")));
+ }
+ }
+ }
+ }
+
+ assertThat(validate).hasSize(2);
+ assertThat(validate).anyMatch(m -> m.startsWith("route getStock:
jsonpath reads the message body"));
+ assertThat(validate).anyMatch(m -> m.startsWith("route buildReport:
unmarshal works on the message body"));
+ assertThat(overview).isEqualTo(validate);
+ }
+
private static String endpoint(Pattern pattern, String message) {
Matcher m = pattern.matcher(message);
assertThat(m.find()).as(message).isTrue();
diff --git
a/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/main/java/org/apache/camel/dsl/yaml/validator/BodyOrigin.java
b/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/main/java/org/apache/camel/dsl/yaml/validator/BodyOrigin.java
new file mode 100644
index 000000000000..ae64be30b621
--- /dev/null
+++
b/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/main/java/org/apache/camel/dsl/yaml/validator/BodyOrigin.java
@@ -0,0 +1,59 @@
+/*
+ * 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.dsl.yaml.validator;
+
+import java.util.List;
+
+/**
+ * Where the message body of one route of a YAML file comes from, read from
the source: the analysis the body check of
+ * {@code camel validate} makes, which {@code camel overview} shows
(CAMEL-25200). The routes of one file only: a caller
+ * in another file is not followed, and the origin is then {@link #UNKNOWN}.
+ *
+ * @param index the position of the route among the routes of the file, from 0
+ * @param route the id of the route, or null
+ * @param from the endpoint the route starts from
+ * @param origin how a message reaches the route: {@link #CONSUMER}, {@link
#REST}, {@link #CALLER},
+ * {@link #ERROR_HANDLER}, {@link #ON_COMPLETION}, {@link
#SAGA} or {@link #UNKNOWN}
+ * @param via what the origin goes through: the endpoint the callers send
to, the REST operation ({@code GET
+ * /stock/{id}}), or the error path ({@code deadLetterChannel},
{@code onException},
+ * {@code onCompletion}, {@code compensation}, {@code
completion}); null for a consumer
+ * @param callers the routes that send to this one (their id, or the endpoint
they start from without its options), or
+ * the route whose error handler or saga reaches it; empty when
they are not known
+ * @param noBody whether it is certain that no message reaching the route has
a body
+ * @param setBy when there is no body: the first step of the route that may
set one, or null
+ * @param setAt the position of that step in the route, from 1; 0 when there
is none
+ * @param problem the message of the body check, when a step reads the body
that is never set; null otherwise
+ * @since 4.24
+ */
+public record BodyOrigin(int index, String route, String from, String origin,
String via, List<String> callers,
+ boolean noBody, String setBy, int setAt, String problem) {
+
+ /** The route consumes from a component that brings its own message: a
timer, an HTTP server, a queue. */
+ public static final String CONSUMER = "consumer";
+ /** A REST operation of the file, or of an OpenAPI contract the file binds
to, calls the route. */
+ public static final String REST = "rest";
+ /** Other routes of the file call the route, with their message. */
+ public static final String CALLER = "caller";
+ /** An error handler or an onException sends the failed message to the
route. */
+ public static final String ERROR_HANDLER = "errorHandler";
+ /** An onCompletion sends the completed message to the route. */
+ public static final String ON_COMPLETION = "onCompletion";
+ /** A saga calls the route to compensate or complete. */
+ public static final String SAGA = "saga";
+ /** Nothing in the file calls the route: a route of another file may, or
code. */
+ public static final String UNKNOWN = "unknown";
+}
diff --git
a/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/main/java/org/apache/camel/dsl/yaml/validator/BodyTypeFlow.java
b/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/main/java/org/apache/camel/dsl/yaml/validator/BodyTypeFlow.java
index 818069ed571f..4a424a403305 100644
---
a/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/main/java/org/apache/camel/dsl/yaml/validator/BodyTypeFlow.java
+++
b/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/main/java/org/apache/camel/dsl/yaml/validator/BodyTypeFlow.java
@@ -16,10 +16,13 @@
*/
package org.apache.camel.dsl.yaml.validator;
+import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Set;
@@ -27,6 +30,7 @@ import com.networknt.schema.Error;
import com.networknt.schema.path.NodePath;
import tools.jackson.databind.JsonNode;
+import static org.apache.camel.dsl.yaml.validator.RouteGraph.REST_VERBS;
import static org.apache.camel.dsl.yaml.validator.RouteGraph.Route;
import static org.apache.camel.dsl.yaml.validator.RouteGraph.endpointOf;
import static org.apache.camel.dsl.yaml.validator.RouteGraph.from;
@@ -62,100 +66,189 @@ final class BodyTypeFlow {
private BodyTypeFlow() {
}
+ /** The components of the routes a route calls with its own message. */
+ private static final Set<String> ROUTE_CALLS = Set.of("direct", "seda",
"direct-vm");
+
/**
+ * Where the body of each route of the file comes from, with the message
of the check for a route that reads a body
+ * it cannot have: what {@link #report} reports, and what {@code camel
overview} shows (CAMEL-25200).
+ *
* @param known the endpoints the caller knows deliver no body, such
as {@code direct:getStock} for the GET
* operation of an OpenAPI specification the route binds
to (CAMEL-24844 phase B)
* @param bodyTypes the body types of the catalog, which say the consumers
that give no body (timer, cron)
*/
- static void check(JsonNode target, NodePath path, List<Error> errors,
Set<String> known, CatalogBodyTypes bodyTypes) {
+ static List<BodyOrigin> analyze(JsonNode target, Set<String> known,
CatalogBodyTypes bodyTypes) {
List<Route> routes = routes(target);
+ List<BodyOrigin> answer = new ArrayList<>();
if (routes.isEmpty()) {
- return;
+ return answer;
+ }
+ Graph graph = new Graph(target, routes, known, bodyTypes);
+ for (int i = 0; i < routes.size(); i++) {
+ answer.add(graph.origin(i, routes.get(i)));
}
- // the graph: which routes send to the endpoint a route starts from
- Map<String, List<Route>> byFrom = new HashMap<>();
- for (Route r : routes) {
- if (r.fromUri() != null) {
- byFrom.computeIfAbsent(normalize(r.fromUri()), k -> new
ArrayList<>()).add(r);
+ return answer;
+ }
+
+ /** Adds the message of each route that reads a body it cannot have, as
{@link #analyze} found them. */
+ static void report(List<BodyOrigin> origins, NodePath path, List<Error>
errors) {
+ for (BodyOrigin origin : origins) {
+ if (origin.problem() != null) {
+ errors.add(Error.builder()
+ .keyword("type")
+ .instanceLocation(path)
+ .messageKey("type")
+ .format(new MessageFormat("{0}"))
+ .arguments(origin.problem())
+ .build());
}
}
- Map<Route, List<Route>> callers = new HashMap<>();
- for (Route caller : routes) {
- for (String uri : sendsTo(caller.steps())) {
- for (Route target2 : byFrom.getOrDefault(normalize(uri),
List.of())) {
- callers.computeIfAbsent(target2, k -> new
ArrayList<>()).add(caller);
+ }
+
+ /** The routes of a file and the ways a message reaches each of them. */
+ private static final class Graph {
+
+ private final Map<Route, List<Route>> callers = new HashMap<>();
+ private final Map<String, String> rest;
+ private final Set<String> restless;
+ private final Set<String> known;
+ private final Map<String, List<RouteGraph.ErrorPath>> errorPaths = new
HashMap<>();
+ private final CatalogBodyTypes bodyTypes;
+
+ Graph(JsonNode target, List<Route> routes, Set<String> known,
CatalogBodyTypes bodyTypes) {
+ this.bodyTypes = bodyTypes;
+ // the graph: which routes send to the endpoint a route starts from
+ Map<String, List<Route>> byFrom = new HashMap<>();
+ for (Route r : routes) {
+ if (r.fromUri() != null) {
+ byFrom.computeIfAbsent(normalize(r.fromUri()), k -> new
ArrayList<>()).add(r);
}
}
+ for (Route caller : routes) {
+ for (String uri : sendsTo(caller.steps())) {
+ for (Route target2 : byFrom.getOrDefault(normalize(uri),
List.of())) {
+ callers.computeIfAbsent(target2, k -> new
ArrayList<>()).add(caller);
+ }
+ }
+ }
+ this.rest = restOperations(target);
+ this.restless = new HashSet<>(restEndpointsWithoutABody(target));
+ this.known = new HashSet<>();
+ for (String uri : known) {
+ this.restless.add(normalize(uri));
+ this.known.add(normalize(uri));
+ }
+ for (RouteGraph.ErrorPath p : RouteGraph.errorPaths(target)) {
+ errorPaths.computeIfAbsent(p.endpoint(), k -> new
ArrayList<>()).add(p);
+ }
}
- Set<String> restless = new
HashSet<>(restEndpointsWithoutABody(target));
- for (String uri : known) {
- restless.add(normalize(uri));
- }
- for (Route r : routes) {
+
+ BodyOrigin origin(int index, Route r) {
+ boolean noBody = certainlyWithoutABody(r, new HashSet<>());
String reader = firstBodyReaderBeforeAnyProducer(r.steps(),
bodyTypes);
- if (reader == null) {
- continue;
+ String problem = reader != null && noBody ? problem(r, reader) :
null;
+ String setBy = null;
+ int setAt = 0;
+ if (noBody && r.steps() != null && r.steps().isArray()) {
+ for (int i = 0; i < r.steps().size(); i++) {
+ if (producesTheBody(r.steps().get(i), bodyTypes)) {
+ setBy = firstName(r.steps().get(i));
+ setAt = i + 1;
+ break;
+ }
+ }
}
- if (!certainlyWithoutABody(r, callers, restless, new HashSet<>(),
bodyTypes)) {
- continue;
+ String key = normalize(r.fromUri());
+ String origin;
+ String via = null;
+ List<String> who = List.of();
+ String scheme = scheme(r.fromUri());
+ if (scheme == null) {
+ // a from without an endpoint: nothing to say where the body
comes from
+ origin = BodyOrigin.UNKNOWN;
+ } else if (!ROUTE_CALLS.contains(scheme)) {
+ origin = BodyOrigin.CONSUMER;
+ } else if (callers.containsKey(r)) {
+ origin = BodyOrigin.CALLER;
+ via = key;
+ // a caller without an id by its endpoint, without the
options, which may carry credentials
+ who = callers.get(r).stream().map(c -> c.id() != null ? c.id()
: normalize(c.fromUri())).distinct()
+ .toList();
+ } else if (rest.containsKey(key) || known.contains(key)) {
+ origin = BodyOrigin.REST;
+ via = rest.get(key);
+ } else if (errorPaths.containsKey(key)) {
+ List<RouteGraph.ErrorPath> paths = errorPaths.get(key);
+ via = paths.get(0).kind();
+ origin = switch (via) {
+ case "onCompletion" -> BodyOrigin.ON_COMPLETION;
+ case "compensation", "completion" -> BodyOrigin.SAGA;
+ default -> BodyOrigin.ERROR_HANDLER;
+ };
+ String kind = via;
+ who = paths.stream().filter(p -> kind.equals(p.kind()) &&
p.route() != null)
+ .map(RouteGraph.ErrorPath::route).distinct().toList();
+ } else {
+ origin = BodyOrigin.UNKNOWN;
}
- errors.add(Error.builder()
- .keyword("type")
- .instanceLocation(path)
- .messageKey("type")
- .format(new java.text.MessageFormat("{0}"))
- .arguments((r.id() != null ? "route " + r.id() + ": " :
"") + reader
- + (READS_THE_BODY.contains(reader) ? " reads
the message body" : " works on the message body")
- + ", and the message reaching this route has
none"
- + (callers.containsKey(r) ? " - the routes that
call it do not set one either" : "")
- + ": read the data first with setBody and
constant: resource:file:... for a known"
- + " file, or poll: for one that is not")
- .build());
+ return new BodyOrigin(index, r.id(), r.fromUri(), origin, via,
who, noBody, setBy, setAt, problem);
}
- }
- /**
- * Whether it is certain that no message reaching this route can have a
body: every way in starts at a consumer or a
- * REST verb that produces none, and nothing on the way sets one. Anything
unknown answers false, which keeps the
- * check quiet.
- */
- private static boolean certainlyWithoutABody(
- Route route, Map<Route, List<Route>> callers, Set<String> restless,
- Set<Route> seen, CatalogBodyTypes bodyTypes) {
- if (!seen.add(route)) {
- return false; // a cycle: say nothing
- }
- String scheme = scheme(route.fromUri());
- if (scheme == null) {
- return false;
- }
- // with variableReceive the message goes into the variable, and the
route starts with no body
- if (bodyTypes.startsWithNoBody(from(route.node()))) {
- return true;
- }
- // a consumer that produces no body of its own, as the catalog says:
timer, cron, scheduler, quartz
- CatalogBodyTypes.Answer out = bodyTypes.consumerOut(route.fromUri(),
from(route.node()));
- if (out != null && out.none()) {
- return true;
- }
- if (!"direct".equals(scheme) && !"seda".equals(scheme) &&
!"direct-vm".equals(scheme)) {
- return false; // a consumer of its own: it brings whatever it
brings
- }
- boolean fromRestWithoutBody =
restless.contains(normalize(route.fromUri()));
- List<Route> from = callers.get(route);
- if (from == null || from.isEmpty()) {
- // nothing in the file calls it: only a REST verb that carries no
body makes this certain
- return fromRestWithoutBody;
+ private String problem(Route r, String reader) {
+ return (r.id() != null ? "route " + r.id() + ": " : "") + reader
+ + (READS_THE_BODY.contains(reader) ? " reads the message
body" : " works on the message body")
+ + ", and the message reaching this route has none"
+ + (callers.containsKey(r) ? " - the routes that call it do
not set one either" : "")
+ + ": read the data first with setBody and constant:
resource:file:... for a known"
+ + " file, or poll: for one that is not";
}
- for (Route caller : from) {
- if (setsTheBodyBeforeSendingTo(caller, route, bodyTypes)) {
+
+ /**
+ * Whether it is certain that no message reaching this route can have
a body: every way in starts at a consumer
+ * or a REST verb that produces none, and nothing on the way sets one.
Anything unknown answers false, which
+ * keeps the check quiet.
+ */
+ private boolean certainlyWithoutABody(Route route, Set<Route> seen) {
+ if (!seen.add(route)) {
+ return false; // a cycle: say nothing
+ }
+ String scheme = scheme(route.fromUri());
+ if (scheme == null) {
return false;
}
- if (!certainlyWithoutABody(caller, callers, restless, seen,
bodyTypes)) {
+ // with variableReceive the message goes into the variable, and
the route starts with no body
+ if (bodyTypes.startsWithNoBody(from(route.node()))) {
+ return true;
+ }
+ // a consumer that produces no body of its own, as the catalog
says: timer, cron, scheduler, quartz
+ CatalogBodyTypes.Answer out =
bodyTypes.consumerOut(route.fromUri(), from(route.node()));
+ if (out != null && out.none()) {
+ return true;
+ }
+ if (!ROUTE_CALLS.contains(scheme)) {
+ return false; // a consumer of its own: it brings whatever it
brings
+ }
+ String key = normalize(route.fromUri());
+ if (errorPaths.containsKey(key)) {
+ // the failed or completed message, which has the body of
wherever the route was: not known here
return false;
}
+ boolean fromRestWithoutBody = restless.contains(key);
+ List<Route> from = callers.get(route);
+ if (from == null || from.isEmpty()) {
+ // nothing in the file calls it: only a REST verb that carries
no body makes this certain
+ return fromRestWithoutBody;
+ }
+ for (Route caller : from) {
+ if (setsTheBodyBeforeSendingTo(caller, route, bodyTypes)) {
+ return false;
+ }
+ if (!certainlyWithoutABody(caller, seen)) {
+ return false;
+ }
+ }
+ return true;
}
- return true;
}
/**
@@ -309,6 +402,49 @@ final class BodyTypeFlow {
return null;
}
+ /** The REST operations of the file by the endpoint they send to: GET
/stock/{id} for direct:getStock. */
+ private static Map<String, String> restOperations(JsonNode target) {
+ Map<String, String> answer = new LinkedHashMap<>();
+ if (target == null || !target.isArray()) {
+ return answer;
+ }
+ for (JsonNode entry : target) {
+ JsonNode rest = entry.isObject() ? entry.get("rest") : null;
+ if (rest == null || !rest.isObject()) {
+ continue;
+ }
+ String base = rest.has("path") ? rest.get("path").asString("") :
"";
+ for (var it = rest.propertyNames().iterator(); it.hasNext();) {
+ String verb = it.next();
+ if (!REST_VERBS.contains(verb)) {
+ continue;
+ }
+ JsonNode value = rest.get(verb);
+ for (JsonNode operation : value.isArray() ? value :
List.of(value)) {
+ String uri = operation.isObject() ?
endpointOf(operation.get("to")) : null;
+ if (uri != null) {
+ String path = operation.has("path") ?
operation.get("path").asString("") : "";
+ answer.putIfAbsent(normalize(uri),
verb.toUpperCase(Locale.ROOT) + " " + joinPath(base, path));
+ }
+ }
+ }
+ }
+ return answer;
+ }
+
+ private static String joinPath(String base, String path) {
+ if (base.isEmpty()) {
+ return path.isEmpty() ? "/" : path;
+ }
+ if (path.isEmpty()) {
+ return base;
+ }
+ if (base.endsWith("/") && path.startsWith("/")) {
+ return base + path.substring(1);
+ }
+ return base.endsWith("/") || path.startsWith("/") ? base + path : base
+ "/" + path;
+ }
+
/** The endpoints a REST verb without a body sends to, such as a get: that
routes to direct:getStock. */
private static Set<String> restEndpointsWithoutABody(JsonNode target) {
Set<String> answer = new HashSet<>();
diff --git
a/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/main/java/org/apache/camel/dsl/yaml/validator/RouteGraph.java
b/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/main/java/org/apache/camel/dsl/yaml/validator/RouteGraph.java
index d2c59080d924..053a93199a5b 100644
---
a/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/main/java/org/apache/camel/dsl/yaml/validator/RouteGraph.java
+++
b/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/main/java/org/apache/camel/dsl/yaml/validator/RouteGraph.java
@@ -18,6 +18,7 @@ package org.apache.camel.dsl.yaml.validator;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -157,8 +158,71 @@ final class RouteGraph {
}
}
+ /**
+ * An endpoint a message reaches by an error path or a saga, not by a step
of a route: the dead letter channel of an
+ * error handler, the steps of an onException or an onCompletion, the
compensation and completion of a saga.
+ *
+ * @param endpoint the endpoint, normalized
+ * @param kind deadLetterChannel, onException, onCompletion,
compensation or completion
+ * @param route the id of the route it belongs to; null for one of the
file (a top-level error handler, a route
+ * configuration) or of a route without an id
+ */
+ record ErrorPath(String endpoint, String kind, String route) {
+ }
+
+ /** The entries whose steps send the message of an error path, and the
kind they are. */
+ private static final Set<String> ERROR_STEPS = Set.of("onException",
"onCompletion");
+
+ /** The error paths of the file, wherever they are: a top-level entry, a
route configuration, a route. */
+ static List<ErrorPath> errorPaths(JsonNode target) {
+ List<ErrorPath> answer = new ArrayList<>();
+ walkErrorPaths(target, null, answer);
+ // the onException entries of a route configuration are a list of
onException: the same path is met twice
+ return List.copyOf(new LinkedHashSet<>(answer));
+ }
+
+ private static void walkErrorPaths(JsonNode node, String route,
List<ErrorPath> answer) {
+ if (node == null) {
+ return;
+ }
+ if (node.isArray()) {
+ for (JsonNode child : node) {
+ walkErrorPaths(child, route, answer);
+ }
+ return;
+ }
+ if (!node.isObject()) {
+ return;
+ }
+ for (var it = node.propertyNames().iterator(); it.hasNext();) {
+ String name = it.next();
+ JsonNode value = node.get(name);
+ if ("route".equals(name) && value.isObject()) {
+ walkErrorPaths(value, value.has("id") ?
value.get("id").asString("") : null, answer);
+ } else if ("deadLetterUri".equals(name) && value.isValueNode()) {
+ answer.add(new ErrorPath(normalize(value.asString("")),
"deadLetterChannel", route));
+ } else if (ERROR_STEPS.contains(name)) {
+ for (String uri : sendsTo(value)) {
+ answer.add(new ErrorPath(normalize(uri), name, route));
+ }
+ // an error handler inside it has a dead letter channel of its
own
+ walkErrorPaths(value, route, answer);
+ } else if ("saga".equals(name) && value.isObject()) {
+ for (String kind : new String[] { "compensation", "completion"
}) {
+ String uri = endpointOf(value.get(kind));
+ if (uri != null) {
+ answer.add(new ErrorPath(normalize(uri), kind, route));
+ }
+ }
+ walkErrorPaths(value, route, answer);
+ } else {
+ walkErrorPaths(value, route, answer);
+ }
+ }
+ }
+
/** The verbs of the REST DSL, each a list of operations under rest:. */
- private static final List<String> REST_VERBS = List.of("get", "post",
"put", "delete", "patch", "head");
+ static final List<String> REST_VERBS = List.of("get", "post", "put",
"delete", "patch", "head");
/** A path parameter of a REST path: id in /orders/{id}. */
private static final Pattern PATH_PARAMETER =
Pattern.compile("\\{([A-Za-z_][\\w.-]*)}");
diff --git
a/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/main/java/org/apache/camel/dsl/yaml/validator/YamlValidator.java
b/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/main/java/org/apache/camel/dsl/yaml/validator/YamlValidator.java
index 65a91d5833bd..3562edf65a61 100644
---
a/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/main/java/org/apache/camel/dsl/yaml/validator/YamlValidator.java
+++
b/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/main/java/org/apache/camel/dsl/yaml/validator/YamlValidator.java
@@ -209,6 +209,32 @@ public class YamlValidator {
return validate(content, ProjectFacts.NONE, true);
}
+ /**
+ * Where the message body of each route of a YAML file comes from: the
analysis the body check of
+ * {@link #validate(String, ProjectFacts)} makes, so {@code camel
overview} and {@code camel validate} give the same
+ * answer (CAMEL-25200). The routes of the file only, in their order.
Empty when the YAML does not pass the schema,
+ * as the routes are then not checked either.
+ *
+ * @param facts what the caller read from the files beside the route; the
body analysis uses the endpoints of the
+ * OpenAPI operations that carry no body
+ */
+ public List<BodyOrigin> bodyOrigins(String content, ProjectFacts facts)
throws Exception {
+ if (schema == null) {
+ init();
+ }
+ if (content == null || content.isBlank() || extraDocument(content) !=
null || jbangDirective(content) != null) {
+ return List.of();
+ }
+ List<BodyOrigin> answer = new ArrayList<>();
+ try {
+ validate(mapper.readTree(content), facts != null ? facts :
ProjectFacts.NONE, true, content, answer);
+ } catch (Exception e) {
+ // YAML the routes cannot be read from: nothing to say of them
+ return List.of();
+ }
+ return answer;
+ }
+
private List<Error> validate(String content, ProjectFacts facts, boolean
routesOnly) throws Exception {
if (schema == null) {
init();
@@ -232,7 +258,8 @@ public class YamlValidator {
}
try {
var target = mapper.readTree(content);
- List<Error> errors = validate(target, facts != null ? facts :
ProjectFacts.NONE, routesOnly, content);
+ List<Error> errors
+ = validate(target, facts != null ? facts :
ProjectFacts.NONE, routesOnly, content, null);
if (routesOnly) {
return errors;
}
@@ -1297,7 +1324,12 @@ public class YamlValidator {
return kind != null && kind.isString() &&
"Kamelet".equals(kind.asString());
}
- private List<Error> validate(JsonNode target, ProjectFacts facts, boolean
routesOnly, String content) {
+ /**
+ * @param origins where the body analysis of the routes goes
(CAMEL-25200), or null; it is only made when the YAML
+ * passes the schema, as the checks of the routes
+ */
+ private List<Error> validate(
+ JsonNode target, ProjectFacts facts, boolean routesOnly, String
content, List<BodyOrigin> origins) {
Schema against = isKamelet(target) ? kameletSchema : schema;
// A branch only matches after scalar conversion if it has no other
errors, including missing required fields.
var errors = filterOneOfNoise(new
ArrayList<>(against.validate(target)));
@@ -1371,8 +1403,11 @@ public class YamlValidator {
checkJsonPathText(camelOnly, new NodePath(PathType.JSON_POINTER),
errors);
checkLiteralPathParameters(camelOnly, new
NodePath(PathType.JSON_POINTER), errors, facts);
// where the body comes from, across the routes of the file
(CAMEL-24844)
- BodyTypeFlow.check(camelOnly, new NodePath(PathType.JSON_POINTER),
errors, facts.bodylessEndpoints(),
- bodyTypes());
+ List<BodyOrigin> flow = BodyTypeFlow.analyze(camelOnly,
facts.bodylessEndpoints(), bodyTypes());
+ if (origins != null) {
+ origins.addAll(flow);
+ }
+ BodyTypeFlow.report(flow, new NodePath(PathType.JSON_POINTER),
errors);
// a field read on a body that is still text (CAMEL-24844)
TextBodyFlow.check(camelOnly, new NodePath(PathType.JSON_POINTER),
errors, facts, bodyTypes());
}
diff --git
a/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/test/java/org/apache/camel/dsl/yaml/validator/BodyOriginTest.java
b/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/test/java/org/apache/camel/dsl/yaml/validator/BodyOriginTest.java
new file mode 100644
index 000000000000..953db00d9695
--- /dev/null
+++
b/dsl/camel-yaml-dsl/camel-yaml-dsl-validator/src/test/java/org/apache/camel/dsl/yaml/validator/BodyOriginTest.java
@@ -0,0 +1,360 @@
+/*
+ * 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.dsl.yaml.validator;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+import com.networknt.schema.Error;
+import org.apache.camel.catalog.DefaultCamelCatalog;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import tools.jackson.databind.JsonNode;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Where the body of each route comes from, as {@code camel overview} shows it
(CAMEL-25200), and that its findings are
+ * the ones of the body check of {@code camel validate}.
+ */
+public class BodyOriginTest {
+
+ private static YamlValidator validator;
+
+ @BeforeAll
+ public static void setup() throws Exception {
+ validator = new YamlValidator();
+ validator.init();
+ }
+
+ @Test
+ public void testConsumersCallersAndRest() throws Exception {
+ String yaml = """
+ - rest:
+ path: /stock
+ get:
+ - path: /{sku}
+ to: direct:getStock
+ post:
+ - to: direct:addStock
+ - route:
+ id: getStock
+ from:
+ uri: direct:getStock
+ steps:
+ - log: "${header.sku}"
+ - setBody:
+ constant: "{}"
+ - route:
+ id: addStock
+ from:
+ uri: direct:addStock
+ steps:
+ - log: "${body}"
+ - route:
+ id: nightly
+ from:
+ uri: timer:nightly
+ steps:
+ - to: direct:buildReport
+ - route:
+ id: buildReport
+ from:
+ uri: direct:buildReport
+ steps:
+ - setBody:
+ expression:
+ jsonpath:
+ expression: "$.total"
+ - route:
+ id: receive
+ from:
+ uri: platform-http:/orders
+ steps:
+ - to: direct://lookup
+ - route:
+ id: lookup
+ from:
+ uri: direct:lookup
+ steps:
+ - log: "${body}"
+ - route:
+ id: helper
+ from:
+ uri: direct:helper
+ steps:
+ - log: "${body}"
+ """;
+ Map<String, BodyOrigin> byRoute = byRoute(validator.bodyOrigins(yaml,
ProjectFacts.NONE));
+
+ BodyOrigin getStock = byRoute.get("getStock");
+ assertThat(getStock.origin()).isEqualTo(BodyOrigin.REST);
+ assertThat(getStock.via()).isEqualTo("GET /stock/{sku}");
+ assertThat(getStock.noBody()).isTrue();
+ assertThat(getStock.setBy()).isEqualTo("setBody");
+ assertThat(getStock.setAt()).isEqualTo(2);
+ assertThat(getStock.problem()).isNull();
+
+ BodyOrigin addStock = byRoute.get("addStock");
+ assertThat(addStock.origin()).isEqualTo(BodyOrigin.REST);
+ assertThat(addStock.via()).isEqualTo("POST /stock");
+ assertThat(addStock.noBody()).isFalse();
+
+ BodyOrigin nightly = byRoute.get("nightly");
+ assertThat(nightly.origin()).isEqualTo(BodyOrigin.CONSUMER);
+ assertThat(nightly.noBody()).isTrue();
+ assertThat(nightly.index()).isEqualTo(2);
+
+ BodyOrigin report = byRoute.get("buildReport");
+ assertThat(report.origin()).isEqualTo(BodyOrigin.CALLER);
+ assertThat(report.via()).isEqualTo("direct:buildReport");
+ assertThat(report.callers()).containsExactly("nightly");
+ assertThat(report.noBody()).isTrue();
+ assertThat(report.problem()).contains("route buildReport: jsonpath
reads the message body");
+
+
assertThat(byRoute.get("receive").origin()).isEqualTo(BodyOrigin.CONSUMER);
+ assertThat(byRoute.get("receive").noBody()).isFalse();
+ BodyOrigin lookup = byRoute.get("lookup");
+ assertThat(lookup.origin()).isEqualTo(BodyOrigin.CALLER);
+ assertThat(lookup.callers()).containsExactly("receive");
+ assertThat(lookup.noBody()).isFalse();
+
+
assertThat(byRoute.get("helper").origin()).isEqualTo(BodyOrigin.UNKNOWN);
+ assertThat(byRoute.get("helper").noBody()).isFalse();
+ }
+
+ @Test
+ public void testRestPathWithATrailingSlash() throws Exception {
+ String yaml = """
+ - rest:
+ path: /stock/
+ get:
+ - path: /{sku}
+ to: direct:getStock
+ - route:
+ id: getStock
+ from:
+ uri: direct:getStock
+ steps:
+ - setBody:
+ constant: "{}"
+ """;
+ Map<String, BodyOrigin> byRoute = byRoute(validator.bodyOrigins(yaml,
ProjectFacts.NONE));
+ assertThat(byRoute.get("getStock").via()).isEqualTo("GET
/stock/{sku}");
+ }
+
+ @Test
+ public void testFromWithoutAnEndpoint() {
+ // the schema rejects it, so only a caller of the analysis itself can
hand one over: no NullPointerException
+ String yaml = """
+ - route:
+ id: nowhere
+ from:
+ steps:
+ - log: "${body}"
+ """;
+ JsonNode target = YamlTrees.newMapper().readTree(yaml);
+ List<BodyOrigin> origins
+ = BodyTypeFlow.analyze(target, Set.of(), new
CatalogBodyTypes(new DefaultCamelCatalog(), null));
+ assertThat(origins).singleElement().satisfies(o -> {
+ assertThat(o.origin()).isEqualTo(BodyOrigin.UNKNOWN);
+ assertThat(o.noBody()).isFalse();
+ });
+ }
+
+ @Test
+ public void testAnOpenApiOperationWithoutABody() throws Exception {
+ String yaml = """
+ - route:
+ id: getStock
+ from:
+ uri: direct:getStock
+ steps:
+ - log: "${header.sku}"
+ """;
+ BodyOrigin origin = validator.bodyOrigins(yaml, new
ProjectFacts(Set.of("direct:getStock"), Map.of(), null))
+ .get(0);
+ assertThat(origin.origin()).isEqualTo(BodyOrigin.REST);
+ assertThat(origin.via()).isNull();
+ assertThat(origin.noBody()).isTrue();
+ }
+
+ @Test
+ public void testErrorPathsAndSagas() throws Exception {
+ String yaml = """
+ - errorHandler:
+ deadLetterChannel:
+ deadLetterUri: direct://dlq
+ - onException:
+ exception:
+ - java.io.IOException
+ steps:
+ - to: direct:failed
+ - onCompletion:
+ steps:
+ - to: direct:done
+ - route:
+ id: order
+ errorHandler:
+ deadLetterChannel:
+ deadLetterUri: direct:orderDlq
+ from:
+ uri: timer:order
+ steps:
+ - saga:
+ compensation: direct:cancel
+ completion: direct:confirm
+ steps:
+ - setBody:
+ constant: order
+ - route:
+ id: dlq
+ from:
+ uri: direct:dlq
+ steps:
+ - setBody:
+ expression:
+ jsonpath:
+ expression: "$.id"
+ - route:
+ id: orderDlq
+ from:
+ uri: direct:orderDlq
+ steps:
+ - log: "${body}"
+ - route:
+ id: failed
+ from:
+ uri: direct:failed
+ steps:
+ - log: "${body}"
+ - route:
+ id: done
+ from:
+ uri: direct:done
+ steps:
+ - log: "${body}"
+ - route:
+ id: cancel
+ from:
+ uri: direct:cancel
+ steps:
+ - log: "${header.Long-Running-Action}"
+ - route:
+ id: confirm
+ from:
+ uri: direct:confirm
+ steps:
+ - log: "${header.Long-Running-Action}"
+ """;
+ Map<String, BodyOrigin> byRoute = byRoute(validator.bodyOrigins(yaml,
ProjectFacts.NONE));
+
+ // the failed message: its body is the one of wherever the route was,
so nothing is said of it
+ BodyOrigin dlq = byRoute.get("dlq");
+ assertThat(dlq.origin()).isEqualTo(BodyOrigin.ERROR_HANDLER);
+ assertThat(dlq.via()).isEqualTo("deadLetterChannel");
+ assertThat(dlq.callers()).isEmpty();
+ assertThat(dlq.noBody()).isFalse();
+ assertThat(dlq.problem()).isNull();
+
+ BodyOrigin orderDlq = byRoute.get("orderDlq");
+ assertThat(orderDlq.origin()).isEqualTo(BodyOrigin.ERROR_HANDLER);
+ assertThat(orderDlq.callers()).containsExactly("order");
+
+
assertThat(byRoute.get("failed").origin()).isEqualTo(BodyOrigin.ERROR_HANDLER);
+ assertThat(byRoute.get("failed").via()).isEqualTo("onException");
+
assertThat(byRoute.get("done").origin()).isEqualTo(BodyOrigin.ON_COMPLETION);
+
+ BodyOrigin cancel = byRoute.get("cancel");
+ assertThat(cancel.origin()).isEqualTo(BodyOrigin.SAGA);
+ assertThat(cancel.via()).isEqualTo("compensation");
+ assertThat(cancel.callers()).containsExactly("order");
+ assertThat(byRoute.get("confirm").via()).isEqualTo("completion");
+
+ // and camel validate says nothing of the dead letter route either
+ assertThat(validator.validate(yaml).stream().map(Error::getMessage))
+ .noneMatch(m -> m.contains("reads the message body"));
+ }
+
+ @Test
+ public void testTheFindingsAreTheOnesOfValidate() throws Exception {
+ String yaml = """
+ - route:
+ id: tick
+ from:
+ uri: timer:tick
+ steps:
+ - to: direct:lookup
+ - route:
+ id: tock
+ from:
+ uri: timer:tock
+ steps:
+ - to: direct:convert
+ - route:
+ id: lookup
+ from:
+ uri: direct:lookup
+ steps:
+ - setBody:
+ expression:
+ jsonpath:
+ expression: "$.sku"
+ - route:
+ id: convert
+ from:
+ uri: direct:convert
+ steps:
+ - unmarshal:
+ json: {}
+ """;
+ List<String> problems = validator.bodyOrigins(yaml,
ProjectFacts.NONE).stream()
+ .map(BodyOrigin::problem).filter(Objects::nonNull).toList();
+ List<String> validate =
validator.validate(yaml).stream().map(Error::getMessage)
+ .filter(m -> m.contains("the message reaching this route has
none")).toList();
+ assertThat(problems).hasSize(2);
+ assertThat(validate).hasSize(2);
+ for (int i = 0; i < problems.size(); i++) {
+ assertThat(validate.get(i)).endsWith(problems.get(i));
+ }
+ }
+
+ @Test
+ public void testNothingWhenTheSchemaFails() throws Exception {
+ // the routes of YAML that does not pass the schema are not checked by
camel validate: no origins either
+ String yaml = """
+ - route:
+ id: tick
+ from:
+ uri: timer:tick
+ steps:
+ - noSuchStep: {}
+ """;
+ assertThat(validator.bodyOrigins(yaml, ProjectFacts.NONE)).isEmpty();
+ assertThat(validator.bodyOrigins("", ProjectFacts.NONE)).isEmpty();
+ assertThat(validator.bodyOrigins("- route: [",
ProjectFacts.NONE)).isEmpty();
+ }
+
+ private static Map<String, BodyOrigin> byRoute(List<BodyOrigin> origins) {
+ Map<String, BodyOrigin> answer = new LinkedHashMap<>();
+ origins.forEach(o -> answer.put(o.route(), o));
+ return answer;
+ }
+}