gnodet-bot commented on code in PR #30597: URL: https://github.com/apache/camel/pull/30597#discussion_r4657562156
########## components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdSchemaLoader.java: ########## @@ -0,0 +1,296 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.dataformat.xsdjson; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; +import java.util.Locale; +import java.util.regex.Pattern; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + +import org.xml.sax.ErrorHandler; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +import org.apache.camel.CamelContext; +import org.apache.camel.support.ResourceHelper; +import org.apache.ws.commons.schema.XmlSchemaCollection; + +/** + * Loads an XML Schema, or the inline schemas of a WSDL, into an {@link XmlSchemaCollection}. + * <p/> + * The schema is configuration of the route and so is trusted, yet every document is parsed with DOCTYPE declarations + * and external entities turned off, and xs:import and xs:include are only followed to resources with the same scheme as + * the schema option, so a schema loaded over https cannot pull in a local file. + */ +final class XsdSchemaLoader { + + static final String XSD_NS = XMLConstants.W3C_XML_SCHEMA_NS_URI; + static final String WSDL11_NS = "http://schemas.xmlsoap.org/wsdl/"; + static final String WSDL20_NS = "http://www.w3.org/ns/wsdl"; + + private static final Pattern SCHEME = Pattern.compile("^[a-zA-Z][a-zA-Z0-9+.-]+:.*"); + + private final CamelContext camelContext; + private final String location; + private final String scheme; + + XsdSchemaLoader(CamelContext camelContext, String schema) { + this.camelContext = camelContext; + String s = schema.trim(); + this.location = hasScheme(s) ? s : "classpath:" + s; + this.scheme = schemeOf(this.location); + } + + XmlSchemaCollection load() throws Exception { + Document doc = parse(read(location), location); + Element root = doc.getDocumentElement(); + XmlSchemaCollection collection = new XmlSchemaCollection(); + collection.setSchemaResolver(this::resolve); + String ns = root.getNamespaceURI(); + String name = root.getLocalName(); + if (XSD_NS.equals(ns) && "schema".equals(name)) { + collection.read(doc, location); + } else if (WSDL11_NS.equals(ns) && "definitions".equals(name) || WSDL20_NS.equals(ns) && "description".equals(name)) { Review Comment: 💡 **Readability: add parentheses to the mixed `&&`/`||` condition.** Java operator precedence (`&&` binds tighter than `||`) makes this correct, but a future reader has to stop and reason about it. Explicit parentheses remove the ambiguity at zero runtime cost. ```suggestion } else if ((WSDL11_NS.equals(ns) && "definitions".equals(name)) || (WSDL20_NS.equals(ns) && "description".equals(name))) { ``` ########## components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/JsonToXml.java: ########## @@ -0,0 +1,447 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.dataformat.xsdjson; + +import java.math.BigDecimal; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Deque; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.xml.XMLConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.camel.dataformat.xsdjson.XsdModel.Attribute; +import org.apache.camel.dataformat.xsdjson.XsdModel.Element; +import org.apache.camel.dataformat.xsdjson.XsdModel.Group; +import org.apache.camel.dataformat.xsdjson.XsdModel.GroupKind; +import org.apache.camel.dataformat.xsdjson.XsdModel.SimpleKind; +import org.apache.camel.dataformat.xsdjson.XsdModel.SimpleType; +import org.apache.camel.dataformat.xsdjson.XsdModel.Type; + +/** + * Writes a JSON tree (a Map, a List, or a value) as XML with StAX, in the order and namespaces of the schema. + */ +final class JsonToXml { + + private static final String XSI_PREFIX = "xsi"; + + private final XsdModel model; + private final boolean ignoreUnknown; + private final String textName; + private final boolean pretty; + private final XMLStreamWriter writer; + private final Set<String> inScope = new HashSet<>(); + private final Deque<List<String>> declared = new ArrayDeque<>(); + private int generated; + + JsonToXml(XsdModel model, boolean ignoreUnknown, String textName, boolean pretty, XMLStreamWriter writer) { + this.model = model; + this.ignoreUnknown = ignoreUnknown; + this.textName = textName; + this.pretty = pretty; + this.writer = writer; + } + + void write(Element root, Object value) throws XMLStreamException { + if (value == null) { + if (!root.nillable) { + throw new IllegalArgumentException( + "The JSON is null, but the root element " + root.name + " is not nillable"); + } + } + writeElement(root, value, "/" + root.jsonName(), 0); + } + + private void writeElement(Element element, Object value, String path, int depth) throws XMLStreamException { + if (depth > XmlToJson.MAX_DEPTH) { + throw new IllegalArgumentException("The JSON is nested deeper than " + XmlToJson.MAX_DEPTH + " at " + path); + } + if (element.unsupported != null) { + throw new IllegalArgumentException("Cannot map " + path + ": " + element.unsupported); + } + Type type = element.type; + if (type.unsupported != null) { + throw new IllegalArgumentException("Cannot map " + path + ": " + type.unsupported); + } + if (type.conflict != null) { + throw new IllegalArgumentException(type.conflict); + } + if (value == null) { + if (!element.nillable) { + if (element.optional) { + return; + } + throw new IllegalArgumentException( + "The JSON field " + path + " is null, but the element is neither nillable nor optional"); + } + indent(depth); + startElement(element, List.of(), true); + writer.writeAttribute(XSI_PREFIX, XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "nil", "true"); + endElement(); + return; + } + indent(depth); + if (!type.complex) { + startElement(element, List.of(), false); + writer.writeCharacters(text(type.simple, value, path)); + endElement(); + return; + } + if (!(value instanceof Map<?, ?> map)) { + if (type.hasSimpleContent() && !(value instanceof Collection)) { + // simple content given as its value only, without attributes + startElement(element, List.of(), false); + writer.writeCharacters(text(type.simple, value, path)); + endElement(); + return; + } + throw new IllegalArgumentException( + "The JSON field " + path + " must be an object for the element " + element.name + ", but is " + + describe(value)); + } + checkUnknown(type, map, path); + List<Attribute> attributes = new ArrayList<>(); + for (Attribute a : type.attributes) { + if (map.get(a.jsonName) != null) { + attributes.add(a); + } + } + startElement(element, attributes, false); + for (Attribute a : attributes) { + String text = text(a.type, map.get(a.jsonName), path + "/" + a.jsonName); + String ns = a.name.getNamespaceURI(); + if (ns.isEmpty()) { + writer.writeAttribute(a.name.getLocalPart(), text); + } else { + writer.writeAttribute(prefix(ns), ns, a.name.getLocalPart(), text); + } + } + if (type.hasSimpleContent()) { + Object text = map.get(textName); + if (text != null) { + writer.writeCharacters(text(type.simple, text, path + "/" + textName)); + } + endElement(); + return; + } + boolean children = false; + if (type.content != null) { + children = writeGroup(type.content, map, path, depth + 1); + } + if (children && pretty) { + writer.writeCharacters("\n" + " ".repeat(depth)); + } + endElement(); + } + + private void checkUnknown(Type type, Map<?, ?> map, String path) { + if (ignoreUnknown) { + return; + } + for (Object key : map.keySet()) { + String k = String.valueOf(key); + if (type.children.containsKey(k) || type.attributesByJsonName.containsKey(k) + || type.hasSimpleContent() && textName.equals(k)) { + continue; + } + if (type.wildcard) { + throw new IllegalArgumentException( + "Cannot map " + path + "/" + k + ": the field would match xs:any, and xs:any content is not supported"); + } + throw new IllegalArgumentException( + "The JSON field " + path + "/" + k + " is not declared by the type " + type.displayName() + + " (set ignoreUnknown to skip it). The type has: " + names(type)); + } + } + + private static String names(Type type) { + List<String> names = new ArrayList<>(type.attributesByJsonName.keySet()); + names.addAll(type.children.keySet()); + return names.toString(); + } + + /** + * Writes the members of a group in schema order. Returns whether an element was written. + */ + private boolean writeGroup(Group group, Map<?, ?> map, String path, int depth) throws XMLStreamException { + boolean written = false; + if (group.kind == GroupKind.ALL) { + // xs:all has no order: keep the order of the JSON + for (Object key : map.keySet()) { + for (Object member : group.members) { + if (member instanceof Element e && e.jsonName().equals(key)) { + written |= writeMember(e, map, path, depth, -1); + } + } + } + return written; + } + if (group.kind == GroupKind.CHOICE) { + List<Object> present = new ArrayList<>(); + for (Object member : group.members) { + if (isPresent(member, map)) { + present.add(member); + } + } + if (present.size() > 1 && !group.repeating) { + throw new IllegalArgumentException( + "The JSON at " + path + " has " + describeMembers(present) + + ", but the schema has an xs:choice that allows only one of them"); + } + for (Object member : present) { + written |= writeMemberOrGroup(member, map, path, depth); + } + return written; + } + if (group.repeating) { + // a repeating sequence: the items of its elements are written by index, a[0] b[0] a[1] b[1] ... + int size = 0; + for (Object member : group.members) { + if (member instanceof Element e) { + size = Math.max(size, asList(map.get(e.jsonName())).size()); + } + } + for (int i = 0; i < size; i++) { + for (Object member : group.members) { + if (member instanceof Element e) { + written |= writeMember(e, map, path, depth, i); + } else if (i == 0) { + written |= writeMemberOrGroup(member, map, path, depth); + } + } + } + return written; + } + for (Object member : group.members) { + written |= writeMemberOrGroup(member, map, path, depth); + } + return written; + } + + private boolean writeMemberOrGroup(Object member, Map<?, ?> map, String path, int depth) throws XMLStreamException { + if (member instanceof Element e) { + return writeMember(e, map, path, depth, -1); + } + return writeGroup((Group) member, map, path, depth); + } + + /** + * Writes an element of a group, all its items, or only the item at index when index is 0 or more. + */ + private boolean writeMember(Element e, Map<?, ?> map, String path, int depth, int index) throws XMLStreamException { + if (!map.containsKey(e.jsonName())) { + return false; + } + Object value = map.get(e.jsonName()); + String childPath = path + "/" + e.jsonName(); + if (e.array) { + List<?> items = asList(value); + if (index >= 0) { + if (index >= items.size()) { + return false; + } + writeElement(e, items.get(index), childPath + "[" + index + "]", depth); + return true; + } + for (int i = 0; i < items.size(); i++) { + writeElement(e, items.get(i), childPath + "[" + i + "]", depth); + } + return !items.isEmpty(); + } + if (value instanceof Collection && !(e.type != null && !e.type.complex && e.type.simple.list())) { + throw new IllegalArgumentException( + "The JSON field " + childPath + " is an array, but the element " + e.name + + " occurs at most once (maxOccurs=1)"); + } + if (value == null && !e.nillable && e.optional) { + return false; + } + writeElement(e, value, childPath, depth); + return true; + } + + private static List<?> asList(Object value) { + if (value == null) { + List<Object> single = new ArrayList<>(1); + single.add(null); + return single; Review Comment: ⚠️ **Semantic issue: `null` for an array field writes one `xsi:nil` element instead of zero.** `asList(null)` returns `[null]`, so when the JSON for an array element field is `null` (e.g. from a manually-constructed Map), `writeMember` calls `writeElement` once with `null` as the value. For a nillable element that produces one `xsi:nil="true"` XML element; for a non-nillable required element it throws. The parallel non-array path (line 275) correctly short-circuits on `null` with `return false`. `null` for an array should consistently mean "absent" — a user who wants one null item can pass `[null]`. ```suggestion private static List<?> asList(Object value) { if (value == null) { return List.of(); } ``` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
