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 e87f99ba8eae CAMEL-27397: camel-jbang - camel generate wsdl --samples:
a sample request and response per operation (#30614)
e87f99ba8eae is described below
commit e87f99ba8eae1d9ac906d66045fb497640bb1100
Author: Claus Ibsen <[email protected]>
AuthorDate: Sun Nov 22 21:27:46 2026 +0100
CAMEL-27397: camel-jbang - camel generate wsdl --samples: a sample request
and response per operation (#30614)
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.
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.
CAMEL-27397: XsdJsonSamples is AutoCloseable, and documents that a schema
that cannot be loaded fails
Addresses the review: close() stops the data format the samples are
written with, camel generate wsdl closes it, and the constructors document
the RuntimeCamelException of a schema that cannot be loaded.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Claus Ibsen <[email protected]>
---
.../camel/catalog/docs/xsdJson-dataformat.adoc | 18 ++
.../src/main/docs/xsdJson-dataformat.adoc | 18 ++
.../dataformat/xsdjson/XsdJsonDataFormat.java | 18 +-
.../camel/dataformat/xsdjson/XsdJsonSamples.java | 265 +++++++++++++++++++++
.../apache/camel/dataformat/xsdjson/XsdModel.java | 9 +-
.../camel/dataformat/xsdjson/XsdModelBuilder.java | 29 ++-
.../camel/dataformat/xsdjson/XsdSchemaLoader.java | 12 +
.../dataformat/xsdjson/XsdJsonSamplesTest.java | 183 ++++++++++++++
.../src/test/resources/xsdjson/samples.xsd | 99 ++++++++
.../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 | 181 +++++++++++++-
.../jbang/core/commands/generate/WsdlModel.java | 27 +++
.../jbang/core/commands/generate/WsdlSamples.java | 231 ++++++++++++++++++
.../commands/generate/CodeWsdlGeneratorTest.java | 165 +++++++++++++
17 files changed, 1269 insertions(+), 19 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..c63d6600fa71 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,24 @@ 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]
+----
+try (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..c63d6600fa71 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,24 @@ 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]
+----
+try (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 7a4b2f4a6acb..301e850460c9 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..86dcc210c527
--- /dev/null
+++
b/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdJsonSamples.java
@@ -0,0 +1,265 @@
+/*
+ * 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.RuntimeCamelException;
+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 implements AutoCloseable {
+
+ 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
+ * @throws RuntimeCamelException if the schema cannot be loaded, such as a
resource that does not exist or is not an
+ * XML Schema or a WSDL
+ */
+ 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)
+ * @throws RuntimeCamelException if the schema cannot be loaded, or the
reader refuses a document
+ */
+ 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;
+ }
+
+ /**
+ * Stops the data format that the samples are written with.
+ */
+ @Override
+ public void close() {
+ dataFormat.stop();
+ }
+
+ 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..3440d72bdc68
--- /dev/null
+++
b/components/camel-xsd-json/src/test/java/org/apache/camel/dataformat/xsdjson/XsdJsonSamplesTest.java
@@ -0,0 +1,183 @@
+/*
+ * 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.RuntimeCamelException;
+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 theSamplesAreClosed() throws Exception {
+ XsdJsonSamples samples;
+ try (XsdJsonSamples s = new XsdJsonSamples(context, SAMPLES)) {
+ samples = s;
+ assertThat(s.json("types")).contains("\"text\"");
+ }
+ // the model is kept, so a closed one still answers, as a stopped data
format does
+ assertThat(samples.json("types")).contains("\"text\"");
+ }
+
+ @Test
+ void aSchemaThatCannotBeLoaded() {
+ assertThatThrownBy(() -> new XsdJsonSamples(context,
"classpath:xsdjson/nope.xsd"))
+ .isInstanceOf(RuntimeCamelException.class);
+ }
+
+ @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>
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..1f6d881a4ac7 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,124 @@ 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));
+ }
+ try (xsd) {
+ 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 +418,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 +478,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 +493,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);