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 18cf19a7ccd40733537bb3781fe4df92f3d15fb8
Author: Claus Ibsen <[email protected]>
AuthorDate: Sun Nov 22 20:34:19 2026 +0100

    CAMEL-27397: camel-xsd-json - XsdJsonSamples: a sample of a global element 
as JSON and XML
    
    A new public class XsdJsonSamples gives a sample of a global element of a
    schema, as JSON in the form of the xsdJson data format and as the XML that
    the data format writes from it. Every element and attribute has a value of
    its type: the first value of an enumeration, a date for xs:date, a number
    for xs:int, and so on; a repeating element has one item, of an xs:choice
    only the first member is filled in, and a type that contains itself is
    filled in once.
    
    The simple types of the model keep the built-in type they derive from and
    their first enumeration value for that. An optional DocumentReader reads
    the schema and its imports instead of the CamelContext, so a caller can
    restrict where they are read from.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    Signed-off-by: Claus Ibsen <[email protected]>
---
 .../camel/catalog/docs/xsdJson-dataformat.adoc     |  17 ++
 .../src/main/docs/xsdJson-dataformat.adoc          |  17 ++
 .../dataformat/xsdjson/XsdJsonDataFormat.java      |  18 +-
 .../camel/dataformat/xsdjson/XsdJsonSamples.java   | 252 +++++++++++++++++++++
 .../apache/camel/dataformat/xsdjson/XsdModel.java  |   9 +-
 .../camel/dataformat/xsdjson/XsdModelBuilder.java  |  29 ++-
 .../camel/dataformat/xsdjson/XsdSchemaLoader.java  |  12 +
 .../dataformat/xsdjson/XsdJsonSamplesTest.java     | 165 ++++++++++++++
 .../src/test/resources/xsdjson/samples.xsd         |  99 ++++++++
 9 files changed, 606 insertions(+), 12 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/xsdJson-dataformat.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/xsdJson-dataformat.adoc
index cb36e9f6b832..19d850473fe9 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/xsdJson-dataformat.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/xsdJson-dataformat.adoc
@@ -311,6 +311,23 @@ YAML::
               schema: classpath:orders.wsdl
 ----
 
