This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch CAMEL-27376-generate-wsdl in repository https://gitbox.apache.org/repos/asf/camel.git
commit 9bcf8dba40f02c6ecc1d086783a79dc3cff6ab38 Author: Claus Ibsen <[email protected]> AuthorDate: Sun Nov 22 10:15:51 2026 +0100 CAMEL-27376: camel-jbang - camel generate wsdl lists the services, ports and operations of a WSDL and scaffolds a cxf route The generate plugin gets a third subcommand, next to rest and schema. It reads a WSDL 1.1 document (a file or a http(s) URL) with SOAP 1.1 or SOAP 1.2 bindings, including wsdl:import, with the DOM parser of the JDK (no CXF, no wsdl4j). It lists each port (service, binding, SOAP version, style, address) and its operations (soapAction, request and response elements, faults) as a table, or as JSON with the cxf endpoint options of each port. With --route=consumer it scaffolds a cxf: consumer in PAYLOAD mode with a choice per operation, and with --route=producer a direct:<operation> route per operation that calls the service, in YAML and with no generated classes. The parser refuses a DOCTYPE and external entities, follows an import only with the scheme of the WSDL, and limits the number and depth of imports. Names must be NCNames and namespaces plain URIs before they go into the YAML, the user info of an address is masked in the listing and left out of the route, and the producer removes the Camel and CXF operation headers before the call. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Claus Ibsen <[email protected]> --- .../modules/ROOT/pages/camel-jbang-projects.adoc | 57 +- .../jbang-commands/camel-jbang-generate-wsdl.adoc | 34 + .../pages/jbang-commands/camel-jbang-generate.adoc | 1 + .../camel-jbang-plugin-commands-metadata.json | 2 +- .../core/commands/generate/CodeWsdlGenerator.java | 387 +++++++++++ .../core/commands/generate/GeneratePlugin.java | 3 +- .../jbang/core/commands/generate/WsdlModel.java | 739 +++++++++++++++++++++ .../core/commands/generate/WsdlRouteScaffold.java | 327 +++++++++ .../commands/generate/CodeWsdlGeneratorTest.java | 442 ++++++++++++ .../src/test/resources/wsdl/doctype.wsdl | 23 + .../wsdl/expected/orders-consumer.camel.yaml | 61 ++ .../wsdl/expected/orders-producer.camel.yaml | 61 ++ .../src/test/resources/wsdl/expected/orders.json | 57 ++ .../src/test/resources/wsdl/expected/orders.txt | 11 + .../src/test/resources/wsdl/multi-binding.wsdl | 59 ++ .../src/test/resources/wsdl/multi.wsdl | 48 ++ .../src/test/resources/wsdl/notify12.wsdl | 70 ++ .../src/test/resources/wsdl/orders.wsdl | 116 ++++ .../src/test/resources/wsdl/rpc.wsdl | 55 ++ .../test/resources/wsdl/types/multi-interface.wsdl | 53 ++ .../src/test/resources/wsdl/wsdl20.wsdl | 23 + 21 files changed, 2626 insertions(+), 3 deletions(-) diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-projects.adoc b/docs/user-manual/modules/ROOT/pages/camel-jbang-projects.adoc index 81cd7881f86b..c1a46b4d92c4 100644 --- a/docs/user-manual/modules/ROOT/pages/camel-jbang-projects.adoc +++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-projects.adoc @@ -395,7 +395,7 @@ The plugins of the Apache Camel project: | kubernetes | `camel kubernetes`: deploy to Kubernetes, see xref:camel-jbang-kubernetes.adoc[Kubernetes Plugin] | test | `camel test`: Citrus tests, see xref:camel-jbang-test.adoc[Testing Plugin] | validate | `camel validate`: check source files, see xref:camel-jbang-validation.adoc[Validation] -| generate | `camel generate`: REST DSL and DTOs from OpenAPI, JSON schemas (see below) +| generate | `camel generate`: REST DSL and DTOs from OpenAPI, cxf routes from a WSDL, JSON schemas (see below) | tui | `camel tui`: the xref:camel-jbang-tui.adoc[Camel TUI] | mcp | `camel mcp`: the xref:camel-jbang-mcp.adoc[Camel CLI MCP Server] | edit | `camel edit`: edit a Camel file in the terminal with suggestions and diagnostics @@ -560,6 +560,61 @@ camel generate rest --input=petstore.yaml --dto --runtime=quarkus --package=com. for the schemas of the specification. Each generated route has a `log` step that says it is not implemented yet: the routes run as they are (`camel run petstore-rest.yaml`), and you replace that step with the implementation. +=== SOAP routes from a WSDL + +List the services, ports and operations of a WSDL 1.1 document (a file or a http(s) URL) with SOAP 1.1 or SOAP 1.2 +bindings: + +[source,bash] +---- +camel generate wsdl orders.wsdl +camel generate wsdl http://localhost:8080/orders?wsdl --json +---- + +The listing has a block per port (the service, port, binding, SOAP version, style, address and namespace), and a row per +operation with its SOAP action, request and response elements, and faults: + +[source,text] +---- +SERVICE OrderService +PORT OrderPort +BINDING OrderSoapBinding +SOAP 1.1 +STYLE document/literal +ADDRESS http://localhost:18081/orders +NAMESPACE http://example.com/orders + + OPERATION SOAP ACTION INPUT OUTPUT FAULTS + getOrder http://example.com/orders/getOrder getOrder getOrderResponse orderNotFound + placeOrder http://example.com/orders/placeOrder placeOrder placeOrderResponse +---- + +With `--json`, each port also has the values of the xref:components::cxf-component.adoc[CXF] endpoint options +(`serviceName`, `portName`, `wsdlURL`, `address` and `defaultOperationNamespace`), ready to copy into a route or a +Kamelet. The user info of an address (`user:password@`) is masked. + +`--route` scaffolds a YAML route in `PAYLOAD` mode, which needs no generated Java classes: + +[source,bash] +---- +camel generate wsdl orders.wsdl --route=consumer --output=orders-service.camel.yaml +camel generate wsdl orders.wsdl --route=producer --operation=getOrder --output=orders-client.camel.yaml +---- + +* `consumer` is a SOAP service: a `cxf:` consumer with schema validation, and a `choice` with a `when` per operation +(on the `CamelCxfOperationName` header) that logs the request and returns a placeholder response element. The response +is validated against the schema too, so until you fill in the placeholder the caller gets a SOAP fault that names the +first element it misses. With `--runtime=camel-main` (the default) the consumer listens on `0.0.0.0` and the port and +path of the address of the WSDL, so `camel run` serves it as it is; with `spring-boot` or `quarkus` it uses the path, +which the CXF servlet of the runtime serves. +* `producer` is a SOAP client: a route `direct:<operation>` per operation, which takes the request element (XML) as +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`). + +When the WSDL has more than one port, choose one with `--service` and `--port`. A remote WSDL may only import documents +over http(s), and a local one only files. The rpc style is listed but not scaffolded, and WSDL 2.0 and bindings that are +not SOAP (such as HTTP GET) are not supported. + === JSON schema Generate JSON Schema definitions from Java objects for use with visual development tools (Kaoto, Karavan): 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 new file mode 100644 index 000000000000..7f0d92ce3525 --- /dev/null +++ b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-generate-wsdl.adoc @@ -0,0 +1,34 @@ + +// AUTO-GENERATED by camel-package-maven-plugin - DO NOT EDIT THIS FILE += camel generate wsdl + +List the services, ports and operations of a WSDL, or scaffold a cxf route in PAYLOAD mode + +NOTE: This command is provided by the `generate` plugin. Install it with `camel plugin add generate`. + + +== Usage + +[source,bash] +---- +camel generate wsdl [options] +---- + + + +== Options + +[cols="2,5,1,2",options="header"] +|=== +| 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 +| `--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 +| `--runtime` | The runtime the route is for (camel-main, spring-boot, quarkus): camel-main listens on the address of the WSDL, spring-boot and quarkus on its path in their CXF servlet | camel-main | RuntimeType +| `--service` | The service (its name), when the WSDL has more than one | | String +| `-h,--help` | Display this help and exit | | boolean +|=== + + diff --git a/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-generate.adoc b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-generate.adoc index 13ba2faf3c1e..60945008e629 100644 --- a/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-generate.adoc +++ b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-generate.adoc @@ -22,6 +22,7 @@ camel generate [options] | Subcommand | Description | xref:jbang-commands/camel-jbang-generate-rest.adoc[rest] | Generate REST DSL source code from OpenApi specification | xref:jbang-commands/camel-jbang-generate-schema.adoc[schema] | Create a JSON schema for a given Camel component and Java Object +| xref:jbang-commands/camel-jbang-generate-wsdl.adoc[wsdl] | List the services, ports and operations of a WSDL, or scaffold a cxf route in PAYLOAD mode |=== 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 1d2b340b9f62..c5d970b845ae 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 new file mode 100644 index 000000000000..8ce42862a2f9 --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/CodeWsdlGenerator.java @@ -0,0 +1,387 @@ +/* + * 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.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; + +import javax.xml.namespace.QName; + +import com.github.freva.asciitable.AsciiTable; +import com.github.freva.asciitable.Column; +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.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.common.CliExitCode; +import org.apache.camel.dsl.jbang.core.common.CompletionCandidates; +import org.apache.camel.dsl.jbang.core.common.JsonOutput; +import org.apache.camel.dsl.jbang.core.common.RuntimeCompletionCandidates; +import org.apache.camel.dsl.jbang.core.common.RuntimeTypeConverter; +import org.apache.camel.dsl.jbang.run.common.RuntimeType; +import org.apache.camel.util.json.JsonArray; +import org.apache.camel.util.json.JsonObject; + +/** + * Lists the services, ports and operations of a WSDL 1.1 document (SOAP 1.1 and SOAP 1.2 bindings), and scaffolds a + * YAML route with a cxf: consumer or cxf: producers in PAYLOAD mode, which needs no generated classes. + * <p/> + * Exit codes: 0 success, 1 the WSDL cannot be read or scaffolded, 2 invalid options, 3 an unknown service, port or + * operation, 66 the WSDL file does not exist. + */ +@CommandDefinition(name = "wsdl", + description = "List the services, ports and operations of a WSDL, or scaffold a cxf route in PAYLOAD mode", + generateHelp = true, sortOptions = true, + footer = { + "Examples:", + " 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 http://localhost:8080/orders?wsdl --route=producer --operation=getOrder" }) +public class CodeWsdlGenerator extends CamelCommand { + + public static class RouteCompletionCandidates extends CompletionCandidates { + + public RouteCompletionCandidates() { + } + + @Override + public Iterator<String> iterator() { + return List.of("consumer", "producer").iterator(); + } + } + + @Argument(paramLabel = "wsdl", index = "0", required = true, + description = "The WSDL: a file or a http(s) URL") + String wsdl; + + @Option(name = "json", hasValue = false, + description = "Output the services, ports and operations in JSON Format, with the cxf endpoint options of each port") + boolean jsonOutput; + + @Option(name = "route", description = "Scaffold a YAML route (consumer or producer) instead of listing the WSDL", + completer = RouteCompletionCandidates.class) + String route; + + @Option(name = "output", description = "The file to write the route to (default: stdout)") + String output; + + @Option(name = "service", description = "The service (its name), when the WSDL has more than one") + String service; + + @Option(name = "port", description = "The port (its name), when the service has more than one") + String port; + + @Option(name = "operation", description = "The operations to list or scaffold (use commas to separate them; default: all)") + String operation; + + @Option(name = "runtime", + description = "The runtime the route is for (${COMPLETION-CANDIDATES}): camel-main listens on the address of" + + " the WSDL, spring-boot and quarkus on its path in their CXF servlet", + defaultValue = "camel-main", + completer = RuntimeCompletionCandidates.class, converter = RuntimeTypeConverter.class) + RuntimeType runtime = RuntimeType.main; + + @Override + public boolean isJsonOutput() { + return jsonOutput; + } + + @Override + public Integer doCall() throws Exception { + if (route != null && !"consumer".equals(route) && !"producer".equals(route)) { + return error(CliExitCode.USAGE, "Unknown route: " + route + " (supported: consumer, producer)"); + } + 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"); + } + + WsdlModel model; + try { + model = WsdlModel.load(wsdl); + } catch (NoSuchFileException e) { + return error(CliExitCode.FILE_NOT_FOUND, "WSDL file " + e.getMessage() + " does not exist"); + } catch (WsdlException e) { + return error(CliExitCode.FAILURE, e.getMessage()); + } catch (IOException e) { + return error(CliExitCode.FAILURE, "Cannot read the WSDL " + wsdl + ": " + e.getMessage()); + } + for (String warning : model.warnings()) { + printer().printWarn(warning); + } + + // the services, ports and operations chosen with --service, --port and --operation + List<Service> services = new ArrayList<>(); + for (Service s : model.services()) { + if (service == null || matches(s.name(), service)) { + List<Port> ports = new ArrayList<>(); + for (Port p : s.ports()) { + if (port == null || matches(p.qname(), port)) { + ports.add(p); + } + } + if (!ports.isEmpty()) { + services.add(new Service(s.name(), ports)); + } + } + } + if (service != null && model.services().stream().noneMatch(s -> matches(s.name(), service))) { + return error(CliExitCode.NOT_FOUND, "Unknown service: " + service + " (the services of the WSDL: " + + String.join(", ", model.services().stream() + .map(s -> s.name().getLocalPart()).toList()) + + ")"); + } + if (services.isEmpty()) { + return error(CliExitCode.NOT_FOUND, "Unknown port: " + port + " (the ports of the WSDL: " + + String.join(", ", allPorts(model.services()).stream() + .map(Port::name).toList()) + + ")"); + } + List<String> operations = operation != null + ? Arrays.stream(operation.split(",")).map(String::trim).filter(o -> !o.isEmpty()).toList() + : List.of(); + for (String op : operations) { + boolean known = allPorts(services).stream() + .anyMatch(p -> p.operations().stream().anyMatch(o -> o.name().equals(op))); + if (!known) { + return error(CliExitCode.NOT_FOUND, "Unknown operation: " + op + " (the operations: " + + String.join(", ", allPorts(services).stream() + .flatMap(p -> p.operations().stream()) + .map(Operation::name).distinct().toList()) + + ")"); + } + } + + if (route == null) { + if (jsonOutput) { + JsonOutput.print(printer(), toJson(model, services, operations)); + } else { + printTable(services, operations); + } + return CliExitCode.OK; + } + return scaffold(services, operations); + } + + private int scaffold(List<Service> services, List<String> operations) throws IOException { + List<Port> ports = allPorts(services); + if (ports.size() > 1) { + StringBuilder sb = new StringBuilder("The WSDL has more than one port: choose one with"); + for (Port p : ports) { + sb.append(" --service=").append(p.service().getLocalPart()).append(" --port=").append(p.name()) + .append(" (SOAP ").append(p.soapVersion()).append(')').append(','); + } + sb.setLength(sb.length() - 1); + return error(CliExitCode.USAGE, sb.toString()); + } + Port p = ports.get(0); + WsdlRouteScaffold scaffold = new WsdlRouteScaffold(p, selected(p, operations), wsdlUrl()); + String yaml; + try { + yaml = "consumer".equals(route) ? scaffold.consumer(runtime) : scaffold.producer(); + } catch (WsdlException e) { + return error(CliExitCode.FAILURE, e.getMessage()); + } + for (String warning : scaffold.warnings()) { + printer().printWarn(warning); + } + if (output == null) { + printer().print(yaml); + } else { + Files.writeString(Path.of(output), yaml, StandardCharsets.UTF_8); + } + return CliExitCode.OK; + } + + /** + * The wsdlURL of the endpoints: the WSDL as it was given, with file: in front of a file name. + */ + String wsdlUrl() { + String lower = wsdl.toLowerCase(Locale.ROOT); + if (lower.startsWith("http://") || lower.startsWith("https://") || lower.startsWith("file:")) { + return wsdl; + } + return "file:" + wsdl; + } + + private void printTable(List<Service> services, List<String> operations) { + boolean first = true; + for (Port p : allPorts(services)) { + if (!first) { + printer().println(); + } + first = false; + String ns = p.namespace(); + List<String[]> block = List.of( + new String[] { "SERVICE", p.service().getLocalPart() }, + new String[] { "PORT", p.name() }, + new String[] { "BINDING", p.binding().getLocalPart() }, + new String[] { "SOAP", p.soapVersion() }, + new String[] { + "STYLE", p.style() + "/" + p.operations().stream().map(Operation::use).findFirst() + .orElse("literal") }, + new String[] { "ADDRESS", p.address() != null ? WsdlModel.maskedAddress(p.address()) : "" }, + new String[] { "NAMESPACE", ns }); + for (String[] row : block) { + printer().println(String.format("%-10s %s", row[0], WsdlModel.printable(row[1]))); + } + List<Operation> ops = selected(p, operations); + if (ops.isEmpty()) { + continue; + } + printer().println(); + printer().println(AsciiTable.getTable(AsciiTable.NO_BORDERS, ops, Arrays.asList( + new Column().header("OPERATION").headerAlign(HorizontalAlign.LEFT).dataAlign(HorizontalAlign.LEFT) + .with(o -> WsdlModel.printable(o.name())), + new Column().header("SOAP ACTION").headerAlign(HorizontalAlign.LEFT).dataAlign(HorizontalAlign.LEFT) + .with(o -> WsdlModel.printable(o.soapAction() != null ? o.soapAction() : "")), + new Column().header("INPUT").headerAlign(HorizontalAlign.LEFT).dataAlign(HorizontalAlign.LEFT) + .with(o -> WsdlModel.printable(shortName(o.input(), ns))), + new Column().header("OUTPUT").headerAlign(HorizontalAlign.LEFT).dataAlign(HorizontalAlign.LEFT) + .with(o -> WsdlModel.printable(o.oneWay() ? "(one-way)" : shortName(o.output(), ns))), + new Column().header("FAULTS").headerAlign(HorizontalAlign.LEFT).dataAlign(HorizontalAlign.LEFT) + .with(o -> WsdlModel.printable( + String.join(", ", o.faults().stream().map(Fault::name).toList())))))); + } + } + + /** + * The local name of an element in the namespace of the port, else {namespace}name. + */ + private static String shortName(QName name, String namespace) { + if (name == null) { + return ""; + } + return name.getNamespaceURI().equals(namespace) ? name.getLocalPart() : name.toString(); + } + + private JsonObject toJson(WsdlModel model, List<Service> services, List<String> operations) { + JsonObject root = new JsonObject(); + root.put("wsdl", wsdl); + root.put("targetNamespace", model.targetNamespace()); + JsonArray sa = new JsonArray(); + for (Service s : services) { + JsonObject so = new JsonObject(); + so.put("name", s.name().getLocalPart()); + so.put("namespace", s.name().getNamespaceURI()); + JsonArray pa = new JsonArray(); + for (Port p : s.ports()) { + String address = WsdlModel.maskedAddress(p.address()); + JsonObject po = new JsonObject(); + po.put("name", p.name()); + po.put("binding", p.binding().toString()); + po.put("soapVersion", p.soapVersion()); + po.put("style", p.style()); + if (p.transport() != null && !p.transport().isEmpty()) { + po.put("transport", p.transport()); + } + if (address != null) { + po.put("address", address); + } + po.put("namespace", p.namespace()); + JsonObject cxf = new JsonObject(); + cxf.put("serviceName", p.service().toString()); + cxf.put("portName", p.qname().toString()); + cxf.put("wsdlURL", wsdlUrl()); + if (address != null) { + cxf.put("address", address); + } + cxf.put("defaultOperationNamespace", p.namespace()); + po.put("cxf", cxf); + JsonArray oa = new JsonArray(); + for (Operation o : selected(p, operations)) { + JsonObject oo = new JsonObject(); + oo.put("name", o.name()); + if (o.soapAction() != null) { + oo.put("soapAction", o.soapAction()); + } + oo.put("style", o.style()); + oo.put("use", o.use()); + oo.put("oneWay", o.oneWay()); + if (o.input() != null) { + oo.put("input", o.input().toString()); + } + if (o.output() != null) { + oo.put("output", o.output().toString()); + } + JsonArray fa = new JsonArray(); + for (Fault f : o.faults()) { + JsonObject fo = new JsonObject(); + fo.put("name", f.name()); + if (f.element() != null) { + fo.put("element", f.element().toString()); + } + fa.add(fo); + } + oo.put("faults", fa); + oa.add(oo); + } + po.put("operations", oa); + pa.add(po); + } + so.put("ports", pa); + sa.add(so); + } + root.put("services", sa); + return root; + } + + private static List<Operation> selected(Port p, List<String> operations) { + if (operations.isEmpty()) { + return p.operations(); + } + return p.operations().stream().filter(o -> operations.contains(o.name())).toList(); + } + + private static List<Port> allPorts(List<Service> services) { + return services.stream().flatMap(s -> s.ports().stream()).toList(); + } + + /** + * Whether the name of the option matches the name: its local name, or {namespace}name. + */ + private static boolean matches(QName name, String option) { + return option.equals(name.getLocalPart()) || option.equals(name.toString()); + } + + private int error(int code, String message) { + // the message may have values of a remote WSDL + message = WsdlModel.printable(message); + printer().printErr(message); + if (jsonOutput) { + JsonOutput.printError(printer(), code, message); + } + return code; + } +} diff --git a/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/GeneratePlugin.java b/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/GeneratePlugin.java index 25e3399fcb8c..079a78d87a07 100644 --- a/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/GeneratePlugin.java +++ b/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/GeneratePlugin.java @@ -28,7 +28,8 @@ public class GeneratePlugin implements Plugin { public void customize(CommandTree commandLine, CamelJBangMain main) { var cmd = new CommandTree(main.command(new CodeGenerator())) .addSubcommand("rest", new CommandTree(main.command(new CodeRestGenerator()))) - .addSubcommand("schema", new CommandTree(main.command(new CodeSchemaGenerator()))); + .addSubcommand("schema", new CommandTree(main.command(new CodeSchemaGenerator()))) + .addSubcommand("wsdl", new CommandTree(main.command(new CodeWsdlGenerator()))); commandLine.addSubcommand("generate", cmd); } 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 new file mode 100644 index 000000000000..c35323e32eb6 --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/WsdlModel.java @@ -0,0 +1,739 @@ +/* + * 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.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.ProxySelector; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import org.xml.sax.ErrorHandler; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +/** + * The services, ports and operations of a WSDL 1.1 document with SOAP 1.1 or SOAP 1.2 bindings, read with the DOM + * parser of the JDK. Only the WSDL structure is read: the XML schema of the types is not. + * <p/> + * The WSDL may come from a remote server, so the parser refuses a DOCTYPE and never loads an external entity, and a + * {@code wsdl:import} is only followed with the same scheme as the WSDL that imports it (a remote WSDL cannot import a + * local file), for at most {@link #MAX_DOCUMENTS} documents and {@link #MAX_DEPTH} levels. + */ +final class WsdlModel { + + static final String WSDL_NS = "http://schemas.xmlsoap.org/wsdl/"; + static final String WSDL2_NS = "http://www.w3.org/ns/wsdl"; + static final String SOAP11_NS = "http://schemas.xmlsoap.org/wsdl/soap/"; + static final String SOAP12_NS = "http://schemas.xmlsoap.org/wsdl/soap12/"; + + static final int MAX_DOCUMENTS = 32; + static final int MAX_DEPTH = 8; + static final int MAX_BYTES = 16 * 1024 * 1024; + + /** + * An NCName (the type of the name attributes of WSDL 1.1): no colon, no space, no quote, no $ or brace, so it can + * go into YAML and into a simple expression as it is. + */ + private static final Pattern NCNAME = Pattern.compile("[\\p{L}_][\\p{L}\\p{M}\\p{N}._\\-]*"); + + /** + * The user info of an address, such as user:password@ in http://user:password@host/path. + */ + private static final Pattern USER_INFO = Pattern.compile("^([A-Za-z][A-Za-z0-9+.-]*://)[^/?#@]*@"); + + /** + * A fault of an operation. + * + * @param name the name of the fault + * @param element the element of the fault detail, or <tt>null</tt> + */ + record Fault(String name, QName element) { + } + + /** + * An operation of a port. + * + * @param name the name of the operation + * @param namespace the namespace of the operation (of its port type), as the defaultOperationNamespace of cxf + * @param soapAction the SOAP action, or <tt>null</tt> + * @param style document or rpc + * @param use literal or encoded + * @param input the element of the request, or for rpc the wrapper element, or <tt>null</tt> + * @param output the element of the response, or <tt>null</tt> for a one-way operation + * @param oneWay whether the operation has no response + * @param faults the faults + */ + record Operation( + String name, String namespace, String soapAction, String style, String use, QName input, QName output, + boolean oneWay, List<Fault> faults) { + } + + /** + * A SOAP port of a service. + * + * @param service the name of the service + * @param name the name of the port + * @param binding the name of the binding + * @param soapVersion 1.1 or 1.2 + * @param style the default style of the binding: document or rpc + * @param transport the transport of the binding + * @param address the address of the port as the WSDL has it, or <tt>null</tt> + * @param namespace the namespace of the port type, which is the namespace of the operations + * @param operations the operations + */ + record Port( + QName service, String name, QName binding, String soapVersion, String style, String transport, String address, + String namespace, List<Operation> operations) { + + QName qname() { + return new QName(service.getNamespaceURI(), name); + } + + /** + * Whether the operations are all document style (rpc is listed, but not scaffolded). + */ + boolean isDocument() { + return operations.stream().allMatch(o -> "document".equals(o.style())); + } + } + + /** + * A service. + * + * @param name the name + * @param ports the SOAP ports + */ + record Service(QName name, List<Port> ports) { + } + + /** + * The WSDL cannot be read: it is not well formed, not WSDL 1.1, has a DOCTYPE, refers to something it does not + * define, or imports a document that cannot be read. + */ + static final class WsdlException extends Exception { + WsdlException(String message) { + super(message); + } + + WsdlException(String message, Throwable cause) { + super(message, cause); + } + } + + private record Part(String name, QName element, QName type) { + } + + private record PortTypeOperation(String name, QName input, QName output, List<Fault> faults) { + } + + private record PortType(QName name, Map<String, PortTypeOperation> operations) { + } + + private record BindingOperation(String name, String soapAction, String style, String use, List<String> bodyParts, + String rpcNamespace) { + } + + private record Binding( + QName name, QName type, String soapVersion, String style, String transport, + Map<String, BindingOperation> operations) { + } + + private record RawPort(String name, QName binding, String address, boolean soapAddress) { + } + + private record RawService(QName name, List<RawPort> ports) { + } + + private final String targetNamespace; + private final List<Service> services; + private final List<String> warnings; + + private WsdlModel(String targetNamespace, List<Service> services, List<String> warnings) { + this.targetNamespace = targetNamespace; + this.services = services; + this.warnings = warnings; + } + + /** + * The target namespace of the WSDL (of the first document). + */ + String targetNamespace() { + return targetNamespace; + } + + /** + * The services with at least one SOAP port, in the order of the WSDL. + */ + List<Service> services() { + return services; + } + + /** + * What was left out, such as a port with a binding that is not SOAP. + */ + List<String> warnings() { + return warnings; + } + + /** + * The location of a WSDL as a URI: a http or https URL, a file: URL, or a file name. + */ + static URI toUri(String location) { + String lower = location.toLowerCase(Locale.ROOT); + if (lower.startsWith("http://") || lower.startsWith("https://") || lower.startsWith("file:")) { + return URI.create(location); + } + return Path.of(location).toAbsolutePath().normalize().toUri(); + } + + /** + * Reads the WSDL and the WSDL documents it imports. + * + * @param location a http or https URL, a file: URL, or a file name + * @throws NoSuchFileException when the WSDL is a file that does not exist + * @throws IOException when the WSDL cannot be read + * @throws WsdlException when the WSDL, or a document it imports, is not a WSDL 1.1 document this can read + */ + static WsdlModel load(String location) throws IOException, WsdlException { + URI base; + try { + base = toUri(location); + } catch (IllegalArgumentException e) { + throw new WsdlException("Not a file or URL: " + location, e); + } + String scheme = base.getScheme() != null ? base.getScheme().toLowerCase(Locale.ROOT) : ""; + if (!"file".equals(scheme) && !"http".equals(scheme) && !"https".equals(scheme)) { + throw new WsdlException("Not a file or http(s) URL: " + location); + } + Reader reader = new Reader(scheme); + reader.read(base, 0); + return reader.build(); + } + + /** + * Whether the name is an NCName, which can go into YAML and into a simple expression as it is. + */ + static boolean isNcName(String name) { + return name != null && NCNAME.matcher(name).matches(); + } + + private static final class Reader { + private final String scheme; + private final Set<URI> visited = new HashSet<>(); + private String targetNamespace; + private final Map<QName, List<Part>> messages = new LinkedHashMap<>(); + private final Map<QName, PortType> portTypes = new LinkedHashMap<>(); + private final Map<QName, Binding> bindings = new LinkedHashMap<>(); + private final List<RawService> rawServices = new ArrayList<>(); + private final List<String> warnings = new ArrayList<>(); + + Reader(String scheme) { + this.scheme = scheme; + } + + void read(URI uri, int depth) throws IOException, WsdlException { + URI normalized = uri.normalize(); + if (!visited.add(normalized)) { + // imported twice, or an import cycle + return; + } + if (visited.size() > MAX_DOCUMENTS) { + throw new WsdlException("The WSDL imports more than " + MAX_DOCUMENTS + " documents"); + } + Document doc = parse(normalized, readBytes(normalized)); + Element root = doc.getDocumentElement(); + if (WSDL2_NS.equals(root.getNamespaceURI())) { + throw new WsdlException( + "WSDL 2.0 is not supported (only WSDL 1.1 with SOAP 1.1 or SOAP 1.2 bindings): " + normalized); + } + if (!WSDL_NS.equals(root.getNamespaceURI()) || !"definitions".equals(root.getLocalName())) { + throw new WsdlException("Not a WSDL 1.1 document (the root element is not wsdl:definitions): " + normalized); + } + String tns = root.getAttribute("targetNamespace"); + if (targetNamespace == null) { + targetNamespace = tns; + } + + for (Element e : children(root, WSDL_NS)) { + switch (e.getLocalName()) { + case "import" -> readImport(normalized, e, depth); + case "message" -> readMessage(tns, e); + case "portType" -> readPortType(tns, e); + case "binding" -> readBinding(tns, e); + case "service" -> readService(tns, e); + default -> { + // types and documentation: not needed for the listing + } + } + } + } + + private void readImport(URI base, Element e, int depth) throws IOException, WsdlException { + String location = e.getAttribute("location"); + if (location.isBlank()) { + return; + } + if (depth + 1 > MAX_DEPTH) { + throw new WsdlException("The imports of the WSDL are nested deeper than " + MAX_DEPTH + " levels"); + } + URI imported; + try { + imported = base.resolve(new URI(location.trim())); + } catch (URISyntaxException ex) { + throw new WsdlException("The import location " + location + " of " + base + " is not a valid URI", ex); + } + String importScheme = imported.getScheme() != null ? imported.getScheme().toLowerCase(Locale.ROOT) : ""; + if (!scheme.equals(importScheme)) { + throw new WsdlException( + "The import " + location + " of " + base + " is not followed: its scheme (" + importScheme + + ") is not the scheme of the WSDL (" + scheme + ")"); + } + read(imported, depth + 1); + } + + private void readMessage(String tns, Element e) throws WsdlException { + List<Part> parts = new ArrayList<>(); + for (Element p : children(e, WSDL_NS, "part")) { + parts.add(new Part(p.getAttribute("name"), qname(p, "element"), qname(p, "type"))); + } + messages.put(new QName(tns, name(e, "message")), parts); + } + + private void readPortType(String tns, Element e) throws WsdlException { + Map<String, PortTypeOperation> operations = new LinkedHashMap<>(); + for (Element op : children(e, WSDL_NS, "operation")) { + String name = name(op, "operation"); + QName input = null; + QName output = null; + boolean inputFirst = false; + List<Fault> faults = new ArrayList<>(); + for (Element c : children(op, WSDL_NS)) { + switch (c.getLocalName()) { + case "input" -> { + input = qname(c, "message"); + inputFirst = output == null; + } + case "output" -> output = qname(c, "message"); + case "fault" -> faults.add(new Fault(name(c, "fault"), qname(c, "message"))); + default -> { + // documentation + } + } + } + if (input == null || !inputFirst) { + warnings.add("The operation " + name + " is left out: notification and solicit-response operations " + + "are not supported"); + continue; + } + // an overloaded operation (same name, other input or output names) is listed once + operations.putIfAbsent(name, new PortTypeOperation(name, input, output, faults)); + } + QName qn = new QName(tns, name(e, "portType")); + portTypes.put(qn, new PortType(qn, operations)); + } + + private void readBinding(String tns, Element e) throws WsdlException { + QName qn = new QName(tns, name(e, "binding")); + QName type = qname(e, "type"); + String soapVersion = null; + String style = "document"; + String transport = null; + Element soapBinding = first(e, SOAP11_NS, "binding"); + String soapNs = SOAP11_NS; + if (soapBinding != null) { + soapVersion = "1.1"; + } else { + soapBinding = first(e, SOAP12_NS, "binding"); + soapNs = SOAP12_NS; + if (soapBinding != null) { + soapVersion = "1.2"; + } + } + if (soapBinding != null) { + if (!soapBinding.getAttribute("style").isBlank()) { + style = soapBinding.getAttribute("style"); + } + transport = soapBinding.getAttribute("transport"); + } + Map<String, BindingOperation> operations = new LinkedHashMap<>(); + for (Element op : children(e, WSDL_NS, "operation")) { + String name = name(op, "operation"); + String soapAction = null; + String opStyle = style; + Element soapOp = first(op, soapNs, "operation"); + if (soapOp != null) { + if (soapOp.hasAttribute("soapAction")) { + soapAction = soapOp.getAttribute("soapAction"); + } + if (!soapOp.getAttribute("style").isBlank()) { + opStyle = soapOp.getAttribute("style"); + } + } + String use = "literal"; + List<String> bodyParts = null; + String rpcNamespace = null; + Element input = first(op, WSDL_NS, "input"); + Element body = input != null ? first(input, soapNs, "body") : null; + if (body != null) { + if (!body.getAttribute("use").isBlank()) { + use = body.getAttribute("use"); + } + if (body.hasAttribute("parts")) { + bodyParts = List.of(body.getAttribute("parts").trim().split("\\s+")); + } + if (!body.getAttribute("namespace").isBlank()) { + rpcNamespace = body.getAttribute("namespace"); + } + } + operations.putIfAbsent(name, new BindingOperation(name, soapAction, opStyle, use, bodyParts, rpcNamespace)); + } + bindings.put(qn, new Binding(qn, type, soapVersion, style, transport, operations)); + } + + private void readService(String tns, Element e) throws WsdlException { + QName qn = new QName(tns, name(e, "service")); + List<RawPort> ports = new ArrayList<>(); + for (Element p : children(e, WSDL_NS, "port")) { + String address = null; + boolean soap = false; + for (Element a : children(p, null)) { + if ("address".equals(a.getLocalName())) { + address = a.getAttribute("location"); + soap = SOAP11_NS.equals(a.getNamespaceURI()) || SOAP12_NS.equals(a.getNamespaceURI()); + break; + } + } + ports.add(new RawPort(name(p, "port"), qname(p, "binding"), address, soap)); + } + rawServices.add(new RawService(qn, ports)); + } + + WsdlModel build() throws WsdlException { + List<Service> services = new ArrayList<>(); + for (RawService rs : rawServices) { + List<Port> ports = new ArrayList<>(); + for (RawPort rp : rs.ports()) { + Binding binding = bindings.get(rp.binding()); + if (binding == null) { + throw new WsdlException( + "The port " + rp.name() + " of the service " + rs.name().getLocalPart() + + " refers to the binding " + rp.binding() + + ", which the WSDL does not define"); + } + if (binding.soapVersion() == null) { + warnings.add("The port " + rp.name() + " of the service " + rs.name().getLocalPart() + + " is left out: its binding " + binding.name().getLocalPart() + + " is not a SOAP 1.1 or SOAP 1.2 binding"); + continue; + } + PortType portType = portTypes.get(binding.type()); + if (portType == null) { + throw new WsdlException( + "The binding " + binding.name().getLocalPart() + " refers to the port type " + binding.type() + + ", which the WSDL does not define"); + } + ports.add(new Port( + rs.name(), rp.name(), binding.name(), binding.soapVersion(), binding.style(), + binding.transport(), rp.address(), portType.name().getNamespaceURI(), + operations(binding, portType))); + } + if (!ports.isEmpty()) { + services.add(new Service(rs.name(), ports)); + } + } + if (services.isEmpty()) { + throw new WsdlException("The WSDL has no service with a SOAP 1.1 or SOAP 1.2 port"); + } + return new WsdlModel(targetNamespace, services, warnings); + } + + private List<Operation> operations(Binding binding, PortType portType) throws WsdlException { + List<Operation> answer = new ArrayList<>(); + // in the order of the port type + for (PortTypeOperation pto : portType.operations().values()) { + BindingOperation bo = binding.operations().get(pto.name()); + if (bo == null) { + // not bound: it cannot be called on this port + continue; + } + boolean rpc = "rpc".equals(bo.style()); + String namespace = portType.name().getNamespaceURI(); + QName input; + QName output = null; + if (rpc) { + // the wrapper elements of rpc: the operation name, and the operation name with Response + String ns = bo.rpcNamespace() != null ? bo.rpcNamespace() : namespace; + input = new QName(ns, pto.name()); + if (pto.output() != null) { + output = new QName(ns, pto.name() + "Response"); + } + } else { + input = element(pto.input(), bo.bodyParts()); + if (pto.output() != null) { + output = element(pto.output(), null); + } + } + List<Fault> faults = new ArrayList<>(); + for (Fault f : pto.faults()) { + faults.add(new Fault(f.name(), element(f.element(), null))); + } + answer.add(new Operation( + pto.name(), namespace, bo.soapAction(), bo.style(), bo.use(), input, output, pto.output() == null, + faults)); + } + return answer; + } + + /** + * The element of the body of a message (the first part with an element, or with a type). + */ + private QName element(QName message, List<String> bodyParts) throws WsdlException { + List<Part> parts = messages.get(message); + if (parts == null) { + throw new WsdlException("The message " + message + " is not defined in the WSDL"); + } + for (Part p : parts) { + if (bodyParts != null && !bodyParts.contains(p.name())) { + // a soap:header part + continue; + } + if (p.element() != null) { + return p.element(); + } + if (p.type() != null) { + return p.type(); + } + } + return null; + } + + private byte[] readBytes(URI uri) throws IOException, WsdlException { + if ("file".equalsIgnoreCase(uri.getScheme())) { + Path path = Path.of(uri); + if (!Files.isRegularFile(path)) { + throw new NoSuchFileException(path.toString()); + } + if (Files.size(path) > MAX_BYTES) { + throw new WsdlException("The WSDL " + uri + " is larger than " + MAX_BYTES + " bytes"); + } + return Files.readAllBytes(path); + } + HttpClient client = HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(10)) + // never from https to http + .followRedirects(HttpClient.Redirect.NORMAL) + .proxy(ProxySelector.getDefault()) + .build(); + HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(30)).GET().build(); + try { + HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream()); + try (InputStream is = response.body()) { + if (response.statusCode() != 200) { + throw new IOException("HTTP " + response.statusCode() + " from " + uri); + } + return readLimited(uri, is); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Interrupted while reading " + uri, e); + } finally { + client.close(); + } + } + + private static byte[] readLimited(URI uri, InputStream is) throws IOException, WsdlException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + byte[] buffer = new byte[8192]; + int n; + while ((n = is.read(buffer)) != -1) { + bos.write(buffer, 0, n); + if (bos.size() > MAX_BYTES) { + throw new WsdlException("The WSDL " + uri + " is larger than " + MAX_BYTES + " bytes"); + } + } + return bos.toByteArray(); + } + + private static Document parse(URI uri, byte[] data) throws WsdlException { + try { + DocumentBuilder db = documentBuilder(); + return db.parse(new ByteArrayInputStream(data), uri.toString()); + } catch (SAXException e) { + String message = e.getMessage() != null ? e.getMessage() : e.toString(); + if (message.contains("DOCTYPE")) { + throw new WsdlException("The WSDL " + uri + " has a DOCTYPE, which is not allowed", e); + } + String line = e instanceof SAXParseException spe ? " (line " + spe.getLineNumber() + ")" : ""; + throw new WsdlException("The WSDL " + uri + " is not well formed" + line + ": " + message, e); + } catch (IOException | ParserConfigurationException e) { + throw new WsdlException("The WSDL " + uri + " cannot be parsed: " + e.getMessage(), e); + } + } + + private static DocumentBuilder documentBuilder() throws ParserConfigurationException { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + dbf.setFeature("http://xml.org/sax/features/external-general-entities", false); + dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); + dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + dbf.setXIncludeAware(false); + dbf.setExpandEntityReferences(false); + DocumentBuilder db = dbf.newDocumentBuilder(); + // no external entity, ever (the DOCTYPE is refused already) + db.setEntityResolver((publicId, systemId) -> { + throw new SAXException("External entities are not allowed: " + systemId); + }); + // the errors become the message of the exception, rather than [Fatal Error] lines on stderr + db.setErrorHandler(new ErrorHandler() { + @Override + public void warning(SAXParseException exception) { + // ignore + } + + @Override + public void error(SAXParseException exception) throws SAXException { + throw exception; + } + + @Override + public void fatalError(SAXParseException exception) throws SAXException { + throw exception; + } + }); + return db; + } + + /** + * The name attribute of a WSDL element, which must be an NCName. + */ + private static String name(Element e, String kind) throws WsdlException { + String name = e.getAttribute("name"); + if (!isNcName(name)) { + throw new WsdlException("The " + kind + " name '" + printable(name) + "' is not a valid NCName"); + } + return name; + } + + /** + * The QName of an attribute (such as tns:getOrder), resolved with the namespaces in scope, or <tt>null</tt>. + */ + private static QName qname(Element e, String attribute) throws WsdlException { + if (!e.hasAttribute(attribute)) { + return null; + } + String value = e.getAttribute(attribute).trim(); + int pos = value.indexOf(':'); + String prefix = pos > 0 ? value.substring(0, pos) : null; + String local = pos > 0 ? value.substring(pos + 1) : value; + if (!isNcName(local) || prefix != null && !isNcName(prefix)) { + throw new WsdlException( + "The " + attribute + " '" + printable(value) + "' of " + e.getLocalName() + " is not a valid QName"); + } + String ns = e.lookupNamespaceURI(prefix); + if (prefix != null && ns == null) { + throw new WsdlException( + "The prefix " + prefix + " of " + attribute + "=\"" + printable(value) + "\" of " + + e.getLocalName() + " is not declared"); + } + return new QName(ns != null ? ns : "", local); + } + + private static List<Element> children(Element parent, String ns) { + return children(parent, ns, null); + } + + private static List<Element> children(Element parent, String ns, String localName) { + List<Element> answer = new ArrayList<>(); + NodeList nl = parent.getChildNodes(); + for (int i = 0; i < nl.getLength(); i++) { + Node n = nl.item(i); + if (n instanceof Element child && (ns == null || ns.equals(child.getNamespaceURI())) + && (localName == null || localName.equals(child.getLocalName()))) { + answer.add(child); + } + } + return answer; + } + + private static Element first(Element parent, String ns, String localName) { + List<Element> list = children(parent, ns, localName); + return list.isEmpty() ? null : list.get(0); + } + } + + /** + * The text with the control characters (such as the escape of a terminal color code) replaced by a question mark, + * so a value from a remote WSDL cannot change the terminal. + */ + static String printable(String text) { + if (text == null) { + return null; + } + StringBuilder sb = new StringBuilder(text.length()); + text.codePoints().forEach(cp -> { + if (Character.isISOControl(cp) || Character.getType(cp) == Character.FORMAT) { + sb.append('?'); + } else { + sb.appendCodePoint(cp); + } + }); + return sb.toString(); + } + + /** + * The address with the user info (user:password@) masked, for the listing. + */ + static String maskedAddress(String address) { + if (address == null) { + return null; + } + return USER_INFO.matcher(address).replaceFirst("$1xxxxxx@"); + } +} diff --git a/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/WsdlRouteScaffold.java b/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/WsdlRouteScaffold.java new file mode 100644 index 000000000000..1a515cd6c71b --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/WsdlRouteScaffold.java @@ -0,0 +1,327 @@ +/* + * 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.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import javax.xml.namespace.QName; + +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.WsdlException; +import org.apache.camel.dsl.jbang.run.common.RuntimeType; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; + +/** + * Scaffolds a YAML route with a cxf: consumer or cxf: producers in PAYLOAD mode for a port of a WSDL, with no generated + * classes. The YAML is written with a YAML writer, and every name from the WSDL that goes into it is an NCName, and + * every namespace a plain URI, so a hostile WSDL cannot add YAML, a simple expression or a property placeholder. + */ +final class WsdlRouteScaffold { + + /** + * The characters of a namespace or an address that can go into an endpoint parameter, a constant and an XML + * attribute as they are: no brace (a property placeholder), quote, parenthesis (RAW), angle bracket or space. + */ + private static final Pattern SAFE_URI = Pattern.compile("[\\p{L}\\p{N}\\-._~:/?#\\[\\]@!$&*+,;=%]*"); + + /** + * The headers that decide which operation and which address the cxf producer calls: they are removed before the + * call, so a caller of the route (or a consumer that copied them from a request) cannot steer it. + */ + static final String PRODUCER_REMOVE_HEADERS = "Camel.*|operationName|operationNamespace|RequestContext|ResponseContext"; + + private static final int DEFAULT_PORT = 8080; + + private final Port port; + private final List<Operation> operations; + private final String wsdlUrl; + private final List<String> warnings = new ArrayList<>(); + + /** + * @param port the port + * @param operations the operations of the port to scaffold + * @param wsdlUrl the wsdlURL of the endpoints + */ + WsdlRouteScaffold(Port port, List<Operation> operations, String wsdlUrl) { + this.port = port; + this.operations = operations; + this.wsdlUrl = wsdlUrl; + } + + /** + * What the scaffold changed from the WSDL, such as the query of an address that it left out. + */ + List<String> warnings() { + return warnings; + } + + /** + * A route with a cxf: consumer for the port, with a choice of one when per operation. + * + * @param runtime the runtime: camel-main (and the Camel CLI) gets an absolute address on 0.0.0.0, spring-boot and + * quarkus the path, which their CXF servlet serves + */ + String consumer(RuntimeType runtime) throws WsdlException { + check(); + URI address = address(); + int p = address.getPort() != -1 ? address.getPort() : DEFAULT_PORT; + String path = address.getRawPath(); + String uri = RuntimeType.springBoot == runtime || RuntimeType.quarkus == runtime + ? "cxf://" + path + : "cxf://http://0.0.0.0:" + p + path; + + Map<String, Object> parameters = new LinkedHashMap<>(); + parameters.put("wsdlURL", wsdlUrl); + parameters.put("serviceName", port.service().toString()); + parameters.put("portName", port.qname().toString()); + parameters.put("dataFormat", "PAYLOAD"); + parameters.put("schemaValidationEnabled", true); + + List<Object> whens = new ArrayList<>(); + for (Operation op : operations) { + List<Object> steps = new ArrayList<>(); + steps.add(Map.of("log", Map.of("message", op.name() + " request: ${body}"))); + if (op.output() != null) { + Map<String, Object> setBody = new LinkedHashMap<>(); + setBody.put("note", "TODO: build the " + op.output().getLocalPart() + " response"); + setBody.put("expression", constant(placeholder(op.output()))); + steps.add(Map.of("setBody", setBody)); + } + Map<String, Object> when = new LinkedHashMap<>(); + when.put("expression", simple("${header.CamelCxfOperationName} == '" + op.name() + "'")); + when.put("steps", steps); + whens.add(when); + } + + List<Object> steps = new ArrayList<>(); + steps.add(Map.of("convertBodyTo", Map.of("type", "java.lang.String"))); + steps.add(Map.of("choice", Map.of("when", whens))); + + Map<String, Object> from = new LinkedHashMap<>(); + from.put("uri", uri); + from.put("parameters", parameters); + from.put("steps", steps); + + Map<String, Object> route = new LinkedHashMap<>(); + route.put("id", port.service().getLocalPart()); + route.put("description", "The " + port.service().getLocalPart() + " SOAP service, port " + port.name()); + route.put("from", from); + + StringBuilder sb = header("consumer"); + sb.append("#\n"); + sb.append("# Each operation returns a placeholder response: replace it with the response element.\n"); + sb.append("# The request and the response are validated against the schema of the WSDL (schemaValidationEnabled):\n"); + sb.append("# until it is filled in, the placeholder gives a SOAP fault that names the first element it misses.\n"); + if (RuntimeType.springBoot == runtime || RuntimeType.quarkus == runtime) { + sb.append("# The CXF servlet of the runtime serves the address ").append(path).append(".\n"); + } + return sb + dump(List.of(Map.of("route", route))); + } + + /** + * A route with a cxf: producer per operation, called with direct:operation and the request element as the body. + */ + String producer() throws WsdlException { + check(); + URI address = address(); + String uri = "cxf://" + address; + + List<Object> routes = new ArrayList<>(); + for (Operation op : operations) { + Map<String, Object> parameters = new LinkedHashMap<>(); + parameters.put("wsdlURL", wsdlUrl); + parameters.put("serviceName", port.service().toString()); + parameters.put("portName", port.qname().toString()); + parameters.put("dataFormat", "PAYLOAD"); + parameters.put("defaultOperationName", op.name()); + parameters.put("defaultOperationNamespace", op.namespace()); + + List<Object> steps = new ArrayList<>(); + Map<String, Object> remove = new LinkedHashMap<>(); + remove.put("note", "the caller must not choose the operation or the address of the call"); + remove.put("pattern", PRODUCER_REMOVE_HEADERS); + steps.add(Map.of("removeHeaders", remove)); + Map<String, Object> to = new LinkedHashMap<>(); + to.put("uri", uri); + to.put("parameters", parameters); + steps.add(Map.of("to", to)); + if (op.output() != null) { + steps.add(Map.of("convertBodyTo", Map.of("type", "java.lang.String"))); + } + + Map<String, Object> from = new LinkedHashMap<>(); + from.put("uri", "direct:" + op.name()); + from.put("steps", steps); + + Map<String, Object> route = new LinkedHashMap<>(); + route.put("id", op.name()); + route.put("description", "Calls " + op.name() + " of " + port.service().getLocalPart() + ": the body is the " + + op.input().getLocalPart() + " request element" + + (op.output() != null + ? ", and the reply the " + op.output().getLocalPart() + " response element" + : " (one-way)")); + route.put("from", from); + routes.add(Map.of("route", route)); + } + + StringBuilder sb = header("producer"); + sb.append("#\n"); + sb.append("# Send the request element (XML) to direct:<operation>, such as direct:") + .append(operations.get(0).name()).append(".\n"); + return sb + dump(routes); + } + + private StringBuilder header(String kind) { + StringBuilder sb = new StringBuilder(); + // only NCNames from the WSDL go into the comments + sb.append("# A cxf: ").append(kind).append(" in PAYLOAD mode for the service ").append(port.service().getLocalPart()) + .append(", port ").append(port.name()).append(" (SOAP ").append(port.soapVersion()).append(")\n"); + sb.append("# Scaffolded by: camel generate wsdl --route=").append(kind).append('\n'); + return sb; + } + + /** + * Checks that the port can be scaffolded and that its values can go into the YAML. + */ + private void check() throws WsdlException { + if (!port.isDocument()) { + throw new WsdlException( + "The port " + port.name() + + " uses the rpc style, which is listed but not scaffolded (only document style)"); + } + if (operations.isEmpty()) { + throw new WsdlException("The port " + port.name() + " has no operations to scaffold"); + } + checkNamespace(port.service().getNamespaceURI()); + checkNamespace(port.namespace()); + for (Operation op : operations) { + checkName(op.name()); + checkNamespace(op.namespace()); + if (op.input() == null) { + throw new WsdlException("The operation " + op.name() + " has no request element"); + } + checkElement(op.input()); + if (op.output() != null) { + checkElement(op.output()); + } + } + checkName(port.service().getLocalPart()); + checkName(port.name()); + } + + private static void checkName(String name) throws WsdlException { + if (!WsdlModel.isNcName(name)) { + throw new WsdlException("The name '" + WsdlModel.printable(name) + "' is not a valid NCName"); + } + } + + private static void checkElement(QName element) throws WsdlException { + checkName(element.getLocalPart()); + checkNamespace(element.getNamespaceURI()); + } + + private static void checkNamespace(String namespace) throws WsdlException { + if (namespace != null && !SAFE_URI.matcher(namespace).matches()) { + throw new WsdlException( + "The namespace '" + WsdlModel.printable(namespace) + + "' has characters that are not scaffolded (such as a brace, quote or space)"); + } + } + + /** + * The address of the port: scheme, host, port and path, without the user info (it is not written into the route) + * and without the query (it would become endpoint parameters). + */ + private URI address() throws WsdlException { + String raw = port.address(); + String fallback = "http://localhost:" + DEFAULT_PORT + "/" + port.service().getLocalPart(); + URI uri = null; + if (raw != null && !raw.isBlank()) { + try { + uri = new URI(raw.trim()); + } catch (URISyntaxException e) { + // not a URI + } + } + String scheme = uri != null && uri.getScheme() != null ? uri.getScheme().toLowerCase(Locale.ROOT) : null; + if (uri == null || uri.getHost() == null || !("http".equals(scheme) || "https".equals(scheme))) { + warnings.add("The port " + port.name() + " has no http(s) address" + + (raw != null ? " (" + WsdlModel.printable(WsdlModel.maskedAddress(raw)) + ")" : "") + + ": the route uses " + fallback); + return URI.create(fallback); + } + if (uri.getRawUserInfo() != null) { + warnings.add("The user info of the address of the port " + port.name() + + " is left out of the route: configure the credentials of the endpoint instead"); + } + if (uri.getRawQuery() != null || uri.getRawFragment() != null) { + warnings.add("The query of the address of the port " + port.name() + " is left out of the route"); + } + String path = uri.getRawPath() == null || uri.getRawPath().isEmpty() + ? "/" + port.service().getLocalPart() : uri.getRawPath(); + String answer = scheme + "://" + uri.getHost() + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + path; + if (!SAFE_URI.matcher(answer).matches()) { + throw new WsdlException("The address of the port " + port.name() + " has characters that are not scaffolded"); + } + return URI.create(answer); + } + + private static String placeholder(QName element) { + // the namespace is a plain URI (checkNamespace), so it needs no escaping in the attribute + String ns = element.getNamespaceURI(); + return "<" + element.getLocalPart() + (ns.isEmpty() ? "" : " xmlns=\"" + ns + "\"") + "><!-- TODO --></" + + element.getLocalPart() + ">"; + } + + private static Map<String, Object> constant(String text) { + return Map.of("constant", Map.of("expression", text)); + } + + private static Map<String, Object> simple(String text) { + return Map.of("simple", Map.of("expression", text)); + } + + private static String dump(Object document) { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + options.setIndent(2); + options.setIndicatorIndent(2); + options.setIndentWithIndicator(true); + options.setSplitLines(false); + options.setWidth(Integer.MAX_VALUE); + String yaml = new Yaml(options).dump(document); + // the writer indents the top-level list too: every line starts with two spaces, which are taken away, so the + // routes start at the first column as in the Camel examples (the same shift of every line keeps the structure) + String[] lines = yaml.split("\n", -1); + boolean indented = Arrays.stream(lines).allMatch(l -> l.isEmpty() || l.startsWith(" ")); + if (!indented) { + return yaml; + } + return Arrays.stream(lines).map(l -> l.isEmpty() ? l : l.substring(2)).collect(Collectors.joining("\n")); + } +} 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 new file mode 100644 index 000000000000..5f0fd9a2ba68 --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/java/org/apache/camel/dsl/jbang/core/commands/generate/CodeWsdlGeneratorTest.java @@ -0,0 +1,442 @@ +/* + * 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.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.stream.Collectors; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain; +import org.apache.camel.dsl.jbang.core.common.CommandLineTestHelper; +import org.apache.camel.dsl.jbang.run.common.StringPrinter; +import org.apache.camel.dsl.yaml.validator.YamlValidator; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.model.ChoiceDefinition; +import org.apache.camel.model.ModelCamelContext; +import org.apache.camel.model.RemoveHeadersDefinition; +import org.apache.camel.model.RouteDefinition; +import org.apache.camel.model.SetBodyDefinition; +import org.apache.camel.model.ToDefinition; +import org.apache.camel.model.WhenDefinition; +import org.apache.camel.support.PluginHelper; +import org.apache.camel.support.ResourceHelper; +import org.apache.camel.util.json.JsonArray; +import org.apache.camel.util.json.JsonObject; +import org.apache.camel.util.json.Jsoner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.assertj.core.api.Assertions.assertThat; + +class CodeWsdlGeneratorTest { + + // relative, as a user gives it: the wsdlURL of the scaffold is the same on every machine + private static final String DIR = "src/test/resources/wsdl/"; + private static final String ORDERS = DIR + "orders.wsdl"; + private static final String NOTIFY = DIR + "notify12.wsdl"; + private static final String MULTI = DIR + "multi.wsdl"; + private static final String RPC = DIR + "rpc.wsdl"; + private static final Path EXPECTED = Paths.get(DIR, "expected"); + + /** + * Run with -Dcamel.wsdl.updateGolden=true to write the expected files from the output (then review the diff). + */ + private static final boolean UPDATE_GOLDEN = Boolean.getBoolean("camel.wsdl.updateGolden"); + + @TempDir + Path dir; + + private final StringPrinter printer = new StringPrinter(); + + @Test + void listsTheServicesPortsAndOperations() throws Exception { + assertThat(run(ORDERS)).as(printer.getOutput()).isZero(); + + assertGolden("orders.txt", printer.getStdout()); + assertThat(printer.getStderr()).isEmpty(); + } + + @Test + void listsAsJsonWithTheCxfOptionsOfEachPort() throws Exception { + assertThat(run(ORDERS, "--json")).as(printer.getOutput()).isZero(); + + JsonObject root = (JsonObject) Jsoner.deserialize(printer.getStdout()); + assertGolden("orders.json", Jsoner.prettyPrint(printer.getStdout(), 2)); + JsonObject port = port(root, 0, 0); + JsonObject cxf = port.getMap("cxf"); + assertThat(cxf.getString("serviceName")).isEqualTo("{http://example.com/orders}OrderService"); + assertThat(cxf.getString("portName")).isEqualTo("{http://example.com/orders}OrderPort"); + assertThat(cxf.getString("wsdlURL")).isEqualTo("file:" + ORDERS); + assertThat(cxf.getString("address")).isEqualTo("http://localhost:18081/orders"); + assertThat(cxf.getString("defaultOperationNamespace")).isEqualTo("http://example.com/orders"); + } + + @Test + void scaffoldsAConsumerRouteThatLoadsWithTheYamlDsl() throws Exception { + assertThat(run(ORDERS, "--route=consumer")).as(printer.getOutput()).isZero(); + + String yaml = printer.getStdout(); + assertGolden("orders-consumer.camel.yaml", yaml); + assertValid(yaml); + + RouteDefinition route = load(yaml).get(0); + assertThat(route.getId()).isEqualTo("OrderService"); + assertThat(route.getInput().getEndpointUri()) + .startsWith("cxf://http://0.0.0.0:18081/orders?") + .contains("wsdlURL=file:" + ORDERS, "dataFormat=PAYLOAD", "schemaValidationEnabled=true", + "serviceName={http://example.com/orders}OrderService", + "portName={http://example.com/orders}OrderPort"); + ChoiceDefinition choice = (ChoiceDefinition) route.getOutputs().get(1); + assertThat(choice.getWhenClauses()).extracting(w -> w.getExpression().getExpression()) + .containsExactly("${header.CamelCxfOperationName} == 'getOrder'", + "${header.CamelCxfOperationName} == 'placeOrder'"); + WhenDefinition getOrder = choice.getWhenClauses().get(0); + SetBodyDefinition setBody = (SetBodyDefinition) getOrder.getOutputs().get(1); + assertThat(setBody.getExpression().getExpression()) + .isEqualTo("<getOrderResponse xmlns=\"http://example.com/orders\"><!-- TODO --></getOrderResponse>"); + } + + @Test + void scaffoldsAProducerRoutePerOperation() throws Exception { + assertThat(run(ORDERS, "--route=producer")).as(printer.getOutput()).isZero(); + + String yaml = printer.getStdout(); + assertGolden("orders-producer.camel.yaml", yaml); + assertValid(yaml); + + List<RouteDefinition> routes = load(yaml); + assertThat(routes).extracting(r -> r.getInput().getEndpointUri()) + .containsExactly("direct:getOrder", "direct:placeOrder"); + RouteDefinition getOrder = routes.get(0); + // the caller cannot steer the call with CamelDestinationOverrideUrl or the operation headers + RemoveHeadersDefinition remove = (RemoveHeadersDefinition) getOrder.getOutputs().get(0); + assertThat(remove.getPattern()).isEqualTo(WsdlRouteScaffold.PRODUCER_REMOVE_HEADERS); + ToDefinition to = (ToDefinition) getOrder.getOutputs().get(1); + assertThat(to.getEndpointUri()) + .startsWith("cxf://http://localhost:18081/orders?") + .contains("defaultOperationName=getOrder", "defaultOperationNamespace=http://example.com/orders", + "dataFormat=PAYLOAD"); + } + + @Test + void theOperationOptionChoosesTheOperations() throws Exception { + assertThat(run(ORDERS, "--route=producer", "--operation=placeOrder")).as(printer.getOutput()).isZero(); + + assertThat(load(printer.getStdout())).extracting(RouteDefinition::getId).containsExactly("placeOrder"); + } + + @ParameterizedTest + @ValueSource(strings = { "spring-boot", "quarkus" }) + void aSpringBootOrQuarkusConsumerListensOnThePathOfTheAddress(String runtime) throws Exception { + assertThat(run(ORDERS, "--route=consumer", "--runtime=" + runtime)).as(printer.getOutput()).isZero(); + + String yaml = printer.getStdout(); + assertValid(yaml); + assertThat(load(yaml).get(0).getInput().getEndpointUri()).startsWith("cxf:///orders?"); + } + + @Test + void writesTheRouteToTheOutputFile() throws Exception { + Path file = dir.resolve("orders.camel.yaml"); + + assertThat(run(ORDERS, "--route=consumer", "--output=" + file)).as(printer.getOutput()).isZero(); + + assertThat(printer.getStdout()).isEmpty(); + assertValid(Files.readString(file)); + } + + @Test + void listsSoap12AndOneWayOperationsAndMasksTheUserInfo() throws Exception { + assertThat(run(NOTIFY)).as(printer.getOutput()).isZero(); + + String out = printer.getStdout(); + assertThat(out).contains("SOAP 1.2", "(one-way)", "https://[email protected]:8443/ws/notify") + .doesNotContain("secret", "user:"); + } + + @Test + void aOneWayOperationReturnsNoResponseAndTheUserInfoIsLeftOut() throws Exception { + assertThat(run(NOTIFY, "--route=consumer")).as(printer.getOutput()).isZero(); + + String yaml = printer.getStdout(); + assertValid(yaml); + assertThat(yaml).doesNotContain("secret", "user", "tenant"); + assertThat(printer.getStderr()).contains("user info", "query"); + RouteDefinition route = load(yaml).get(0); + assertThat(route.getInput().getEndpointUri()).startsWith("cxf://http://0.0.0.0:8443/ws/notify?"); + ChoiceDefinition choice = (ChoiceDefinition) route.getOutputs().get(1); + // notify is one-way: only a log + assertThat(choice.getWhenClauses().get(0).getOutputs()).hasSize(1); + assertThat(choice.getWhenClauses().get(1).getOutputs()).hasSize(2); + + StringPrinter producer = new StringPrinter(); + assertThat(run(producer, NOTIFY, "--route=producer")).as(producer.getOutput()).isZero(); + assertThat(producer.getStdout()).contains("uri: cxf://https://notify.example.com:8443/ws/notify") + .doesNotContain("secret", "tenant"); + assertValid(producer.getStdout()); + } + + @Test + void followsTheImportsAndListsEverySoapPort() throws Exception { + assertThat(run(MULTI, "--json")).as(printer.getOutput()).isZero(); + + JsonObject root = (JsonObject) Jsoner.deserialize(printer.getStdout()); + JsonArray services = root.getJsonArray("services"); + assertThat(services).extracting(s -> ((JsonObject) s).getString("name")) + .containsExactly("StockService", "StockAdminService"); + assertThat(((JsonObject) services.get(0)).getJsonArray("ports")) + .extracting(p -> ((JsonObject) p).getString("name") + " " + ((JsonObject) p).getString("soapVersion")) + .containsExactly("StockSoap 1.1", "StockSoap12 1.2"); + JsonObject getQuote = (JsonObject) port(root, 0, 1).getJsonArray("operations").get(0); + assertThat(getQuote.getString("input")).isEqualTo("{http://example.com/stock}getQuote"); + JsonObject fault = (JsonObject) getQuote.getJsonArray("faults").get(0); + assertThat(fault.getString("element")).isEqualTo("{http://example.com/errors}unknownSymbol"); + // the HTTP binding is not SOAP + assertThat(printer.getStderr()).contains("The port StockHttpGet of the service StockService is left out"); + } + + @Test + void asksForTheServiceAndPortWhenTheWsdlHasMoreThanOne() throws Exception { + assertThat(run(MULTI, "--route=consumer")).isEqualTo(2); + assertThat(printer.getStderr()).contains("--service=StockService --port=StockSoap12 (SOAP 1.2)"); + + StringPrinter chosen = new StringPrinter(); + assertThat(run(chosen, MULTI, "--route=consumer", "--service=StockService", "--port=StockSoap12")) + .as(chosen.getOutput()).isZero(); + assertValid(chosen.getStdout()); + assertThat(load(chosen.getStdout()).get(0).getInput().getEndpointUri()) + .startsWith("cxf://http://0.0.0.0:9001/stock12?") + .contains("portName={http://example.com/stock/service}StockSoap12"); + } + + @Test + void anUnknownServicePortOrOperationIsNotFound() throws Exception { + assertThat(run(ORDERS, "--service=Nope")).isEqualTo(3); + assertThat(printer.getStderr()).contains("Unknown service: Nope", "OrderService"); + + StringPrinter port = new StringPrinter(); + assertThat(run(port, ORDERS, "--port=Nope")).isEqualTo(3); + assertThat(port.getStderr()).contains("Unknown port: Nope", "OrderPort"); + + StringPrinter op = new StringPrinter(); + assertThat(run(op, ORDERS, "--route=producer", "--operation=getOrder,deleteOrder")).isEqualTo(3); + assertThat(op.getStderr()).contains("Unknown operation: deleteOrder", "getOrder, placeOrder"); + } + + @Test + void listsButDoesNotScaffoldRpc() throws Exception { + assertThat(run(RPC)).as(printer.getOutput()).isZero(); + assertThat(printer.getStdout()).contains("STYLE rpc/literal", "{http://example.com/calc/rpc}add"); + + StringPrinter scaffold = new StringPrinter(); + assertThat(run(scaffold, RPC, "--route=consumer")).isEqualTo(1); + assertThat(scaffold.getStderr()).contains("rpc style"); + } + + @Test + void refusesWsdl20() throws Exception { + assertThat(run(DIR + "wsdl20.wsdl")).isEqualTo(1); + assertThat(printer.getStderr()).contains("WSDL 2.0 is not supported"); + } + + @Test + void refusesADoctype() throws Exception { + assertThat(run(DIR + "doctype.wsdl")).isEqualTo(1); + assertThat(printer.getStderr()).contains("has a DOCTYPE, which is not allowed"); + assertThat(printer.getOutput()).doesNotContain("root:"); + } + + @Test + void aFileThatDoesNotExist() throws Exception { + assertThat(run(DIR + "nope.wsdl")).isEqualTo(66); + assertThat(printer.getStderr()).contains("does not exist"); + + StringPrinter json = new StringPrinter(); + assertThat(run(json, DIR + "nope.wsdl", "--json")).isEqualTo(66); + JsonObject error = (JsonObject) Jsoner.deserialize(json.getStdout()); + assertThat(error.getInteger("code")).isEqualTo(66); + } + + @Test + void doesNotFollowAnImportWithAnotherScheme() throws Exception { + // a WSDL of a remote server must not import a local file, and the other way round + Path wsdl = Files.writeString(dir.resolve("import.wsdl"), """ + <wsdl:definitions targetNamespace="urn:x" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"> + <wsdl:import namespace="urn:y" location="http://localhost:1/other.wsdl"/> + </wsdl:definitions> + """); + + assertThat(run(wsdl.toString())).isEqualTo(1); + assertThat(printer.getStderr()).contains("is not followed: its scheme (http) is not the scheme of the WSDL (file)"); + } + + @Test + void anImportCycleIsReadOnce() throws Exception { + Path wsdl = Files.writeString(dir.resolve("self.wsdl"), + ordersWith("<wsdl:types>", "<wsdl:import namespace=\"urn:self\" location=\"self.wsdl\"/><wsdl:types>")); + + assertThat(run(wsdl.toString())).as(printer.getOutput()).isZero(); + assertThat(printer.getStdout()).contains("getOrder"); + } + + @Test + void refusesANameThatIsNotAnNcName() throws Exception { + Path wsdl = Files.writeString(dir.resolve("evil.wsdl"), + ordersWith("<wsdl:operation name=\"getOrder\">", "<wsdl:operation name=\"getOrder' || true || '\">")); + + assertThat(run(wsdl.toString(), "--route=consumer")).isEqualTo(1); + assertThat(printer.getStderr()).contains("is not a valid NCName"); + assertThat(printer.getStdout()).isEmpty(); + } + + @Test + void doesNotScaffoldANamespaceWithAPropertyPlaceholder() throws Exception { + Path wsdl = Files.writeString(dir.resolve("placeholder.wsdl"), + ordersWith("http://example.com/orders", "urn:{{env:HOME}}")); + + // listed, as the JSON and the table do not evaluate it + assertThat(run(wsdl.toString(), "--json")).as(printer.getOutput()).isZero(); + + StringPrinter scaffold = new StringPrinter(); + assertThat(run(scaffold, wsdl.toString(), "--route=consumer")).isEqualTo(1); + assertThat(scaffold.getStderr()).contains("has characters that are not scaffolded"); + assertThat(scaffold.getStdout()).isEmpty(); + } + + @Test + void readsARemoteWsdlButNotAFileItImports() throws Exception { + byte[] orders = Files.readAllBytes(Paths.get(ORDERS)); + byte[] evil = """ + <wsdl:definitions targetNamespace="urn:x" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"> + <wsdl:import namespace="urn:y" location="file:///etc/hosts"/> + </wsdl:definitions> + """.getBytes(StandardCharsets.UTF_8); + HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + server.createContext("/orders", exchange -> reply(exchange, orders)); + server.createContext("/evil", exchange -> reply(exchange, evil)); + server.start(); + try { + String base = "http://localhost:" + server.getAddress().getPort(); + + assertThat(run(base + "/orders?wsdl", "--route=producer")).as(printer.getOutput()).isZero(); + assertValid(printer.getStdout()); + assertThat(printer.getStdout()).contains("wsdlURL: " + base + "/orders?wsdl"); + + StringPrinter refused = new StringPrinter(); + assertThat(run(refused, base + "/evil")).isEqualTo(1); + assertThat(refused.getStderr()).contains("its scheme (file) is not the scheme of the WSDL (http)"); + } finally { + server.stop(0); + } + } + + private static void reply(HttpExchange exchange, byte[] body) throws IOException { + exchange.sendResponseHeaders(200, body.length); + try (OutputStream os = exchange.getResponseBody()) { + os.write(body); + } + } + + @Test + void invalidOptions() throws Exception { + assertThat(run(ORDERS, "--route=both")).isEqualTo(2); + assertThat(run(ORDERS, "--route=consumer", "--json")).isEqualTo(2); + assertThat(run(ORDERS, "--output=x.yaml")).isEqualTo(2); + } + + private static String ordersWith(String target, String replacement) throws Exception { + String orders = Files.readString(Paths.get(ORDERS)); + assertThat(orders).contains(target); + return orders.replace(target, replacement); + } + + private static JsonObject port(JsonObject root, int service, int port) { + JsonObject s = (JsonObject) root.getJsonArray("services").get(service); + return (JsonObject) s.getJsonArray("ports").get(port); + } + + private int run(String... args) throws Exception { + return run(printer, args); + } + + private static int run(StringPrinter printer, String... args) throws Exception { + CodeWsdlGenerator command = new CamelJBangMain().withPrinter(printer).command(new CodeWsdlGenerator()); + CommandLineTestHelper.parse(command, args); + return command.doCall(); + } + + private static void assertValid(String yaml) throws Exception { + for (boolean canonical : new boolean[] { false, true }) { + YamlValidator validator = new YamlValidator(canonical); + validator.init(); + assertThat(validator.validate(yaml)).as("canonical=" + canonical + ":\n" + yaml).isEmpty(); + } + } + + /** + * The routes of the YAML, as the YAML DSL loads them (without starting them: camel-cxf is not on the classpath). + */ + private static List<RouteDefinition> load(String yaml) throws Exception { + try (DefaultCamelContext context = new DefaultCamelContext()) { + PluginHelper.getRoutesLoader(context).loadRoutes(ResourceHelper.fromString("wsdl.camel.yaml", yaml)); + return List.copyOf(((ModelCamelContext) context).getRouteDefinitions()); + } + } + + private static void assertGolden(String name, String actual) throws Exception { + Path file = EXPECTED.resolve(name); + String normalized = normalize(actual); + if (UPDATE_GOLDEN) { + Files.createDirectories(EXPECTED); + // keep the license header that the build adds to a YAML file + String header = Files.exists(file) ? licenseHeader(Files.readString(file)) : ""; + Files.writeString(file, header + normalized, StandardCharsets.UTF_8); + } + assertThat(file).as("the expected output " + file + " (run with -Dcamel.wsdl.updateGolden=true)").exists(); + String expected = Files.readString(file).replace("\r\n", "\n"); + assertThat(normalized).isEqualTo(normalize(expected.substring(licenseHeader(expected).length()))); + } + + /** + * The license header at the start of the text (up to and with the first empty line), or empty. + */ + private static String licenseHeader(String text) { + String t = text.replace("\r\n", "\n"); + int end = t.indexOf("\n\n"); + if (t.startsWith("#\n# Licensed to the Apache Software Foundation") && end > 0) { + return t.substring(0, end + 2); + } + return ""; + } + + // without the trailing spaces of the table rows, which an editor may remove + private static String normalize(String text) { + return text.replace("\r\n", "\n").lines().map(String::stripTrailing).collect(Collectors.joining("\n")).strip() + + "\n"; + } +} diff --git a/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/doctype.wsdl b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/doctype.wsdl new file mode 100644 index 000000000000..ffc5bfaeb407 --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/doctype.wsdl @@ -0,0 +1,23 @@ +<?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. + +--> +<!DOCTYPE definitions [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]> +<wsdl:definitions name="Evil" targetNamespace="http://example.com/evil" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"> + <wsdl:documentation>&xxe;</wsdl:documentation> +</wsdl:definitions> diff --git a/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/expected/orders-consumer.camel.yaml b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/expected/orders-consumer.camel.yaml new file mode 100644 index 000000000000..9c04e765034e --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/expected/orders-consumer.camel.yaml @@ -0,0 +1,61 @@ +# +# 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. +# + +# A cxf: consumer in PAYLOAD mode for the service OrderService, port OrderPort (SOAP 1.1) +# Scaffolded by: camel generate wsdl --route=consumer +# +# Each operation returns a placeholder response: replace it with the response element. +# The request and the response are validated against the schema of the WSDL (schemaValidationEnabled): +# until it is filled in, the placeholder gives a SOAP fault that names the first element it misses. +- route: + id: OrderService + description: The OrderService SOAP service, port OrderPort + from: + uri: cxf://http://0.0.0.0:18081/orders + parameters: + wsdlURL: file:src/test/resources/wsdl/orders.wsdl + serviceName: '{http://example.com/orders}OrderService' + portName: '{http://example.com/orders}OrderPort' + dataFormat: PAYLOAD + schemaValidationEnabled: true + steps: + - convertBodyTo: + type: java.lang.String + - choice: + when: + - expression: + simple: + expression: ${header.CamelCxfOperationName} == 'getOrder' + steps: + - log: + message: 'getOrder request: ${body}' + - setBody: + note: 'TODO: build the getOrderResponse response' + expression: + constant: + expression: <getOrderResponse xmlns="http://example.com/orders"><!-- TODO --></getOrderResponse> + - expression: + simple: + expression: ${header.CamelCxfOperationName} == 'placeOrder' + steps: + - log: + message: 'placeOrder request: ${body}' + - setBody: + note: 'TODO: build the placeOrderResponse response' + expression: + constant: + expression: <placeOrderResponse xmlns="http://example.com/orders"><!-- TODO --></placeOrderResponse> diff --git a/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/expected/orders-producer.camel.yaml b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/expected/orders-producer.camel.yaml new file mode 100644 index 000000000000..c86e9280173f --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/expected/orders-producer.camel.yaml @@ -0,0 +1,61 @@ +# +# 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. +# + +# A cxf: producer in PAYLOAD mode for the service OrderService, port OrderPort (SOAP 1.1) +# Scaffolded by: camel generate wsdl --route=producer +# +# Send the request element (XML) to direct:<operation>, such as direct:getOrder. +- route: + id: getOrder + description: 'Calls getOrder of OrderService: the body is the getOrder request element, and the reply the getOrderResponse response element' + from: + uri: direct:getOrder + steps: + - removeHeaders: + note: the caller must not choose the operation or the address of the call + pattern: Camel.*|operationName|operationNamespace|RequestContext|ResponseContext + - to: + uri: cxf://http://localhost:18081/orders + parameters: + wsdlURL: file:src/test/resources/wsdl/orders.wsdl + serviceName: '{http://example.com/orders}OrderService' + portName: '{http://example.com/orders}OrderPort' + dataFormat: PAYLOAD + defaultOperationName: getOrder + defaultOperationNamespace: http://example.com/orders + - convertBodyTo: + type: java.lang.String +- route: + id: placeOrder + description: 'Calls placeOrder of OrderService: the body is the placeOrder request element, and the reply the placeOrderResponse response element' + from: + uri: direct:placeOrder + steps: + - removeHeaders: + note: the caller must not choose the operation or the address of the call + pattern: Camel.*|operationName|operationNamespace|RequestContext|ResponseContext + - to: + uri: cxf://http://localhost:18081/orders + parameters: + wsdlURL: file:src/test/resources/wsdl/orders.wsdl + serviceName: '{http://example.com/orders}OrderService' + portName: '{http://example.com/orders}OrderPort' + dataFormat: PAYLOAD + defaultOperationName: placeOrder + defaultOperationNamespace: http://example.com/orders + - convertBodyTo: + type: java.lang.String diff --git a/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/expected/orders.json b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/expected/orders.json new file mode 100644 index 000000000000..f2027aed1e54 --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/expected/orders.json @@ -0,0 +1,57 @@ +{ + "wsdl": "src\/test\/resources\/wsdl\/orders.wsdl", + "targetNamespace": "http:\/\/example.com\/orders", + "services": [ + { + "name": "OrderService", + "namespace": "http:\/\/example.com\/orders", + "ports": [ + { + "name": "OrderPort", + "binding": "{http:\/\/example.com\/orders}OrderSoapBinding", + "soapVersion": "1.1", + "style": "document", + "transport": "http:\/\/schemas.xmlsoap.org\/soap\/http", + "address": "http:\/\/localhost:18081\/orders", + "namespace": "http:\/\/example.com\/orders", + "cxf": { + "serviceName": "{http:\/\/example.com\/orders}OrderService", + "portName": "{http:\/\/example.com\/orders}OrderPort", + "wsdlURL": "file:src\/test\/resources\/wsdl\/orders.wsdl", + "address": "http:\/\/localhost:18081\/orders", + "defaultOperationNamespace": "http:\/\/example.com\/orders" + }, + "operations": [ + { + "name": "getOrder", + "soapAction": "http:\/\/example.com\/orders\/getOrder", + "style": "document", + "use": "literal", + "oneWay": false, + "input": "{http:\/\/example.com\/orders}getOrder", + "output": "{http:\/\/example.com\/orders}getOrderResponse", + "faults": [ + { + "name": "orderNotFound", + "element": "{http:\/\/example.com\/orders}orderNotFound" + } + ] + }, + { + "name": "placeOrder", + "soapAction": "http:\/\/example.com\/orders\/placeOrder", + "style": "document", + "use": "literal", + "oneWay": false, + "input": "{http:\/\/example.com\/orders}placeOrder", + "output": "{http:\/\/example.com\/orders}placeOrderResponse", + "faults": [ + + ] + } + ] + } + ] + } + ] +} diff --git a/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/expected/orders.txt b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/expected/orders.txt new file mode 100644 index 000000000000..0538746019d2 --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/expected/orders.txt @@ -0,0 +1,11 @@ +SERVICE OrderService +PORT OrderPort +BINDING OrderSoapBinding +SOAP 1.1 +STYLE document/literal +ADDRESS http://localhost:18081/orders +NAMESPACE http://example.com/orders + + OPERATION SOAP ACTION INPUT OUTPUT FAULTS + getOrder http://example.com/orders/getOrder getOrder getOrderResponse orderNotFound + placeOrder http://example.com/orders/placeOrder placeOrder placeOrderResponse diff --git a/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/multi-binding.wsdl b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/multi-binding.wsdl new file mode 100644 index 000000000000..757c48fc7e11 --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/multi-binding.wsdl @@ -0,0 +1,59 @@ +<?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. + +--> +<!-- The bindings of multi.wsdl, which import the messages and the port type. --> +<wsdl:definitions name="StockBinding" + targetNamespace="http://example.com/stock/binding" + xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" + xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" + xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" + xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" + xmlns:i="http://example.com/stock"> + + <wsdl:import namespace="http://example.com/stock" location="types/multi-interface.wsdl"/> + + <wsdl:binding name="StockSoapBinding" type="i:StockPortType"> + <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> + <wsdl:operation name="getQuote"> + <soap:operation soapAction="http://example.com/stock/getQuote"/> + <wsdl:input><soap:body use="literal"/></wsdl:input> + <wsdl:output><soap:body use="literal"/></wsdl:output> + <wsdl:fault name="unknownSymbol"><soap:fault name="unknownSymbol" use="literal"/></wsdl:fault> + </wsdl:operation> + </wsdl:binding> + + <wsdl:binding name="StockSoap12Binding" type="i:StockPortType"> + <soap12:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> + <wsdl:operation name="getQuote"> + <soap12:operation soapAction="http://example.com/stock/getQuote"/> + <wsdl:input><soap12:body use="literal"/></wsdl:input> + <wsdl:output><soap12:body use="literal"/></wsdl:output> + <wsdl:fault name="unknownSymbol"><soap12:fault name="unknownSymbol" use="literal"/></wsdl:fault> + </wsdl:operation> + </wsdl:binding> + + <wsdl:binding name="StockHttpBinding" type="i:StockPortType"> + <http:binding verb="GET"/> + <wsdl:operation name="getQuote"> + <http:operation location="/getQuote"/> + <wsdl:input><http:urlEncoded/></wsdl:input> + <wsdl:output/> + </wsdl:operation> + </wsdl:binding> +</wsdl:definitions> diff --git a/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/multi.wsdl b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/multi.wsdl new file mode 100644 index 000000000000..b74b59d0ae0d --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/multi.wsdl @@ -0,0 +1,48 @@ +<?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. + +--> +<!-- Two services, a SOAP 1.1 and a SOAP 1.2 port, and an HTTP port; the messages, port type and bindings are imported. --> +<wsdl:definitions name="Stock" + targetNamespace="http://example.com/stock/service" + xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" + xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" + xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" + xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" + xmlns:b="http://example.com/stock/binding"> + + <wsdl:import namespace="http://example.com/stock/binding" location="multi-binding.wsdl"/> + + <wsdl:service name="StockService"> + <wsdl:port name="StockSoap" binding="b:StockSoapBinding"> + <soap:address location="http://localhost:9001/stock"/> + </wsdl:port> + <wsdl:port name="StockSoap12" binding="b:StockSoap12Binding"> + <soap12:address location="http://localhost:9001/stock12"/> + </wsdl:port> + <wsdl:port name="StockHttpGet" binding="b:StockHttpBinding"> + <http:address location="http://localhost:9001/stock-http"/> + </wsdl:port> + </wsdl:service> + + <wsdl:service name="StockAdminService"> + <wsdl:port name="StockAdminSoap" binding="b:StockSoapBinding"> + <soap:address location="http://localhost:9002/admin"/> + </wsdl:port> + </wsdl:service> +</wsdl:definitions> diff --git a/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/notify12.wsdl b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/notify12.wsdl new file mode 100644 index 000000000000..086b8fdac9ba --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/notify12.wsdl @@ -0,0 +1,70 @@ +<?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. + +--> +<!-- SOAP 1.2, with a one-way operation and an address with user info. --> +<wsdl:definitions name="NotifyService" + targetNamespace="http://example.com/notify" + xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" + xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" + xmlns:xs="http://www.w3.org/2001/XMLSchema" + xmlns:tns="http://example.com/notify"> + + <wsdl:types> + <xs:schema targetNamespace="http://example.com/notify" elementFormDefault="qualified"> + <xs:element name="notify"><xs:complexType><xs:sequence> + <xs:element name="text" type="xs:string"/> + </xs:sequence></xs:complexType></xs:element> + <xs:element name="ping"><xs:complexType/></xs:element> + <xs:element name="pingResponse"><xs:complexType/></xs:element> + </xs:schema> + </wsdl:types> + + <wsdl:message name="notifyRequest"><wsdl:part name="parameters" element="tns:notify"/></wsdl:message> + <wsdl:message name="pingRequest"><wsdl:part name="parameters" element="tns:ping"/></wsdl:message> + <wsdl:message name="pingResponse"><wsdl:part name="parameters" element="tns:pingResponse"/></wsdl:message> + + <wsdl:portType name="NotifyPortType"> + <wsdl:operation name="notify"> + <wsdl:input message="tns:notifyRequest"/> + </wsdl:operation> + <wsdl:operation name="ping"> + <wsdl:input message="tns:pingRequest"/> + <wsdl:output message="tns:pingResponse"/> + </wsdl:operation> + </wsdl:portType> + + <wsdl:binding name="NotifySoap12Binding" type="tns:NotifyPortType"> + <soap12:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> + <wsdl:operation name="notify"> + <soap12:operation soapAction="urn:notify"/> + <wsdl:input><soap12:body use="literal"/></wsdl:input> + </wsdl:operation> + <wsdl:operation name="ping"> + <soap12:operation/> + <wsdl:input><soap12:body use="literal"/></wsdl:input> + <wsdl:output><soap12:body use="literal"/></wsdl:output> + </wsdl:operation> + </wsdl:binding> + + <wsdl:service name="NotifyService"> + <wsdl:port name="NotifyPort" binding="tns:NotifySoap12Binding"> + <soap12:address location="https://user:[email protected]:8443/ws/notify?tenant=a"/> + </wsdl:port> + </wsdl:service> +</wsdl:definitions> diff --git a/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/orders.wsdl b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/orders.wsdl new file mode 100644 index 000000000000..5f6361ba4a92 --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/orders.wsdl @@ -0,0 +1,116 @@ +<?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. + +--> +<!-- A small document/literal wrapped SOAP 1.1 service, written for the soap-source / soap-action prototype. --> +<wsdl:definitions name="OrderService" + targetNamespace="http://example.com/orders" + xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" + xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" + xmlns:xs="http://www.w3.org/2001/XMLSchema" + xmlns:tns="http://example.com/orders"> + + <wsdl:types> + <xs:schema targetNamespace="http://example.com/orders" elementFormDefault="qualified"> + <xs:complexType name="Item"> + <xs:sequence> + <xs:element name="sku" type="xs:string"/> + <xs:element name="quantity" type="xs:int"/> + <xs:element name="price" type="xs:decimal"/> + </xs:sequence> + </xs:complexType> + <xs:complexType name="Order"> + <xs:sequence> + <xs:element name="orderId" type="xs:string"/> + <xs:element name="customer" type="xs:string"/> + <xs:element name="status" type="xs:string"/> + <xs:element name="item" type="tns:Item" maxOccurs="unbounded"/> + </xs:sequence> + </xs:complexType> + + <xs:element name="getOrder"> + <xs:complexType><xs:sequence> + <xs:element name="orderId" type="xs:string"/> + </xs:sequence></xs:complexType> + </xs:element> + <xs:element name="getOrderResponse"> + <xs:complexType><xs:sequence> + <xs:element name="order" type="tns:Order"/> + </xs:sequence></xs:complexType> + </xs:element> + + <xs:element name="placeOrder"> + <xs:complexType><xs:sequence> + <xs:element name="customer" type="xs:string"/> + <xs:element name="item" type="tns:Item" maxOccurs="unbounded"/> + </xs:sequence></xs:complexType> + </xs:element> + <xs:element name="placeOrderResponse"> + <xs:complexType><xs:sequence> + <xs:element name="orderId" type="xs:string"/> + <xs:element name="status" type="xs:string"/> + </xs:sequence></xs:complexType> + </xs:element> + + <xs:element name="orderNotFound"> + <xs:complexType><xs:sequence> + <xs:element name="orderId" type="xs:string"/> + </xs:sequence></xs:complexType> + </xs:element> + </xs:schema> + </wsdl:types> + + <wsdl:message name="getOrderRequest"><wsdl:part name="parameters" element="tns:getOrder"/></wsdl:message> + <wsdl:message name="getOrderResponse"><wsdl:part name="parameters" element="tns:getOrderResponse"/></wsdl:message> + <wsdl:message name="placeOrderRequest"><wsdl:part name="parameters" element="tns:placeOrder"/></wsdl:message> + <wsdl:message name="placeOrderResponse"><wsdl:part name="parameters" element="tns:placeOrderResponse"/></wsdl:message> + <wsdl:message name="orderNotFoundFault"><wsdl:part name="fault" element="tns:orderNotFound"/></wsdl:message> + + <wsdl:portType name="OrderPortType"> + <wsdl:operation name="getOrder"> + <wsdl:input message="tns:getOrderRequest"/> + <wsdl:output message="tns:getOrderResponse"/> + <wsdl:fault name="orderNotFound" message="tns:orderNotFoundFault"/> + </wsdl:operation> + <wsdl:operation name="placeOrder"> + <wsdl:input message="tns:placeOrderRequest"/> + <wsdl:output message="tns:placeOrderResponse"/> + </wsdl:operation> + </wsdl:portType> + + <wsdl:binding name="OrderSoapBinding" type="tns:OrderPortType"> + <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> + <wsdl:operation name="getOrder"> + <soap:operation soapAction="http://example.com/orders/getOrder"/> + <wsdl:input><soap:body use="literal"/></wsdl:input> + <wsdl:output><soap:body use="literal"/></wsdl:output> + <wsdl:fault name="orderNotFound"><soap:fault name="orderNotFound" use="literal"/></wsdl:fault> + </wsdl:operation> + <wsdl:operation name="placeOrder"> + <soap:operation soapAction="http://example.com/orders/placeOrder"/> + <wsdl:input><soap:body use="literal"/></wsdl:input> + <wsdl:output><soap:body use="literal"/></wsdl:output> + </wsdl:operation> + </wsdl:binding> + + <wsdl:service name="OrderService"> + <wsdl:port name="OrderPort" binding="tns:OrderSoapBinding"> + <soap:address location="http://localhost:18081/orders"/> + </wsdl:port> + </wsdl:service> +</wsdl:definitions> diff --git a/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/rpc.wsdl b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/rpc.wsdl new file mode 100644 index 000000000000..04f85c58c82d --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/rpc.wsdl @@ -0,0 +1,55 @@ +<?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. + +--> +<!-- rpc/literal: listed, but not scaffolded. --> +<wsdl:definitions name="Calculator" + targetNamespace="http://example.com/calc" + xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" + xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" + xmlns:xs="http://www.w3.org/2001/XMLSchema" + xmlns:tns="http://example.com/calc"> + + <wsdl:message name="addRequest"> + <wsdl:part name="a" type="xs:int"/> + <wsdl:part name="b" type="xs:int"/> + </wsdl:message> + <wsdl:message name="addResponse"><wsdl:part name="sum" type="xs:int"/></wsdl:message> + + <wsdl:portType name="CalculatorPortType"> + <wsdl:operation name="add"> + <wsdl:input message="tns:addRequest"/> + <wsdl:output message="tns:addResponse"/> + </wsdl:operation> + </wsdl:portType> + + <wsdl:binding name="CalculatorBinding" type="tns:CalculatorPortType"> + <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> + <wsdl:operation name="add"> + <soap:operation soapAction=""/> + <wsdl:input><soap:body use="literal" namespace="http://example.com/calc/rpc"/></wsdl:input> + <wsdl:output><soap:body use="literal" namespace="http://example.com/calc/rpc"/></wsdl:output> + </wsdl:operation> + </wsdl:binding> + + <wsdl:service name="CalculatorService"> + <wsdl:port name="CalculatorPort" binding="tns:CalculatorBinding"> + <soap:address location="http://localhost:9003/calc"/> + </wsdl:port> + </wsdl:service> +</wsdl:definitions> diff --git a/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/types/multi-interface.wsdl b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/types/multi-interface.wsdl new file mode 100644 index 000000000000..9fc0827845eb --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/types/multi-interface.wsdl @@ -0,0 +1,53 @@ +<?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. + +--> +<!-- The messages and the port type of multi.wsdl, with the element of the faults in another namespace. --> +<wsdl:definitions name="StockInterface" + targetNamespace="http://example.com/stock" + xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" + xmlns:xs="http://www.w3.org/2001/XMLSchema" + xmlns:tns="http://example.com/stock" + xmlns:err="http://example.com/errors"> + + <wsdl:types> + <xs:schema targetNamespace="http://example.com/stock" elementFormDefault="qualified"> + <xs:element name="getQuote"><xs:complexType><xs:sequence> + <xs:element name="symbol" type="xs:string"/> + </xs:sequence></xs:complexType></xs:element> + <xs:element name="getQuoteResponse"><xs:complexType><xs:sequence> + <xs:element name="price" type="xs:decimal"/> + </xs:sequence></xs:complexType></xs:element> + </xs:schema> + <xs:schema targetNamespace="http://example.com/errors" elementFormDefault="qualified"> + <xs:element name="unknownSymbol" type="xs:string"/> + </xs:schema> + </wsdl:types> + + <wsdl:message name="getQuoteRequest"><wsdl:part name="parameters" element="tns:getQuote"/></wsdl:message> + <wsdl:message name="getQuoteResponse"><wsdl:part name="parameters" element="tns:getQuoteResponse"/></wsdl:message> + <wsdl:message name="unknownSymbolFault"><wsdl:part name="fault" element="err:unknownSymbol"/></wsdl:message> + + <wsdl:portType name="StockPortType"> + <wsdl:operation name="getQuote"> + <wsdl:input message="tns:getQuoteRequest"/> + <wsdl:output message="tns:getQuoteResponse"/> + <wsdl:fault name="unknownSymbol" message="tns:unknownSymbolFault"/> + </wsdl:operation> + </wsdl:portType> +</wsdl:definitions> diff --git a/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/wsdl20.wsdl b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/wsdl20.wsdl new file mode 100644 index 000000000000..427791d5f906 --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-plugin-generate/src/test/resources/wsdl/wsdl20.wsdl @@ -0,0 +1,23 @@ +<?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. + +--> +<!-- WSDL 2.0: refused. --> +<description xmlns="http://www.w3.org/ns/wsdl" targetNamespace="http://example.com/wsdl20"> + <interface name="Hello"/> +</description>
