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

davsclaus pushed a commit to branch CAMEL-27397-wsdl-samples
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 67ea7a6e9bc07d6c5c7c47caa2ccd1f9b411d360
Author: Claus Ibsen <[email protected]>
AuthorDate: Sun Nov 22 20:34:20 2026 +0100

    CAMEL-27397: camel-jbang - camel generate wsdl --samples: a sample request 
and response per operation
    
    With --samples, camel generate wsdl writes for each operation (or those of
    --operation) a sample request, response and faults, as XML and as JSON in
    the xsdJson form (XsdJsonSamples of camel-xsd-json), and the request in a
    SOAP envelope of the SOAP version of the port with a curl command that
    posts it to the address of the WSDL. They are printed, written as files
    with --output=<dir>, or put into the listing with --json.
    
    The XML schema of a remote WSDL is read with the rules of a wsdl:import:
    the host of the WSDL only, and a redirect only to the same scheme, host and
    port. A SOAP action or address that is not a plain URI is not put into the
    curl command, and only NCNames go into file names.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    Signed-off-by: Claus Ibsen <[email protected]>
---
 .../modules/ROOT/pages/camel-jbang-projects.adoc   |  23 ++
 .../jbang-commands/camel-jbang-generate-wsdl.adoc  |   3 +-
 .../camel-jbang-plugin-generate/pom.xml            |   5 +
 .../camel-jbang-plugin-commands-metadata.json      |   2 +-
 .../core/commands/generate/CodeWsdlGenerator.java  | 179 +++++++++++++++-
 .../jbang/core/commands/generate/WsdlModel.java    |  27 +++
 .../jbang/core/commands/generate/WsdlSamples.java  | 231 +++++++++++++++++++++
 .../commands/generate/CodeWsdlGeneratorTest.java   | 165 +++++++++++++++
 8 files changed, 628 insertions(+), 7 deletions(-)

diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-projects.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-jbang-projects.adoc
index 72f67372a0e5..902de1d960e1 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-projects.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-projects.adoc
@@ -682,6 +682,29 @@ default port. See 
xref:next@components:others:cxf-platform-http.adoc[CXF Platfor
 the body and returns the response element. It removes the `Camel*` headers and 
the CXF operation headers first, so a
 caller cannot choose another operation or address (such as with 
`CamelDestinationOverrideUrl`).
 
+`--samples` writes a sample request, response and faults of each operation (or 
those of `--operation`), to call a
+SOAP service from a route, or to test a SOAP service that a route serves:
+
+[source,bash]
+----
+camel generate wsdl orders.wsdl --samples --operation=getOrder
+camel generate wsdl orders.wsdl --samples --output=samples
+----
+
+Each message is written as XML, and as JSON in the form that the
+xref:next@components:dataformats:xsdJson-dataformat.adoc[XSD JSON] data format 
reads and writes. The request is also
+written in a SOAP envelope of the SOAP version of the port, with a `curl` 
command that posts it to the address of the
+WSDL, with the SOAP action in the `SOAPAction` header (SOAP 1.1) or the 
content type (SOAP 1.2). Every element and
+attribute has a value of its type: the first value of an enumeration, a date 
for `xs:date`, `1` for `xs:int`, and so on.
+A repeating element has one item, and of an `xs:choice` only the first member 
is filled in. A value does not follow the
+other facets of its type, such as a pattern or a length.
+
+Without `--output` the samples are printed. With `--output=<dir>` they are 
written as files, such as
+`getOrder-request.xml`, `getOrder-request.json`, `getOrder-request.soap.xml`, 
`getOrder-response.json` and
+`getOrder-fault-orderNotFound.xml`, and the `curl` commands, which post the 
`.soap.xml` files, are printed. With
+`--json` the samples are in the listing, per operation. The XML schema is the 
`xs:schema` in the `wsdl:types` of the
+WSDL and what it imports; of a remote WSDL, it is read with the same rules as 
an import of the WSDL (see below).
+
 When the WSDL has more than one port, choose one with `--service` and 
`--port`. A local WSDL may only import files, and
 a remote one only documents on its own host, over http or https (not from 
https down to http). A redirect is only
 followed to the same scheme, host and port; for another one the command names 
the new location, so you can use it if
diff --git 
a/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-generate-wsdl.adoc
 
b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-generate-wsdl.adoc
index 47d7b3da591a..dc28da03ec56 100644
--- 
a/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-generate-wsdl.adoc
+++ 
b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-generate-wsdl.adoc
@@ -23,9 +23,10 @@ camel generate wsdl [options]
 | Option | Description | Default | Type
 | `--json` | Output the services, ports and operations in JSON Format, with 
the cxf endpoint options of each port |  | boolean
 | `--operation` | The operations to list or scaffold (use commas to separate 
them; default: all) |  | String
-| `--output` | The file to write the route to (default: stdout) |  | String
+| `--output` | The file to write the route to, or the directory to write the 
samples to (default: stdout) |  | String
 | `--port` | The port (its name), when the service has more than one |  | 
String
 | `--route` | Scaffold a YAML route (consumer or producer) instead of listing 
the WSDL |  | String
+| `--samples` | Write a sample request, response and faults of each operation, 
as XML and as JSON (the form of the xsdJson data format), and the request in a 
SOAP envelope with a curl command to send it |  | boolean
 | `--service` | The service (its name), when the WSDL has more than one |  | 
String
 | `-h,--help` | Display this help and exit |  | boolean
 |===
diff --git a/dsl/camel-jbang/camel-jbang-plugin-generate/pom.xml 
b/dsl/camel-jbang/camel-jbang-plugin-generate/pom.xml
index 01525f3453a5..902c243a9c49 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-generate/pom.xml
+++ b/dsl/camel-jbang/camel-jbang-plugin-generate/pom.xml
@@ -94,6 +94,11 @@
                 </exclusion>
             </exclusions>
         </dependency>
+        <!-- the sample messages of the samples option of camel generate wsdl 
-->
+        <dependency>
+            <groupId>org.apache.camel</groupId>
+            <artifactId>camel-xsd-json</artifactId>
+        </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-openapi-rest-dsl-generator</artifactId>
diff --git 
a/dsl/camel-jbang/camel-jbang-plugin-generate/src/generated/resources/META-INF/camel-jbang-plugin-commands-metadata.json
 
b/dsl/camel-jbang/camel-jbang-plugin-generate/src/generated/resources/META-INF/camel-jbang-plugin-commands-metadata.json
index 828db8e6a357..f91f19f9cc5c 100644
--- 
a/dsl/camel-jbang/camel-jbang-plugin-generate/src/generated/resources/META-INF/camel-jbang-plugin-commands-metadata.json
+++ 
b/dsl/camel-jbang/camel-jbang-plugin-generate/src/generated/resources/META-INF/camel-jbang-plugin-commands-metadata.json
@@ -1,5 +1,5 @@
 {
   "commands": [
-    { "name": "generate", "fullName": "generate", "description": "Generate 
source code", "sourceClass": 
"org.apache.camel.dsl.jbang.core.commands.generate.CodeGenerator", "plugin": 
"generate", "options": [ { "names": "-h,--help", "description": "Display this 
help and exit", "javaType": "boolean", "type": "boolean" } ], "subcommands": [ 
{ "name": "rest", "fullName": "generate rest", "description": "Generate REST 
DSL source code from OpenApi specification", "sourceClass": "org.apache.camel 
[...]
+    { "name": "generate", "fullName": "generate", "description": "Generate 
source code", "sourceClass": 
"org.apache.camel.dsl.jbang.core.commands.generate.CodeGenerator", "plugin": 
"generate", "options": [ { "names": "-h,--help", "description": "Display this 
help and exit", "javaType": "boolean", "type": "boolean" } ], "subcommands": [ 
{ "name": "rest", "fullName": "generate rest", "description": "Generate REST 
DSL source code from OpenApi specification", "sourceClass": "org.apache.camel 
[...]
   ]
 }
diff --git 
a/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/CodeWsdlGenerator.java
 
b/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/CodeWsdlGenerator.java
index d319b95add25..a29b4c03fe95 100644
--- 
a/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/CodeWsdlGenerator.java
+++ 
b/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/CodeWsdlGenerator.java
@@ -17,6 +17,7 @@
 package org.apache.camel.dsl.jbang.core.commands.generate;
 
 import java.io.IOException;
+import java.net.URI;
 import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.NoSuchFileException;
@@ -24,8 +25,10 @@ import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Iterator;
+import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Locale;
+import java.util.Map;
 
 import javax.xml.namespace.QName;
 
@@ -35,15 +38,19 @@ import com.github.freva.asciitable.HorizontalAlign;
 import org.aesh.command.CommandDefinition;
 import org.aesh.command.option.Argument;
 import org.aesh.command.option.Option;
+import org.apache.camel.CamelContext;
+import org.apache.camel.dataformat.xsdjson.XsdJsonSamples;
 import org.apache.camel.dsl.jbang.core.commands.CamelCommand;
 import org.apache.camel.dsl.jbang.core.commands.generate.WsdlModel.Fault;
 import org.apache.camel.dsl.jbang.core.commands.generate.WsdlModel.Operation;
 import org.apache.camel.dsl.jbang.core.commands.generate.WsdlModel.Port;
 import org.apache.camel.dsl.jbang.core.commands.generate.WsdlModel.Service;
 import 
org.apache.camel.dsl.jbang.core.commands.generate.WsdlModel.WsdlException;
+import org.apache.camel.dsl.jbang.core.commands.generate.WsdlSamples.Sample;
 import org.apache.camel.dsl.jbang.core.common.CliExitCode;
 import org.apache.camel.dsl.jbang.core.common.CompletionCandidates;
 import org.apache.camel.dsl.jbang.core.common.JsonOutput;
+import org.apache.camel.impl.DefaultCamelContext;
 import org.apache.camel.util.json.JsonArray;
 import org.apache.camel.util.json.JsonObject;
 
@@ -62,6 +69,8 @@ import org.apache.camel.util.json.JsonObject;
                            "  camel generate wsdl orders.wsdl",
                            "  camel generate wsdl orders.wsdl --json",
                            "  camel generate wsdl orders.wsdl --route=consumer 
--output=orders.camel.yaml",
+                           "  camel generate wsdl orders.wsdl --samples 
--operation=getOrder",
+                           "  camel generate wsdl orders.wsdl --samples 
--output=samples",
                            "  camel generate wsdl 
http://localhost:8080/orders?wsdl --route=producer --operation=getOrder" })
 public class CodeWsdlGenerator extends CamelCommand {
 
@@ -88,9 +97,15 @@ public class CodeWsdlGenerator extends CamelCommand {
             completer = RouteCompletionCandidates.class)
     String route;
 
-    @Option(name = "output", description = "The file to write the route to 
(default: stdout)")
+    @Option(name = "output",
+            description = "The file to write the route to, or the directory to 
write the samples to (default: stdout)")
     String output;
 
+    @Option(name = "samples", hasValue = false,
+            description = "Write a sample request, response and faults of each 
operation, as XML and as JSON (the form of"
+                          + " the xsdJson data format), and the request in a 
SOAP envelope with a curl command to send it")
+    boolean samples;
+
     @Option(name = "service", description = "The service (its name), when the 
WSDL has more than one")
     String service;
 
@@ -113,8 +128,14 @@ public class CodeWsdlGenerator extends CamelCommand {
         if (route != null && jsonOutput) {
             return error(CliExitCode.USAGE, "Use --json to list the WSDL, or 
--route to scaffold a route, not both");
         }
-        if (route == null && output != null) {
-            return error(CliExitCode.USAGE, "--output is for the route of 
--route");
+        if (route != null && samples) {
+            return error(CliExitCode.USAGE, "Use --route to scaffold a route, 
or --samples for sample messages, not both");
+        }
+        if (samples && jsonOutput && output != null) {
+            return error(CliExitCode.USAGE, "--output is for the files of the 
samples, not with --json");
+        }
+        if (route == null && !samples && output != null) {
+            return error(CliExitCode.USAGE, "--output is for the route of 
--route, or the samples of --samples");
         }
 
         WsdlModel model;
@@ -173,9 +194,12 @@ public class CodeWsdlGenerator extends CamelCommand {
             }
         }
 
+        if (samples) {
+            return samples(model, services, operations);
+        }
         if (route == null) {
             if (jsonOutput) {
-                JsonOutput.print(printer(), toJson(model, services, 
operations));
+                JsonOutput.print(printer(), toJson(model, services, 
operations, null));
             } else {
                 printTable(services, operations);
             }
@@ -214,6 +238,122 @@ public class CodeWsdlGenerator extends CamelCommand {
         return CliExitCode.OK;
     }
 
+    private int samples(WsdlModel model, List<Service> services, List<String> 
operations) throws Exception {
+        Map<Port, List<Sample>> all = new LinkedHashMap<>();
+        List<Port> ports = allPorts(services);
+        try (CamelContext context = new DefaultCamelContext()) {
+            context.start();
+            XsdJsonSamples xsd;
+            try {
+                xsd = new XsdJsonSamples(context, wsdlUrl(), schemaReader());
+            } catch (RuntimeException e) {
+                // the WSDL was read, its types were not
+                return error(CliExitCode.FAILURE, "Cannot read the XML schema 
of the WSDL " + wsdl + ": "
+                                                  + rootMessage(e));
+            }
+            for (Port p : ports) {
+                // the operation names are file names: the port name tells the 
ports apart
+                String prefix = ports.size() > 1 ? p.name() + "-" : "";
+                WsdlSamples ws = new WsdlSamples(p, selected(p, operations), 
xsd);
+                all.put(p, ws.samples(prefix));
+                for (String warning : ws.warnings()) {
+                    printer().printWarn(warning);
+                }
+            }
+        }
+
+        if (jsonOutput) {
+            JsonOutput.print(printer(), toJson(model, services, operations, 
all));
+        } else if (output != null) {
+            Path dir = Path.of(output);
+            Files.createDirectories(dir);
+            for (List<Sample> list : all.values()) {
+                for (Sample sample : list) {
+                    for (Map.Entry<String, String> file : 
files(sample).entrySet()) {
+                        Files.writeString(dir.resolve(file.getKey()), 
file.getValue(), StandardCharsets.UTF_8);
+                        printer().println("Wrote " + 
dir.resolve(file.getKey()));
+                    }
+                }
+            }
+            for (List<Sample> list : all.values()) {
+                for (Sample sample : list) {
+                    if (sample.curl() != null) {
+                        printer().println();
+                        printer().println("Send the " + sample.operation() + " 
request (in " + output + "):");
+                        printer().println("  " + sample.curl());
+                    }
+                }
+            }
+        } else {
+            boolean first = true;
+            for (Map.Entry<Port, List<Sample>> entry : all.entrySet()) {
+                for (Sample sample : entry.getValue()) {
+                    if (!first) {
+                        printer().println();
+                    }
+                    first = false;
+                    printSample(entry.getKey(), sample);
+                }
+            }
+        }
+        return CliExitCode.OK;
+    }
+
+    private void printSample(Port p, Sample sample) {
+        String what = "fault".equals(sample.kind())
+                ? sample.operation() + " fault " + sample.name() : 
sample.operation() + " " + sample.kind();
+        printer().println("### " + what + ": " + 
sample.element().getLocalPart() + " (XML)");
+        printer().println(sample.xml().strip());
+        printer().println();
+        printer().println("### " + what + ": " + 
sample.element().getLocalPart() + " (JSON, xsdJson)");
+        printer().println(sample.json().strip());
+        if (sample.soap() != null) {
+            printer().println();
+            printer().println("### " + what + ": SOAP " + p.soapVersion() + " 
envelope (" + sample.soapFile() + ")");
+            printer().println(sample.soap().strip());
+            if (sample.curl() != null) {
+                printer().println();
+                printer().println("### Send it, with the envelope saved as " + 
sample.soapFile());
+                printer().println(sample.curl());
+            }
+        }
+    }
+
+    /**
+     * The files of a sample, by name: the XML, the JSON and the SOAP envelope.
+     */
+    private static Map<String, String> files(Sample sample) {
+        Map<String, String> answer = new LinkedHashMap<>();
+        answer.put(sample.baseName() + ".xml", sample.xml());
+        answer.put(sample.baseName() + ".json", sample.json() + "\n");
+        if (sample.soap() != null) {
+            answer.put(sample.soapFile(), sample.soap());
+        }
+        return answer;
+    }
+
+    /**
+     * Reads the documents of the XML schema of a remote WSDL with the rules 
of a wsdl:import (the host of the WSDL
+     * only, and a redirect only to the same scheme, host and port); a local 
WSDL only reads files.
+     */
+    private XsdJsonSamples.DocumentReader schemaReader() {
+        String url = wsdlUrl();
+        String lower = url.toLowerCase(Locale.ROOT);
+        if (!lower.startsWith("http://";) && !lower.startsWith("https://";)) {
+            return null;
+        }
+        URI root = WsdlModel.toUri(url);
+        return uri -> WsdlModel.readDocument(root, uri);
+    }
+
+    private static String rootMessage(Throwable e) {
+        Throwable t = e;
+        while (t.getCause() != null && t.getCause() != t) {
+            t = t.getCause();
+        }
+        return t.getMessage() != null ? t.getMessage() : e.getMessage();
+    }
+
     /**
      * The wsdlURL of the endpoints: the WSDL as it was given, with file: in 
front of a file name.
      */
@@ -276,7 +416,8 @@ public class CodeWsdlGenerator extends CamelCommand {
         return name.getNamespaceURI().equals(namespace) ? name.getLocalPart() 
: name.toString();
     }
 
-    private JsonObject toJson(WsdlModel model, List<Service> services, 
List<String> operations) {
+    private JsonObject toJson(
+            WsdlModel model, List<Service> services, List<String> operations, 
Map<Port, List<Sample>> samples) {
         JsonObject root = new JsonObject();
         root.put("wsdl", wsdl);
         root.put("targetNamespace", model.targetNamespace());
@@ -335,6 +476,9 @@ public class CodeWsdlGenerator extends CamelCommand {
                         fa.add(fo);
                     }
                     oo.put("faults", fa);
+                    if (samples != null) {
+                        oo.put("samples", samplesJson(samples.getOrDefault(p, 
List.of()), o.name()));
+                    }
                     oa.add(oo);
                 }
                 po.put("operations", oa);
@@ -347,6 +491,31 @@ public class CodeWsdlGenerator extends CamelCommand {
         return root;
     }
 
+    private static JsonArray samplesJson(List<Sample> samples, String 
operation) {
+        JsonArray answer = new JsonArray();
+        for (Sample sample : samples) {
+            if (!operation.equals(sample.operation())) {
+                continue;
+            }
+            JsonObject so = new JsonObject();
+            so.put("kind", sample.kind());
+            if ("fault".equals(sample.kind())) {
+                so.put("fault", sample.name());
+            }
+            so.put("element", sample.element().toString());
+            so.put("xml", sample.xml());
+            so.put("json", sample.json());
+            if (sample.soap() != null) {
+                so.put("soap", sample.soap());
+            }
+            if (sample.curl() != null) {
+                so.put("curl", sample.curl());
+            }
+            answer.add(so);
+        }
+        return answer;
+    }
+
     private static List<Operation> selected(Port p, List<String> operations) {
         if (operations.isEmpty()) {
             return p.operations();
diff --git 
a/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/WsdlModel.java
 
b/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/WsdlModel.java
index 7ff7313058f7..7e57262697c4 100644
--- 
a/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/WsdlModel.java
+++ 
b/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/WsdlModel.java
@@ -262,6 +262,33 @@ final class WsdlModel {
         }
     }
 
+    /**
+     * Reads a document of a remote WSDL that is not a WSDL document, such as 
a schema that its types import, with the
+     * rules of a {@code wsdl:import}: only from the host of the WSDL, not 
from https down to http, and a redirect only
+     * to the same scheme, host and port.
+     *
+     * @param  root        the WSDL the user gave
+     * @param  uri         the document
+     * @throws IOException when the document cannot be read, or is refused
+     */
+    static byte[] readDocument(URI root, String uri) throws IOException {
+        URI target;
+        try {
+            target = new URI(uri);
+        } catch (URISyntaxException e) {
+            throw new IOException("Not a valid URI: " + printable(uri), e);
+        }
+        String refused = refusedImport(root, root, target);
+        if (refused != null) {
+            throw new IOException("The document " + printable(uri) + " is not 
read: " + refused);
+        }
+        try (Reader reader = new Reader(root)) {
+            return reader.readBytes(target).data();
+        } catch (WsdlException e) {
+            throw new IOException(e.getMessage(), e);
+        }
+    }
+
     /**
      * Why the WSDL at {@code base} does not import the document at {@code 
imported}, or <tt>null</tt> when it does.
      * <p/>
diff --git 
a/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/WsdlSamples.java
 
b/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/WsdlSamples.java
new file mode 100644
index 000000000000..53da47b229a0
--- /dev/null
+++ 
b/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/WsdlSamples.java
@@ -0,0 +1,231 @@
+/*
+ * 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.generate;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.regex.Pattern;
+
+import javax.xml.namespace.QName;
+
+import org.apache.camel.dataformat.xsdjson.XsdJsonSamples;
+import org.apache.camel.dsl.jbang.core.commands.generate.WsdlModel.Fault;
+import org.apache.camel.dsl.jbang.core.commands.generate.WsdlModel.Operation;
+import org.apache.camel.dsl.jbang.core.commands.generate.WsdlModel.Port;
+
+/**
+ * The sample messages of the operations of a port: the request, the response 
and the faults as XML and as JSON in the
+ * form of the xsdJson data format, and the request in a SOAP envelope with a 
curl command to send it.
+ * <p>
+ * The names of the operations and faults go into file names and the address 
and SOAP action into a shell command, so
+ * they must be NCNames and plain URIs (no quote, space or brace); a message 
whose values are not is left out with a
+ * warning, as a hostile WSDL could otherwise put a command into the curl line.
+ */
+final class WsdlSamples {
+
+    static final String SOAP11_ENV = 
"http://schemas.xmlsoap.org/soap/envelope/";;
+    static final String SOAP12_ENV = "http://www.w3.org/2003/05/soap-envelope";;
+
+    /**
+     * The characters of an address or a SOAP action that can go into a 
single-quoted shell argument as they are.
+     */
+    private static final Pattern SAFE_URI = 
Pattern.compile("[\\p{L}\\p{N}\\-._~:/?#\\[\\]@!$&*+,;=%]*");
+
+    /**
+     * A sample message of an operation.
+     *
+     * @param prefix    the prefix of the file names (or empty)
+     * @param operation the operation
+     * @param kind      request, response or fault
+     * @param name      the name of the fault, else the operation name
+     * @param element   the element of the message
+     * @param xml       the XML document
+     * @param json      the JSON, as the xsdJson data format reads and writes 
it
+     * @param soap      the request in a SOAP envelope, else null
+     * @param curl      the curl command that sends the SOAP envelope (from 
the file {@link #soapFile()}), else null
+     */
+    record Sample(
+            String prefix, String operation, String kind, String name, QName 
element, String xml, String json, String soap,
+            String curl) {
+
+        /**
+         * The base name of the files of this sample, such as getOrder-request 
or getOrder-fault-orderNotFound.
+         */
+        String baseName() {
+            return prefix + ("fault".equals(kind) ? operation + "-fault-" + 
name : operation + "-" + kind);
+        }
+
+        String soapFile() {
+            return baseName() + ".soap.xml";
+        }
+    }
+
+    private final Port port;
+    private final List<Operation> operations;
+    private final XsdJsonSamples samples;
+    private final List<String> warnings = new ArrayList<>();
+
+    WsdlSamples(Port port, List<Operation> operations, XsdJsonSamples samples) 
{
+        this.port = port;
+        this.operations = operations;
+        this.samples = samples;
+    }
+
+    List<String> warnings() {
+        return warnings;
+    }
+
+    /**
+     * The samples of the operations, in the order of the operations: the 
request, the response and the faults.
+     *
+     * @param prefix the prefix of the file names, such as the port name when 
there is more than one port (or empty)
+     */
+    List<Sample> samples(String prefix) {
+        List<Sample> answer = new ArrayList<>();
+        if (!port.isDocument()) {
+            warnings.add("The port " + port.name() + " uses the rpc style, 
which has no samples (only document style)");
+            return answer;
+        }
+        String address = address();
+        for (Operation op : operations) {
+            if (!WsdlModel.isNcName(op.name())) {
+                warnings.add("The operation '" + 
WsdlModel.printable(op.name()) + "' is not a valid NCName: no samples");
+                continue;
+            }
+            String operation = op.name();
+            if (op.input() != null) {
+                Sample request = sample(prefix, operation, "request", 
op.name(), op.input());
+                if (request != null) {
+                    String soap = envelope(request.xml());
+                    String curl = curl(op, address, request.soapFile());
+                    answer.add(new Sample(
+                            prefix, operation, "request", op.name(), 
op.input(), request.xml(),
+                            request.json(), soap, curl));
+                }
+            }
+            if (op.output() != null) {
+                Sample response = sample(prefix, operation, "response", 
op.name(), op.output());
+                if (response != null) {
+                    answer.add(response);
+                }
+            }
+            for (Fault fault : op.faults()) {
+                if (fault.element() == null) {
+                    continue;
+                }
+                if (!WsdlModel.isNcName(fault.name())) {
+                    warnings.add("The fault '" + 
WsdlModel.printable(fault.name()) + "' of " + op.name()
+                                 + " is not a valid NCName: no samples");
+                    continue;
+                }
+                Sample sample = sample(prefix, operation, "fault", 
fault.name(), fault.element());
+                if (sample != null) {
+                    answer.add(sample);
+                }
+            }
+        }
+        return answer;
+    }
+
+    private Sample sample(String prefix, String operation, String kind, String 
name, QName element) {
+        try {
+            return new Sample(
+                    prefix, operation, kind, name, element, 
samples.xml(element.toString()),
+                    samples.json(element.toString()), null, null);
+        } catch (IllegalArgumentException e) {
+            warnings.add("No sample of the " + kind + " " + 
element.getLocalPart() + " of " + operation + ": "
+                         + WsdlModel.printable(e.getMessage()));
+            return null;
+        }
+    }
+
+    /**
+     * The request in a SOAP envelope of the SOAP version of the port.
+     */
+    String envelope(String xml) {
+        String body = xml;
+        if (body.startsWith("<?xml")) {
+            int end = body.indexOf("?>");
+            body = body.substring(end + 2);
+        }
+        String ns = "1.2".equals(port.soapVersion()) ? SOAP12_ENV : SOAP11_ENV;
+        StringBuilder sb = new StringBuilder();
+        sb.append("<soapenv:Envelope 
xmlns:soapenv=\"").append(ns).append("\">\n");
+        sb.append("  <soapenv:Body>\n");
+        for (String line : body.strip().split("\n")) {
+            sb.append("    ").append(line).append('\n');
+        }
+        sb.append("  </soapenv:Body>\n");
+        sb.append("</soapenv:Envelope>\n");
+        return sb.toString();
+    }
+
+    /**
+     * The curl command that posts the SOAP envelope in the file to the 
address of the port, with the SOAP action in the
+     * SOAPAction header (SOAP 1.1) or the action parameter of the content 
type (SOAP 1.2).
+     */
+    private String curl(Operation op, String address, String file) {
+        if (address == null) {
+            return null;
+        }
+        String action = op.soapAction() != null ? op.soapAction() : "";
+        if (!SAFE_URI.matcher(action).matches()) {
+            warnings.add("The SOAP action of " + op.name() + " has characters 
that are not put into a curl command");
+            return null;
+        }
+        StringBuilder sb = new StringBuilder("curl -X POST");
+        if ("1.2".equals(port.soapVersion())) {
+            sb.append(" -H 'Content-Type: application/soap+xml; charset=utf-8")
+                    .append(action.isEmpty() ? "" : "; action=\"" + action + 
"\"").append('\'');
+        } else {
+            sb.append(" -H 'Content-Type: text/xml; charset=utf-8' -H 
'SOAPAction: \"").append(action).append("\"'");
+        }
+        sb.append(" --data-binary @").append(file).append(" 
'").append(address).append('\'');
+        return sb.toString();
+    }
+
+    /**
+     * The address of the port without the user info and the query, or null 
when it has none or it has characters that
+     * cannot go into the curl command.
+     */
+    private String address() {
+        String raw = port.address();
+        if (raw == null || raw.isBlank()) {
+            return null;
+        }
+        URI uri;
+        try {
+            uri = new URI(raw.trim());
+        } catch (URISyntaxException e) {
+            return null;
+        }
+        String scheme = uri.getScheme() != null ? 
uri.getScheme().toLowerCase(Locale.ROOT) : null;
+        if (uri.getHost() == null || !("http".equals(scheme) || 
"https".equals(scheme))) {
+            return null;
+        }
+        String answer = scheme + "://" + uri.getHost() + (uri.getPort() != -1 
? ":" + uri.getPort() : "")
+                        + (uri.getRawPath() != null ? uri.getRawPath() : "");
+        if (!SAFE_URI.matcher(answer).matches()) {
+            warnings.add("The address of the port " + port.name() + " has 
characters that are not put into a curl command");
+            return null;
+        }
+        return answer;
+    }
+}
diff --git 
a/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/java/org/apache/camel/dsl/jbang/core/commands/generate/CodeWsdlGeneratorTest.java
 
b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/java/org/apache/camel/dsl/jbang/core/commands/generate/CodeWsdlGeneratorTest.java
index b1a49cacdf41..604ae7edfd6d 100644
--- 
a/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/java/org/apache/camel/dsl/jbang/core/commands/generate/CodeWsdlGeneratorTest.java
+++ 
b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/java/org/apache/camel/dsl/jbang/core/commands/generate/CodeWsdlGeneratorTest.java
@@ -16,6 +16,7 @@
  */
 package org.apache.camel.dsl.jbang.core.commands.generate;
 
+import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.net.InetAddress;
@@ -29,6 +30,8 @@ import java.util.List;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.stream.Collectors;
 
+import javax.xml.parsers.DocumentBuilderFactory;
+
 import com.sun.net.httpserver.HttpExchange;
 import com.sun.net.httpserver.HttpServer;
 import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
@@ -487,6 +490,168 @@ class CodeWsdlGeneratorTest {
         }
     }
 
+    @Test
+    void samplesOfAnOperation() throws Exception {
+        assertThat(run(ORDERS, "--samples", 
"--operation=getOrder")).as(printer.getOutput()).isZero();
+
+        String out = printer.getStdout();
+        assertThat(out).contains(
+                "### getOrder request: getOrder (XML)",
+                "<tns:getOrder xmlns:tns=\"http://example.com/orders\";>",
+                "### getOrder request: getOrder (JSON, xsdJson)",
+                "### getOrder request: SOAP 1.1 envelope 
(getOrder-request.soap.xml)",
+                "<soapenv:Envelope 
xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\";>",
+                "curl -X POST -H 'Content-Type: text/xml; charset=utf-8'"
+                                                                               
                   + " -H 'SOAPAction: \"http://example.com/orders/getOrder\";'"
+                                                                               
                   + " --data-binary @getOrder-request.soap.xml"
+                                                                               
                   + " 'http://localhost:18081/orders'",
+                "### getOrder response: getOrderResponse (XML)",
+                "### getOrder fault orderNotFound: orderNotFound (XML)")
+                .doesNotContain("placeOrder");
+        assertThat(printer.getStderr()).isEmpty();
+    }
+
+    @Test
+    void samplesAreWrittenToFiles() throws Exception {
+        Path samples = dir.resolve("samples");
+
+        assertThat(run(ORDERS, "--samples", "--output=" + 
samples)).as(printer.getOutput()).isZero();
+
+        
assertThat(samples).isDirectoryContaining("glob:**/getOrder-request.xml")
+                .isDirectoryContaining("glob:**/getOrder-request.json")
+                .isDirectoryContaining("glob:**/getOrder-request.soap.xml")
+                .isDirectoryContaining("glob:**/getOrder-response.json")
+                
.isDirectoryContaining("glob:**/getOrder-fault-orderNotFound.xml")
+                .isDirectoryContaining("glob:**/placeOrder-request.json");
+        JsonObject request = (JsonObject) 
Jsoner.deserialize(Files.readString(samples.resolve("getOrder-request.json")));
+        assertThat(request).containsKey("orderId");
+        // the envelope is XML
+        String soap = 
Files.readString(samples.resolve("getOrder-request.soap.xml"));
+        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+        factory.setNamespaceAware(true);
+        assertThat(factory.newDocumentBuilder()
+                .parse(new 
ByteArrayInputStream(soap.getBytes(StandardCharsets.UTF_8))).getDocumentElement()
+                .getLocalName()).isEqualTo("Envelope");
+        assertThat(printer.getStdout()).contains("Wrote " + 
samples.resolve("getOrder-request.xml"),
+                "--data-binary @getOrder-request.soap.xml");
+    }
+
+    @Test
+    void samplesOfSoap12LeaveOutTheUserInfo() throws Exception {
+        assertThat(run(NOTIFY, "--samples")).as(printer.getOutput()).isZero();
+
+        assertThat(printer.getStdout()).contains(
+                "<soapenv:Envelope 
xmlns:soapenv=\"http://www.w3.org/2003/05/soap-envelope\";>",
+                "-H 'Content-Type: application/soap+xml; charset=utf-8",
+                "'https://notify.example.com:8443/ws/notify'")
+                .doesNotContain("secret", "tenant");
+    }
+
+    @Test
+    void samplesInTheJsonListing() throws Exception {
+        assertThat(run(ORDERS, "--samples", "--json", 
"--operation=getOrder")).as(printer.getOutput()).isZero();
+
+        JsonObject root = (JsonObject) Jsoner.deserialize(printer.getStdout());
+        JsonObject getOrder = (JsonObject) port(root, 0, 
0).getJsonArray("operations").get(0);
+        JsonArray samples = getOrder.getJsonArray("samples");
+        assertThat(samples).extracting(o -> ((JsonObject) o).getString("kind"))
+                .containsExactly("request", "response", "fault");
+        JsonObject request = (JsonObject) samples.get(0);
+        
assertThat(request.getString("element")).isEqualTo("{http://example.com/orders}getOrder";);
+        assertThat(request.getString("soap")).contains("<soapenv:Body>");
+        assertThat(request.getString("curl")).startsWith("curl -X POST");
+        assertThat(((JsonObject) 
samples.get(2)).getString("fault")).isEqualTo("orderNotFound");
+    }
+
+    @Test
+    void samplesOptions() throws Exception {
+        assertThat(run(ORDERS, "--samples", "--route=consumer")).isEqualTo(2);
+        assertThat(printer.getStderr()).contains("not both");
+
+        StringPrinter json = new StringPrinter();
+        assertThat(run(json, ORDERS, "--samples", "--json", "--output=" + 
dir)).isEqualTo(2);
+    }
+
+    @Test
+    void aSoapActionThatIsNotAPlainUriIsNotPutIntoTheCurlCommand() throws 
Exception {
+        Path wsdl = dir.resolve("hostile.wsdl");
+        Files.writeString(wsdl, Files.readString(Paths.get(ORDERS))
+                .replace("http://example.com/orders/getOrder";, "x'; touch 
/tmp/pwned; echo '"));
+
+        assertThat(run(wsdl.toString(), "--samples", 
"--operation=getOrder")).as(printer.getOutput()).isZero();
+
+        assertThat(printer.getStdout()).contains("### getOrder request: SOAP 
1.1 envelope")
+                .doesNotContain("curl", "pwned");
+        assertThat(printer.getStderr()).contains("The SOAP action of getOrder 
has characters");
+    }
+
+    @Test
+    void theSchemaOfARemoteWsdlIsOnlyReadFromItsHost() throws Exception {
+        byte[] types = """
+                <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"; 
targetNamespace="urn:t"
+                           elementFormDefault="qualified">
+                  <xs:element name="ping"><xs:complexType><xs:sequence>
+                    <xs:element name="text" type="xs:string"/>
+                  </xs:sequence></xs:complexType></xs:element>
+                </xs:schema>
+                """.getBytes(StandardCharsets.UTF_8);
+        AtomicInteger typesRead = new AtomicInteger();
+        HttpServer server = HttpServer.create(new 
InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
+        int port = server.getAddress().getPort();
+        server.createContext("/same", exchange -> reply(exchange, 
pingWsdl("types.xsd")));
+        server.createContext("/other",
+                exchange -> reply(exchange, pingWsdl("http://127.0.0.1:"; + 
port + "/types.xsd")));
+        server.createContext("/types.xsd", exchange -> {
+            typesRead.incrementAndGet();
+            reply(exchange, types);
+        });
+        server.start();
+        try {
+            String base = "http://localhost:"; + port;
+
+            assertThat(run(base + "/same", 
"--samples")).as(printer.getOutput()).isZero();
+            // the imported schema declares no prefix for its namespace, so 
the writer chooses one
+            assertThat(printer.getStdout()).contains(":ping xmlns:", 
"=\"urn:t\">", ":text>string</");
+            assertThat(typesRead).hasValue(1);
+
+            // 127.0.0.1 is another host than localhost
+            StringPrinter refused = new StringPrinter();
+            assertThat(run(refused, base + "/other", 
"--samples")).isEqualTo(1);
+            assertThat(refused.getStderr()).contains("is not read: it is on 
the host 127.0.0.1");
+            assertThat(typesRead).hasValue(1);
+        } finally {
+            server.stop(0);
+        }
+    }
+
+    private static byte[] pingWsdl(String schemaLocation) {
+        return """
+                <wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/";
+                    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"; 
xmlns:tns="urn:ping" xmlns:t="urn:t"
+                    xmlns:xs="http://www.w3.org/2001/XMLSchema"; 
targetNamespace="urn:ping">
+                  <wsdl:types>
+                    <xs:schema targetNamespace="urn:ping"><xs:import 
namespace="urn:t" schemaLocation="%s"/></xs:schema>
+                  </wsdl:types>
+                  <wsdl:message name="pingRequest"><wsdl:part name="body" 
element="t:ping"/></wsdl:message>
+                  <wsdl:portType name="PingPortType">
+                    <wsdl:operation name="ping"><wsdl:input 
message="tns:pingRequest"/></wsdl:operation>
+                  </wsdl:portType>
+                  <wsdl:binding name="PingBinding" type="tns:PingPortType">
+                    <soap:binding style="document" 
transport="http://schemas.xmlsoap.org/soap/http"/>
+                    <wsdl:operation name="ping">
+                      <soap:operation soapAction="urn:ping"/>
+                      <wsdl:input><soap:body use="literal"/></wsdl:input>
+                    </wsdl:operation>
+                  </wsdl:binding>
+                  <wsdl:service name="PingService">
+                    <wsdl:port name="PingPort" binding="tns:PingBinding">
+                      <soap:address location="http://localhost:9/ping"/>
+                    </wsdl:port>
+                  </wsdl:service>
+                </wsdl:definitions>
+                """.formatted(schemaLocation).getBytes(StandardCharsets.UTF_8);
+    }
+
     @Test
     void invalidOptions() throws Exception {
         assertThat(run(ORDERS, "--route=both")).isEqualTo(2);

Reply via email to