+== Samples
+
+The Camel CLI writes a sample of each message of a WSDL, as XML and as JSON in 
the form of this data format, with
+`camel generate wsdl orders.wsdl --samples`. See 
xref:manual::camel-jbang-projects.adoc[Camel CLI projects].
+
+From Java, `org.apache.camel.dataformat.xsdjson.XsdJsonSamples` gives the same 
samples for any global element of a
+schema. Every element and attribute has a value of its type (the first value 
of an enumeration, a date for `xs:date`,
+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.
+
+[source,java]
+----
+XsdJsonSamples samples = new XsdJsonSamples(camelContext, 
"classpath:orders.wsdl");
+String json = samples.json("getOrder");
+String xml = samples.xml("getOrder");
+----
+
 == Dependencies
 
 Maven users need to add the following dependency:
diff --git a/components/camel-xsd-json/src/main/docs/xsdJson-dataformat.adoc 
b/components/camel-xsd-json/src/main/docs/xsdJson-dataformat.adoc
index cb36e9f6b832..19d850473fe9 100644
--- a/components/camel-xsd-json/src/main/docs/xsdJson-dataformat.adoc
+++ b/components/camel-xsd-json/src/main/docs/xsdJson-dataformat.adoc
@@ -311,6 +311,23 @@ YAML::
               schema: classpath:orders.wsdl
 ----
 
+== Samples
+
+The Camel CLI writes a sample of each message of a WSDL, as XML and as JSON in 
the form of this data format, with
+`camel generate wsdl orders.wsdl --samples`. See 
xref:manual::camel-jbang-projects.adoc[Camel CLI projects].
+
+From Java, `org.apache.camel.dataformat.xsdjson.XsdJsonSamples` gives the same 
samples for any global element of a
+schema. Every element and attribute has a value of its type (the first value 
of an enumeration, a date for `xs:date`,
+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.
+
+[source,java]
+----
+XsdJsonSamples samples = new XsdJsonSamples(camelContext, 
"classpath:orders.wsdl");
+String json = samples.json("getOrder");
+String xml = samples.xml("getOrder");
+----
+
 == Dependencies
 
 Maven users need to add the following dependency:
diff --git 
a/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdJsonDataFormat.java
 
b/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdJsonDataFormat.java
index a3ab37b87753..2b9f64762484 100644
--- 
a/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdJsonDataFormat.java
+++ 
b/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdJsonDataFormat.java
@@ -100,6 +100,7 @@ public class XsdJsonDataFormat extends ServiceSupport 
implements DataFormat, Dat
     private boolean prettyPrint;
 
     private XsdModel model;
+    private XsdJsonSamples.DocumentReader documentReader;
     private Element defaultElement;
     private XMLInputFactory inputFactory;
     private XMLOutputFactory outputFactory;
@@ -128,7 +129,8 @@ public class XsdJsonDataFormat extends ServiceSupport 
implements DataFormat, Dat
         if (ObjectHelper.isEmpty(textName)) {
             textName = "value";
         }
-        model = new XsdModelBuilder(new XsdSchemaLoader(camelContext, 
schema).load(), attributePrefix, textName).build();
+        model = new XsdModelBuilder(
+                new XsdSchemaLoader(camelContext, schema, 
documentReader).load(), attributePrefix, textName).build();
         if (ObjectHelper.isNotEmpty(element)) {
             defaultElement = model.findElement(element);
             model.checkConflicts(defaultElement);
@@ -142,6 +144,20 @@ public class XsdJsonDataFormat extends ServiceSupport 
implements DataFormat, Dat
         // the model is kept, a restart reads the schema again
     }
 
+    /**
+     * Reads the schema and the documents it imports, instead of the 
CamelContext (used by {@link XsdJsonSamples}).
+     */
+    void setDocumentReader(XsdJsonSamples.DocumentReader documentReader) {
+        this.documentReader = documentReader;
+    }
+
+    /**
+     * The model of the schema, once the data format is started.
+     */
+    XsdModel getModel() {
+        return model;
+    }
+
     /**
      * The element for this message: the header, else the element option, else 
null.
      */
diff --git 
a/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdJsonSamples.java
 
b/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdJsonSamples.java
new file mode 100644
index 000000000000..0c830948e54f
--- /dev/null
+++ 
b/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdJsonSamples.java
@@ -0,0 +1,252 @@
+/*
+ * 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.dataformat.xsdjson;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.dataformat.xsdjson.XsdModel.Attribute;
+import org.apache.camel.dataformat.xsdjson.XsdModel.Element;
+import org.apache.camel.dataformat.xsdjson.XsdModel.Group;
+import org.apache.camel.dataformat.xsdjson.XsdModel.SimpleType;
+import org.apache.camel.dataformat.xsdjson.XsdModel.Type;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.util.ObjectHelper;
+
+/**
+ * Sample documents for the global elements of an XML Schema (an .xsd file, or 
the types of a .wsdl file), such as the
+ * request and response of a SOAP operation. Every element and attribute is 
filled in with a value of its type: the
+ * first value of an enumeration, a date for xs:date, a number for xs:int, and 
so on, and a repeating element has one
+ * item. Of an xs:choice, only the first member is filled in, and an element 
whose type contains itself is filled in
+ * once. A value is not made to match the other facets of its type, such as a 
pattern or a length.
+ * <p>
+ * The JSON is the form that the xsdJson data format reads and writes, without 
the root element (the default of
+ * includeRoot), and the XML is what the data format writes from it, so a 
sample can be used as it is in a route.
+ *
+ * @since 4.24
+ */
+public final class XsdJsonSamples {
+
+    private static final int MAX_DEPTH = 32;
+
+    /**
+     * Reads a document: the schema, or a schema or WSDL that it imports or 
includes.
+     */
+    @FunctionalInterface
+    public interface DocumentReader {
+
+        /**
+         * @param  uri         the uri of the document, such as 
file:orders.wsdl or https://example.com/orders.xsd
+         * @return             the content of the document
+         * @throws IOException if the document cannot be read, or must not be
+         */
+        byte[] read(String uri) throws IOException;
+    }
+
+    private final XsdJsonDataFormat dataFormat;
+    private final CamelContext camelContext;
+
+    /**
+     * Loads the schema as the xsdJson data format does.
+     *
+     * @param camelContext the CamelContext, which loads the schema
+     * @param schema       the schema, such as file:orders.wsdl or 
classpath:orders.xsd
+     */
+    public XsdJsonSamples(CamelContext camelContext, String schema) {
+        this(camelContext, schema, null);
+    }
+
+    /**
+     * Loads the schema as the xsdJson data format does, with the documents 
read by the reader, such as to only read
+     * from the host of a WSDL. The imports and includes still keep to the 
scheme of the schema.
+     *
+     * @param camelContext the CamelContext
+     * @param schema       the schema, such as file:orders.wsdl or 
https://example.com/orders?wsdl
+     * @param reader       reads the schema and the documents it imports or 
includes (null to use the CamelContext)
+     */
+    public XsdJsonSamples(CamelContext camelContext, String schema, 
DocumentReader reader) {
+        this.camelContext = camelContext;
+        this.dataFormat = new XsdJsonDataFormat();
+        dataFormat.setCamelContext(camelContext);
+        dataFormat.setSchema(schema);
+        dataFormat.setDocumentReader(reader);
+        dataFormat.setPrettyPrint(true);
+        dataFormat.start();
+    }
+
+    /**
+     * The sample of a global element as JSON text, indented.
+     *
+     * @param  element                  the element, as {namespace}name or as 
a local name that is unique in the schema
+     * @throws IllegalArgumentException if the schema has no such element, or 
the element cannot be mapped
+     */
+    public String json(String element) {
+        return JsonText.write(sample(element), true);
+    }
+
+    /**
+     * The sample of a global element as an XML document, indented, as the 
xsdJson data format writes it from the JSON
+     * sample.
+     *
+     * @param  element                  the element, as {namespace}name or as 
a local name that is unique in the schema
+     * @throws IllegalArgumentException if the schema has no such element, or 
the element cannot be mapped
+     */
+    public String xml(String element) {
+        Object json = sample(element);
+        Exchange exchange = new DefaultExchange(camelContext);
+        exchange.getMessage().setHeader(XsdJsonDataFormat.ELEMENT, element);
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        try {
+            dataFormat.marshal(exchange, json, out);
+        } catch (RuntimeException e) {
+            throw e;
+        } catch (Exception e) {
+            throw new IllegalArgumentException("Cannot write the sample of " + 
element + ": " + e.getMessage(), e);
+        }
+        String xml = out.toString(StandardCharsets.UTF_8);
+        // the root element on a line of its own, after the XML declaration
+        int end = xml.startsWith("<?xml") ? xml.indexOf("?>") : -1;
+        if (end > 0 && end + 2 < xml.length() && xml.charAt(end + 2) != '\n') {
+            xml = xml.substring(0, end + 2) + "\n" + xml.substring(end + 2);
+        }
+        return xml;
+    }
+
+    private Object sample(String element) {
+        XsdModel model = dataFormat.getModel();
+        Element root = model.findElement(element);
+        model.checkConflicts(root);
+        if (root.unsupported != null) {
+            throw new IllegalArgumentException("Cannot map " + root.name + ": 
" + root.unsupported);
+        }
+        return value(root.type, Collections.newSetFromMap(new 
IdentityHashMap<>()), 0);
+    }
+
+    private Object value(Type type, Set<Type> path, int depth) {
+        if (type == null) {
+            return "string";
+        }
+        if (type.unsupported != null) {
+            throw new IllegalArgumentException("Cannot map " + 
type.displayName() + ": " + type.unsupported);
+        }
+        if (!type.complex) {
+            return simple(type.simple);
+        }
+        Map<String, Object> map = new LinkedHashMap<>();
+        path.add(type);
+        try {
+            for (Attribute attribute : type.attributes) {
+                map.put(attribute.jsonName, simple(attribute.type));
+            }
+            if (type.hasSimpleContent()) {
+                map.put(dataFormat.getTextName(), simple(type.simple));
+            } else if (type.content != null) {
+                group(type.content, map, path, depth);
+            }
+        } finally {
+            path.remove(type);
+        }
+        return map;
+    }
+
+    private void group(Group group, Map<String, Object> map, Set<Type> path, 
int depth) {
+        for (Object member : group.members) {
+            if (member instanceof Element e) {
+                element(e, map, path, depth);
+            } else if (member instanceof Group g) {
+                group(g, map, path, depth);
+            }
+            if (group.kind == XsdModel.GroupKind.CHOICE) {
+                // the first member of a choice only
+                return;
+            }
+        }
+    }
+
+    private void element(Element e, Map<String, Object> map, Set<Type> path, 
int depth) {
+        if (e.unsupported != null || e.type != null && path.contains(e.type) 
|| depth >= MAX_DEPTH) {
+            // an element that cannot be mapped, or that contains itself, is 
left out
+            return;
+        }
+        Object value = value(e.type, path, depth + 1);
+        map.put(e.jsonName(), e.array ? List.of(value) : value);
+    }
+
+    private static Object simple(SimpleType type) {
+        if (type == null) {
+            return "string";
+        }
+        Object value = scalar(type);
+        return type.list() ? List.of(value) : value;
+    }
+
+    private static Object scalar(SimpleType type) {
+        String text = ObjectHelper.isNotEmpty(type.enumeration()) ? 
type.enumeration() : null;
+        return switch (type.kind()) {
+            case BOOLEAN -> text != null ? Boolean.valueOf(text.trim()) : 
Boolean.TRUE;
+            case INTEGER -> text != null ? number(text) : switch 
(type.builtin()) {
+                case "negativeInteger" -> -1L;
+                case "nonPositiveInteger" -> 0L;
+                default -> 1L;
+            };
+            case DECIMAL -> text != null ? number(text) : new 
BigDecimal("9.99");
+            case FLOAT -> text != null ? number(text) : 1.5d;
+            default -> text != null ? text : string(type.builtin());
+        };
+    }
+
+    private static Object number(String text) {
+        try {
+            return new BigDecimal(text.trim());
+        } catch (NumberFormatException e) {
+            return text;
+        }
+    }
+
+    private static String string(String builtin) {
+        if (builtin == null) {
+            return "string";
+        }
+        return switch (builtin) {
+            case "dateTime", "dateTimeStamp" -> "2026-01-31T12:00:00Z";
+            case "date" -> "2026-01-31";
+            case "time" -> "12:00:00";
+            case "duration" -> "P1D";
+            case "gYear" -> "2026";
+            case "gYearMonth" -> "2026-01";
+            case "gMonth" -> "--01";
+            case "gMonthDay" -> "--01-31";
+            case "gDay" -> "---31";
+            case "base64Binary" -> "c2FtcGxl";
+            case "hexBinary" -> "73616D706C65";
+            case "anyURI" -> "http://example.com";;
+            case "language" -> "en";
+            case "ID", "IDREF", "NCName", "Name", "NMTOKEN", "ENTITY" -> "id1";
+            default -> "string";
+        };
+    }
+}
diff --git 
a/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdModel.java
 
b/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdModel.java
index aa1fdebd48d7..54c2c882458c 100644
--- 
a/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdModel.java
+++ 
b/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdModel.java
@@ -51,9 +51,14 @@ final class XsdModel {
     }
 
     /**
-     * A simple type: the JSON kind of its text, and whether it is an xs:list 
(a JSON array).
+     * A simple type: the JSON kind of its text, and whether it is an xs:list 
(a JSON array). The built-in type that it
+     * derives from (such as dateTime or int) and its first enumeration value 
(or null) are only used for samples.
      */
-    record SimpleType(SimpleKind kind, boolean list) {
+    record SimpleType(SimpleKind kind, boolean list, String builtin, String 
enumeration) {
+
+        SimpleType withEnumeration(String value) {
+            return new SimpleType(kind, list, builtin, value);
+        }
     }
 
     /**
diff --git 
a/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdModelBuilder.java
 
b/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdModelBuilder.java
index bfb88f69ca47..6e39eb6c4262 100644
--- 
a/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdModelBuilder.java
+++ 
b/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdModelBuilder.java
@@ -52,6 +52,8 @@ import org.apache.ws.commons.schema.XmlSchemaComplexType;
 import org.apache.ws.commons.schema.XmlSchemaContent;
 import org.apache.ws.commons.schema.XmlSchemaContentModel;
 import org.apache.ws.commons.schema.XmlSchemaElement;
+import org.apache.ws.commons.schema.XmlSchemaEnumerationFacet;
+import org.apache.ws.commons.schema.XmlSchemaFacet;
 import org.apache.ws.commons.schema.XmlSchemaForm;
 import org.apache.ws.commons.schema.XmlSchemaGroup;
 import org.apache.ws.commons.schema.XmlSchemaGroupParticle;
@@ -82,7 +84,7 @@ import static 
org.apache.camel.dataformat.xsdjson.XsdSchemaLoader.XSD_NS;
  */
 final class XsdModelBuilder {
 
-    private static final SimpleType STRING = new SimpleType(SimpleKind.STRING, 
false);
+    private static final SimpleType STRING = new SimpleType(SimpleKind.STRING, 
false, "string", null);
     private static final int MAX_TYPE_DEPTH = 64;
 
     private final XmlSchemaCollection collection;
@@ -448,12 +450,19 @@ final class XsdModelBuilder {
         }
         XmlSchemaSimpleTypeContent content = st.getContent();
         if (content instanceof XmlSchemaSimpleTypeRestriction r) {
-            return r.getBaseType() != null
+            SimpleType base = r.getBaseType() != null
                     ? simpleType(r.getBaseType(), depth + 1) : 
simpleType(r.getBaseTypeName(), depth + 1);
+            // the enumeration of the most derived type that has one
+            for (XmlSchemaFacet facet : r.getFacets()) {
+                if (facet instanceof XmlSchemaEnumerationFacet e && 
e.getValue() != null) {
+                    return base.withEnumeration(e.getValue().toString());
+                }
+            }
+            return base;
         } else if (content instanceof XmlSchemaSimpleTypeList list) {
             SimpleType item = list.getItemType() != null
                     ? simpleType(list.getItemType(), depth + 1) : 
simpleType(list.getItemTypeName(), depth + 1);
-            return new SimpleType(item.kind(), true);
+            return new SimpleType(item.kind(), true, item.builtin(), 
item.enumeration());
         } else if (content instanceof XmlSchemaSimpleTypeUnion) {
             return STRING;
         }
@@ -462,15 +471,17 @@ final class XsdModelBuilder {
 
     private static SimpleType builtin(String name) {
         return switch (name) {
-            case "boolean" -> new SimpleType(SimpleKind.BOOLEAN, false);
-            case "decimal" -> new SimpleType(SimpleKind.DECIMAL, false);
-            case "float", "double" -> new SimpleType(SimpleKind.FLOAT, false);
+            case "boolean" -> new SimpleType(SimpleKind.BOOLEAN, false, name, 
null);
+            case "decimal" -> new SimpleType(SimpleKind.DECIMAL, false, name, 
null);
+            case "float", "double" -> new SimpleType(SimpleKind.FLOAT, false, 
name, null);
             case "integer", "nonPositiveInteger", "negativeInteger", "long", 
"int", "short", "byte",
                     "nonNegativeInteger", "unsignedLong", "unsignedInt", 
"unsignedShort", "unsignedByte",
                     "positiveInteger" ->
-                new SimpleType(SimpleKind.INTEGER, false);
-            case "NMTOKENS", "IDREFS", "ENTITIES" -> new 
SimpleType(SimpleKind.STRING, true);
-            default -> STRING;
+                new SimpleType(SimpleKind.INTEGER, false, name, null);
+            case "NMTOKENS" -> new SimpleType(SimpleKind.STRING, true, 
"NMTOKEN", null);
+            case "IDREFS" -> new SimpleType(SimpleKind.STRING, true, "IDREF", 
null);
+            case "ENTITIES" -> new SimpleType(SimpleKind.STRING, true, 
"ENTITY", null);
+            default -> new SimpleType(SimpleKind.STRING, false, name, null);
         };
     }
 
diff --git 
a/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdSchemaLoader.java
 
b/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdSchemaLoader.java
index 2e4ddb6dd100..60fc0ad6f403 100644
--- 
a/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdSchemaLoader.java
+++ 
b/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdSchemaLoader.java
@@ -65,9 +65,18 @@ final class XsdSchemaLoader {
     private final CamelContext camelContext;
     private final String location;
     private final String scheme;
+    private final XsdJsonSamples.DocumentReader reader;
 
     XsdSchemaLoader(CamelContext camelContext, String schema) {
+        this(camelContext, schema, null);
+    }
+
+    /**
+     * @param reader reads the schema and the documents it imports or 
includes, instead of the CamelContext (or null)
+     */
+    XsdSchemaLoader(CamelContext camelContext, String schema, 
XsdJsonSamples.DocumentReader reader) {
         this.camelContext = camelContext;
+        this.reader = reader;
         String s = schema.trim();
         this.location = hasScheme(s) ? s : "classpath:" + s;
         this.scheme = schemeOf(this.location);
@@ -227,6 +236,9 @@ final class XsdSchemaLoader {
     }
 
     private byte[] read(String uri) throws IOException {
+        if (reader != null) {
+            return reader.read(uri);
+        }
         try (InputStream is = 
ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, uri)) {
             return is.readAllBytes();
         }
diff --git 
a/components/camel-xsd-json/src/test/java/org/apache/camel/dataformat/xsdjson/XsdJsonSamplesTest.java
 
b/components/camel-xsd-json/src/test/java/org/apache/camel/dataformat/xsdjson/XsdJsonSamplesTest.java
new file mode 100644
index 000000000000..5b8fb21161f6
--- /dev/null
+++ 
b/components/camel-xsd-json/src/test/java/org/apache/camel/dataformat/xsdjson/XsdJsonSamplesTest.java
@@ -0,0 +1,165 @@
+/*
+ * 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.dataformat.xsdjson;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringReader;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.XMLConstants;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.validation.SchemaFactory;
+import javax.xml.validation.Validator;
+
+import org.apache.camel.support.ResourceHelper;
+import org.apache.camel.util.json.JsonObject;
+import org.apache.camel.util.json.Jsoner;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class XsdJsonSamplesTest extends XsdJsonTestSupport {
+
+    private static final String SAMPLES = "classpath:xsdjson/samples.xsd";
+
+    @Test
+    void everyBuiltInTypeHasAValueOfItsType() throws Exception {
+        XsdJsonSamples samples = new XsdJsonSamples(context, SAMPLES);
+
+        JsonObject json = (JsonObject) 
Jsoner.deserialize(samples.json("types"));
+        assertThat(json.get("version")).hasToString("1");
+        assertThat(json.get("text")).isEqualTo("string");
+        assertThat(json.get("flag")).isEqualTo(true);
+        assertThat(json.get("count")).hasToString("1");
+        assertThat(json.get("negative")).hasToString("-1");
+        assertThat(json.get("nonPositive")).hasToString("0");
+        assertThat(json.get("amount")).hasToString("9.99");
+        assertThat(json.get("dateTime")).isEqualTo("2026-01-31T12:00:00Z");
+        assertThat(json.get("date")).isEqualTo("2026-01-31");
+        assertThat(json.get("uri")).isEqualTo("http://example.com";);
+        // the first value of an enumeration, of the type of the field, and of 
the most derived type
+        assertThat(json.get("level")).hasToString("3");
+        assertThat(json.get("color")).isEqualTo("red");
+        assertThat(json.get("dark")).isEqualTo("blue");
+        // lists and repeating elements are arrays with one item
+        assertThat(list(json, "tokens")).containsExactly("id1");
+        assertThat(list(json, "levels")).hasSize(1);
+        assertThat(list(json, "item")).containsExactly("string");
+        // the first member of a choice, and the optional elements too
+        assertThat(json).containsKeys("email", 
"optional").doesNotContainKey("phone");
+        // a type that contains itself is filled in once
+        assertThat(map(json, "root")).containsOnlyKeys("name");
+
+        // the XML is valid
+        assertValid("src/test/resources/xsdjson/samples.xsd", 
samples.xml("types"));
+    }
+
+    @Test
+    void theXmlIsWhatTheDataFormatWritesAndReadsBackAsTheJson() throws 
Exception {
+        XsdJsonSamples samples = new XsdJsonSamples(context, SAMPLES);
+        String xml = samples.xml("{urn:samples}types");
+
+        assertThat(xml).startsWith("<?xml version=\"1.0\" 
encoding=\"UTF-8\"?>")
+                .contains("<t:types xmlns:t=\"urn:samples\" version=\"1\">", 
"<t:level>3</t:level>",
+                        "<t:tokens>id1</t:tokens>");
+        XsdJsonDataFormat df = dataFormat(SAMPLES, d -> {
+        });
+        assertThat(Jsoner.deserialize(toJson(df, 
xml))).isEqualTo(Jsoner.deserialize(samples.json("types")));
+    }
+
+    @ParameterizedTest
+    @CsvSource({ "getOrder", "getOrderResponse", "placeOrder", 
"placeOrderResponse", "orderNotFound" })
+    void theMessagesOfAWsdl(String element) throws Exception {
+        XsdJsonSamples samples = new XsdJsonSamples(context, 
"classpath:xsdjson/orders.wsdl");
+
+        String xml = samples.xml(element);
+        assertThat(xml).contains("<tns:" + element + " 
xmlns:tns=\"http://example.com/orders\";>");
+        XsdJsonDataFormat df = dataFormat("classpath:xsdjson/orders.wsdl", d 
-> {
+        });
+        assertThat(Jsoner.deserialize(toJson(df, 
xml))).isEqualTo(Jsoner.deserialize(samples.json(element)));
+    }
+
+    @Test
+    void theSampleOfTheShopOrder() throws Exception {
+        XsdJsonSamples samples = new XsdJsonSamples(context, 
"classpath:xsdjson/shop.xsd");
+
+        JsonObject json = (JsonObject) 
Jsoner.deserialize(samples.json("order"));
+        assertThat(json.get("status")).isEqualTo("NEW");
+        assertThat(map(json, "customer")).containsKeys("id", "name", "vip");
+        // simple content with an attribute
+        assertThat(map((JsonObject) list(json, "line").get(0), "price"))
+                .containsOnlyKeys("currency", "value");
+        assertThat(json).containsKeys("card", "tags", 
"extras").doesNotContainKey("invoice");
+        assertThat(map(json, "address")).containsOnlyKeys("country", "street", 
"zip");
+    }
+
+    @Test
+    void theDocumentsAreReadByTheReader() throws Exception {
+        List<String> read = new ArrayList<>();
+        XsdJsonSamples.DocumentReader reader = uri -> {
+            read.add(uri);
+            try (InputStream is = 
ResourceHelper.resolveMandatoryResourceAsInputStream(context, uri)) {
+                return is.readAllBytes();
+            }
+        };
+        XsdJsonSamples samples = new XsdJsonSamples(context, 
"classpath:xsdjson/shop.xsd", reader);
+
+        assertThat(samples.json("order")).contains("\"street\"");
+        assertThat(read).containsExactly("classpath:xsdjson/shop.xsd", 
"classpath:xsdjson/common/common.xsd");
+
+        // a reader that refuses the import
+        XsdJsonSamples.DocumentReader refusing = uri -> {
+            if (uri.contains("common")) {
+                throw new IOException("not this one");
+            }
+            return reader.read(uri);
+        };
+        assertThatThrownBy(() -> new XsdJsonSamples(context, 
"classpath:xsdjson/shop.xsd", refusing))
+                .hasStackTraceContaining("not this one");
+    }
+
+    @Test
+    void anUnknownElement() {
+        XsdJsonSamples samples = new XsdJsonSamples(context, SAMPLES);
+
+        assertThatThrownBy(() -> samples.json("nope"))
+                .isInstanceOf(IllegalArgumentException.class)
+                .hasMessageContaining("The schema has no global element nope");
+    }
+
+    @SuppressWarnings("unchecked")
+    private static List<Object> list(JsonObject json, String key) {
+        return (List<Object>) json.get(key);
+    }
+
+    private static Map<String, Object> map(JsonObject json, String key) {
+        return (JsonObject) json.get(key);
+    }
+
+    private static void assertValid(String xsd, String xml) throws Exception {
+        SchemaFactory factory = 
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+        Validator validator = 
factory.newSchema(Paths.get(xsd).toFile()).newValidator();
+        validator.validate(new StreamSource(new StringReader(xml)));
+    }
+}
diff --git a/components/camel-xsd-json/src/test/resources/xsdjson/samples.xsd 
b/components/camel-xsd-json/src/test/resources/xsdjson/samples.xsd
new file mode 100644
index 000000000000..07a33c88e63f
--- /dev/null
+++ b/components/camel-xsd-json/src/test/resources/xsdjson/samples.xsd
@@ -0,0 +1,99 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    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.
+
+-->
+<!-- every built-in type that XsdJsonSamples gives a value of its own, to 
check that the samples are valid -->
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"; xmlns:t="urn:samples" 
targetNamespace="urn:samples"
+           elementFormDefault="qualified">
+
+  <xs:simpleType name="Level">
+    <xs:restriction base="xs:int">
+      <xs:enumeration value="3"/>
+      <xs:enumeration value="5"/>
+    </xs:restriction>
+  </xs:simpleType>
+  <xs:simpleType name="Color">
+    <xs:restriction base="xs:token">
+      <xs:enumeration value="red"/>
+      <xs:enumeration value="blue"/>
+    </xs:restriction>
+  </xs:simpleType>
+  <!-- the enumeration of the most derived type -->
+  <xs:simpleType name="DarkColor">
+    <xs:restriction base="t:Color">
+      <xs:enumeration value="blue"/>
+    </xs:restriction>
+  </xs:simpleType>
+
+  <xs:complexType name="Folder">
+    <xs:sequence>
+      <xs:element name="folder" type="t:Folder" minOccurs="0" 
maxOccurs="unbounded"/>
+    </xs:sequence>
+    <xs:attribute name="name" type="xs:NCName" use="required"/>
+  </xs:complexType>
+
+  <xs:element name="types">
+    <xs:complexType>
+      <xs:sequence>
+        <xs:element name="text" type="xs:string"/>
+        <xs:element name="token" type="xs:token"/>
+        <xs:element name="flag" type="xs:boolean"/>
+        <xs:element name="count" type="xs:int"/>
+        <xs:element name="big" type="xs:integer"/>
+        <xs:element name="positive" type="xs:positiveInteger"/>
+        <xs:element name="negative" type="xs:negativeInteger"/>
+        <xs:element name="nonPositive" type="xs:nonPositiveInteger"/>
+        <xs:element name="unsigned" type="xs:unsignedByte"/>
+        <xs:element name="amount" type="xs:decimal"/>
+        <xs:element name="ratio" type="xs:float"/>
+        <xs:element name="measure" type="xs:double"/>
+        <xs:element name="dateTime" type="xs:dateTime"/>
+        <xs:element name="date" type="xs:date"/>
+        <xs:element name="time" type="xs:time"/>
+        <xs:element name="duration" type="xs:duration"/>
+        <xs:element name="year" type="xs:gYear"/>
+        <xs:element name="yearMonth" type="xs:gYearMonth"/>
+        <xs:element name="month" type="xs:gMonth"/>
+        <xs:element name="monthDay" type="xs:gMonthDay"/>
+        <xs:element name="day" type="xs:gDay"/>
+        <xs:element name="base64" type="xs:base64Binary"/>
+        <xs:element name="hex" type="xs:hexBinary"/>
+        <xs:element name="uri" type="xs:anyURI"/>
+        <xs:element name="lang" type="xs:language"/>
+        <xs:element name="id" type="xs:ID"/>
+        <xs:element name="ncname" type="xs:NCName"/>
+        <xs:element name="tokens" type="xs:NMTOKENS"/>
+        <xs:element name="level" type="t:Level"/>
+        <xs:element name="color" type="t:Color"/>
+        <xs:element name="dark" type="t:DarkColor"/>
+        <xs:element name="levels">
+          <xs:simpleType><xs:list itemType="t:Level"/></xs:simpleType>
+        </xs:element>
+        <xs:choice>
+          <xs:element name="email" type="xs:string"/>
+          <xs:element name="phone" type="xs:string"/>
+        </xs:choice>
+        <xs:element name="optional" type="xs:string" minOccurs="0"/>
+        <xs:element name="item" type="xs:string" maxOccurs="unbounded"/>
+        <xs:element name="root" type="t:Folder"/>
+      </xs:sequence>
+      <xs:attribute name="version" type="xs:int" use="required"/>
+    </xs:complexType>
+  </xs:element>
+
+</xs:schema>

Reply via email to