001// *************************************************************************************************************************** 002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * 003// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * 004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * 005// * with the License. You may obtain a copy of the License at * 006// * * 007// * http://www.apache.org/licenses/LICENSE-2.0 * 008// * * 009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * 010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * 011// * specific language governing permissions and limitations under the License. * 012// *************************************************************************************************************************** 013package org.apache.juneau.xmlschema; 014 015import static org.apache.juneau.internal.ArrayUtils.*; 016import static org.apache.juneau.xml.annotation.XmlFormat.*; 017 018import java.io.*; 019import java.util.*; 020import java.util.regex.*; 021 022import javax.xml.*; 023import javax.xml.transform.stream.*; 024import javax.xml.validation.*; 025 026import org.apache.juneau.*; 027import org.apache.juneau.serializer.*; 028import org.apache.juneau.xml.*; 029import org.apache.juneau.xml.annotation.*; 030import org.w3c.dom.bootstrap.*; 031import org.w3c.dom.ls.*; 032 033/** 034 * Session object that lives for the duration of a single use of {@link XmlSchemaSerializer}. 035 * 036 * <p> 037 * This class is NOT thread safe. 038 * It is typically discarded after one-time use although it can be reused within the same thread. 039 */ 040public class XmlSchemaSerializerSession extends XmlSerializerSession { 041 042 /** 043 * Create a new session using properties specified in the context. 044 * 045 * @param ctx 046 * The context creating this session object. 047 * The context contains all the configuration settings for this object. 048 * @param args 049 * Runtime arguments. 050 * These specify session-level information such as locale and URI context. 051 * It also include session-level properties that override the properties defined on the bean and 052 * serializer contexts. 053 */ 054 protected XmlSchemaSerializerSession(XmlSerializer ctx, SerializerSessionArgs args) { 055 super(ctx, args); 056 } 057 058 @Override /* SerializerSession */ 059 protected void doSerialize(SerializerPipe out, Object o) throws Exception { 060 if (isEnableNamespaces() && isAutoDetectNamespaces()) 061 findNsfMappings(o); 062 063 Namespace xs = getXsNamespace(); 064 Namespace[] allNs = append(new Namespace[]{getDefaultNamespace()}, getNamespaces()); 065 066 Schemas schemas = new Schemas(this, xs, getDefaultNamespace(), allNs); 067 schemas.process(o); 068 schemas.serializeTo(out.getWriter()); 069 } 070 071 /** 072 * Returns an XML-Schema validator based on the output returned by {@link #doSerialize(SerializerPipe, Object)}; 073 * 074 * @param out The target writer. 075 * @param o The object to serialize. 076 * @return The new validator. 077 * @throws Exception If a problem was detected in the XML-Schema output produced by this serializer. 078 */ 079 public Validator getValidator(SerializerPipe out, Object o) throws Exception { 080 doSerialize(out, o); 081 String xmlSchema = out.getWriter().toString(); 082 083 // create a SchemaFactory capable of understanding WXS schemas 084 SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 085 086 if (xmlSchema.indexOf('\u0000') != -1) { 087 088 // Break it up into a map of namespaceURI->schema document 089 final Map<String,String> schemas = new HashMap<>(); 090 String[] ss = xmlSchema.split("\u0000"); 091 xmlSchema = ss[0]; 092 for (String s : ss) { 093 Matcher m = pTargetNs.matcher(s); 094 if (m.find()) 095 schemas.put(m.group(1), s); 096 } 097 098 // Create a custom resolver 099 factory.setResourceResolver( 100 new LSResourceResolver() { 101 102 @Override /* LSResourceResolver */ 103 public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) { 104 105 String schema = schemas.get(namespaceURI); 106 if (schema == null) 107 throw new FormattedRuntimeException("No schema found for namespaceURI ''{0}''", namespaceURI); 108 109 try { 110 DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); 111 DOMImplementationLS domImplementationLS = (DOMImplementationLS)registry.getDOMImplementation("LS 3.0"); 112 LSInput in = domImplementationLS.createLSInput(); 113 in.setCharacterStream(new StringReader(schema)); 114 in.setSystemId(systemId); 115 return in; 116 117 } catch (Exception e) { 118 throw new RuntimeException(e); 119 } 120 } 121 } 122 ); 123 } 124 return factory.newSchema(new StreamSource(new StringReader(xmlSchema))).newValidator(); 125 } 126 127 private static Pattern pTargetNs = Pattern.compile("targetNamespace=['\"]([^'\"]+)['\"]"); 128 129 130 /* An instance of a global element, global attribute, or XML type to be serialized. */ 131 private static class QueueEntry { 132 Namespace ns; 133 String name; 134 ClassMeta<?> cm; 135 QueueEntry(Namespace ns, String name, ClassMeta<?> cm) { 136 this.ns = ns; 137 this.name = name; 138 this.cm = cm; 139 } 140 } 141 142 /* An encapsulation of all schemas present in the metamodel of the serialized object. */ 143 final class Schemas extends LinkedHashMap<Namespace,Schema> { 144 145 private static final long serialVersionUID = 1L; 146 147 private Namespace defaultNs; 148 BeanSession session; 149 private LinkedList<QueueEntry> 150 elementQueue = new LinkedList<>(), 151 attributeQueue = new LinkedList<>(), 152 typeQueue = new LinkedList<>(); 153 154 Schemas(BeanSession session, Namespace xs, Namespace defaultNs, Namespace[] allNs) throws IOException { 155 this.session = session; 156 this.defaultNs = defaultNs; 157 for (Namespace ns : allNs) 158 put(ns, new Schema(this, xs, ns, defaultNs, allNs)); 159 } 160 161 Schema getSchema(Namespace ns) { 162 if (ns == null) 163 ns = defaultNs; 164 Schema s = get(ns); 165 if (s == null) 166 throw new FormattedRuntimeException("No schema defined for namespace ''{0}''", ns); 167 return s; 168 } 169 170 void process(Object o) throws IOException { 171 ClassMeta<?> cm = getClassMetaForObject(o); 172 Namespace ns = defaultNs; 173 if (cm == null) 174 queueElement(ns, "null", object()); 175 else { 176 XmlClassMeta xmlMeta = cm.getExtendedMeta(XmlClassMeta.class); 177 if (cm.getDictionaryName() != null && xmlMeta.getNamespace() != null) 178 ns = xmlMeta.getNamespace(); 179 queueElement(ns, cm.getDictionaryName(), cm); 180 } 181 processQueue(); 182 } 183 184 void processQueue() throws IOException { 185 boolean b; 186 do { 187 b = false; 188 while (! elementQueue.isEmpty()) { 189 QueueEntry q = elementQueue.removeFirst(); 190 b |= getSchema(q.ns).processElement(q.name, q.cm); 191 } 192 while (! typeQueue.isEmpty()) { 193 QueueEntry q = typeQueue.removeFirst(); 194 b |= getSchema(q.ns).processType(q.name, q.cm); 195 } 196 while (! attributeQueue.isEmpty()) { 197 QueueEntry q = attributeQueue.removeFirst(); 198 b |= getSchema(q.ns).processAttribute(q.name, q.cm); 199 } 200 } while (b); 201 } 202 203 void queueElement(Namespace ns, String name, ClassMeta<?> cm) { 204 elementQueue.add(new QueueEntry(ns, name, cm)); 205 } 206 207 void queueType(Namespace ns, String name, ClassMeta<?> cm) { 208 if (name == null) 209 name = XmlUtils.encodeElementName(cm); 210 typeQueue.add(new QueueEntry(ns, name, cm)); 211 } 212 213 void queueAttribute(Namespace ns, String name, ClassMeta<?> cm) { 214 attributeQueue.add(new QueueEntry(ns, name, cm)); 215 } 216 217 void serializeTo(Writer w) throws IOException { 218 boolean b = false; 219 for (Schema s : values()) { 220 if (b) 221 w.append('\u0000'); 222 w.append(s.toString()); 223 b = true; 224 } 225 } 226 } 227 228 @Override /* SerializerSession */ 229 protected boolean isTrimStrings() { 230 return super.isTrimStrings(); 231 } 232 233 /* An encapsulation of a single schema. */ 234 private final class Schema { 235 private StringWriter sw = new StringWriter(); 236 private XmlWriter w; 237 private Namespace defaultNs, targetNs; 238 private Schemas schemas; 239 private Set<String> 240 processedTypes = new HashSet<>(), 241 processedAttributes = new HashSet<>(), 242 processedElements = new HashSet<>(); 243 244 public Schema(Schemas schemas, Namespace xs, Namespace targetNs, Namespace defaultNs, Namespace[] allNs) throws IOException { 245 this.schemas = schemas; 246 this.defaultNs = defaultNs; 247 this.targetNs = targetNs; 248 w = new XmlWriter(sw, isUseWhitespace(), getMaxIndent(), isTrimStrings(), getQuoteChar(), null, true, null); 249 int i = indent; 250 w.oTag(i, "schema"); 251 w.attr("xmlns", xs.getUri()); 252 w.attr("targetNamespace", targetNs.getUri()); 253 w.attr("elementFormDefault", "qualified"); 254 if (targetNs != defaultNs) 255 w.attr("attributeFormDefault", "qualified"); 256 for (Namespace ns2 : allNs) 257 w.attr("xmlns", ns2.getName(), ns2.getUri()); 258 w.append('>').nl(i); 259 for (Namespace ns : allNs) { 260 if (ns != targetNs) { 261 w.oTag(i+1, "import") 262 .attr("namespace", ns.getUri()) 263 .attr("schemaLocation", ns.getName()+".xsd") 264 .append("/>").nl(i+1); 265 } 266 } 267 } 268 269 boolean processElement(String name, ClassMeta<?> cm) throws IOException { 270 if (processedElements.contains(name)) 271 return false; 272 processedElements.add(name); 273 274 ClassMeta<?> ft = cm.getSerializedClassMeta(schemas.session); 275 if (name == null) 276 name = getElementName(ft); 277 Namespace ns = first(ft.getExtendedMeta(XmlClassMeta.class).getNamespace(), defaultNs); 278 String type = getXmlType(ns, ft); 279 280 w.oTag(indent+1, "element") 281 .attr("name", XmlUtils.encodeElementName(name)) 282 .attr("type", type) 283 .append('/').append('>').nl(indent+1); 284 285 schemas.queueType(ns, null, ft); 286 schemas.processQueue(); 287 return true; 288 } 289 290 boolean processAttribute(String name, ClassMeta<?> cm) throws IOException { 291 if (processedAttributes.contains(name)) 292 return false; 293 processedAttributes.add(name); 294 295 String type = getXmlAttrType(cm); 296 297 w.oTag(indent+1, "attribute") 298 .attr("name", name) 299 .attr("type", type) 300 .append('/').append('>').nl(indent+1); 301 302 return true; 303 } 304 305 boolean processType(String name, ClassMeta<?> cm) throws IOException { 306 if (processedTypes.contains(name)) 307 return false; 308 processedTypes.add(name); 309 310 int i = indent + 1; 311 312 cm = cm.getSerializedClassMeta(schemas.session); 313 XmlBeanMeta xbm = cm.isBean() ? cm.getBeanMeta().getExtendedMeta(XmlBeanMeta.class) : null; 314 315 w.oTag(i, "complexType") 316 .attr("name", name); 317 318 // This element can have mixed content if: 319 // 1) It's a generic Object (so it can theoretically be anything) 320 // 2) The bean has a property defined with @XmlFormat.CONTENT. 321 if ((xbm != null && (xbm.getContentFormat() != null && xbm.getContentFormat().isOneOf(TEXT,TEXT_PWS,MIXED,MIXED_PWS,XMLTEXT))) || ! cm.isMapOrBean()) 322 w.attr("mixed", "true"); 323 324 w.cTag().nl(i); 325 326 if (! (cm.isMapOrBean() || cm.isCollectionOrArray() || (cm.isAbstract() && ! cm.isNumber()) || cm.isObject())) { 327 w.oTag(i+1, "attribute").attr("name", getBeanTypePropertyName(cm)).attr("type", "string").ceTag().nl(i+1); 328 329 } else { 330 331 //----- Bean ----- 332 if (cm.isBean()) { 333 BeanMeta<?> bm = cm.getBeanMeta(); 334 335 boolean hasChildElements = false; 336 337 for (BeanPropertyMeta pMeta : bm.getPropertyMetas()) { 338 if (pMeta.canRead()) { 339 XmlFormat bpXml = pMeta.getExtendedMeta(XmlBeanPropertyMeta.class).getXmlFormat(); 340 if (bpXml != XmlFormat.ATTR) 341 hasChildElements = true; 342 } 343 } 344 345 XmlBeanMeta xbm2 = bm.getExtendedMeta(XmlBeanMeta.class); 346 if (xbm2.getContentProperty() != null && xbm2.getContentFormat() == ELEMENTS) { 347 w.sTag(i+1, "sequence").nl(i+1); 348 w.oTag(i+2, "any") 349 .attr("processContents", "skip") 350 .attr("minOccurs", 0) 351 .ceTag().nl(i+2); 352 w.eTag(i+1, "sequence").nl(i+1); 353 354 } else if (hasChildElements) { 355 356 boolean hasOtherNsElement = false; 357 boolean hasCollapsed = false; 358 359 for (BeanPropertyMeta pMeta : bm.getPropertyMetas()) { 360 if (pMeta.canRead()) { 361 XmlBeanPropertyMeta xmlMeta = pMeta.getExtendedMeta(XmlBeanPropertyMeta.class); 362 if (xmlMeta.getXmlFormat() != ATTR) { 363 if (xmlMeta.getNamespace() != null) { 364 ClassMeta<?> ct2 = pMeta.getClassMeta(); 365 Namespace cNs = first(xmlMeta.getNamespace(), ct2.getExtendedMeta(XmlClassMeta.class).getNamespace(), cm.getExtendedMeta(XmlClassMeta.class).getNamespace(), defaultNs); 366 // Child element is in another namespace. 367 schemas.queueElement(cNs, pMeta.getName(), ct2); 368 hasOtherNsElement = true; 369 } 370 if (xmlMeta.getXmlFormat() == COLLAPSED) 371 hasCollapsed = true; 372 } 373 374 } 375 } 376 377 if (hasOtherNsElement || hasCollapsed) { 378 // If this bean has any child elements in another namespace, 379 // we need to add an <any> element. 380 w.oTag(i+1, "choice").attr("maxOccurs", "unbounded").cTag().nl(i+1); 381 w.oTag(i+2, "any") 382 .attr("processContents", "skip") 383 .attr("minOccurs", 0) 384 .ceTag().nl(i+2); 385 w.eTag(i+1, "choice").nl(i+1); 386 387 } else { 388 w.sTag(i+1, "all").nl(i+1); 389 for (BeanPropertyMeta pMeta : bm.getPropertyMetas()) { 390 if (pMeta.canRead()) { 391 XmlBeanPropertyMeta xmlMeta = pMeta.getExtendedMeta(XmlBeanPropertyMeta.class); 392 if (xmlMeta.getXmlFormat() != ATTR) { 393 boolean isCollapsed = xmlMeta.getXmlFormat() == COLLAPSED; 394 ClassMeta<?> ct2 = pMeta.getClassMeta(); 395 String childName = pMeta.getName(); 396 if (isCollapsed) { 397 if (xmlMeta.getChildName() != null) 398 childName = xmlMeta.getChildName(); 399 ct2 = pMeta.getClassMeta().getElementType(); 400 } 401 Namespace cNs = first(xmlMeta.getNamespace(), ct2.getExtendedMeta(XmlClassMeta.class).getNamespace(), cm.getExtendedMeta(XmlClassMeta.class).getNamespace(), defaultNs); 402 if (xmlMeta.getNamespace() == null) { 403 w.oTag(i+2, "element") 404 .attr("name", XmlUtils.encodeElementName(childName), false) 405 .attr("type", getXmlType(cNs, ct2)) 406 .attr("minOccurs", 0); 407 408 w.ceTag().nl(i+2); 409 } else { 410 // Child element is in another namespace. 411 schemas.queueElement(cNs, pMeta.getName(), ct2); 412 hasOtherNsElement = true; 413 } 414 } 415 } 416 } 417 w.eTag(i+1, "all").nl(i+1); 418 } 419 420 } 421 422 for (BeanPropertyMeta pMeta : bm.getExtendedMeta(XmlBeanMeta.class).getAttrProperties().values()) { 423 if (pMeta.canRead()) { 424 Namespace pNs = pMeta.getExtendedMeta(XmlBeanPropertyMeta.class).getNamespace(); 425 if (pNs == null) 426 pNs = defaultNs; 427 428 // If the bean attribute has a different namespace than the bean, then it needs to 429 // be added as a top-level entry in the appropriate schema file. 430 if (pNs != targetNs) { 431 schemas.queueAttribute(pNs, pMeta.getName(), pMeta.getClassMeta()); 432 w.oTag(i+1, "attribute") 433 //.attr("name", pMeta.getName(), true) 434 .attr("ref", pNs.getName() + ':' + pMeta.getName()) 435 .ceTag().nl(i+1); 436 } 437 438 // Otherwise, it's just a plain attribute of this bean. 439 else { 440 w.oTag(i+1, "attribute") 441 .attr("name", pMeta.getName(), true) 442 .attr("type", getXmlAttrType(pMeta.getClassMeta())) 443 .ceTag().nl(i+1); 444 } 445 } 446 } 447 448 //----- Collection ----- 449 } else if (cm.isCollectionOrArray()) { 450 ClassMeta<?> elementType = cm.getElementType(); 451 if (elementType.isObject()) { 452 w.sTag(i+1, "sequence").nl(i+1); 453 w.oTag(i+2, "any") 454 .attr("processContents", "skip") 455 .attr("maxOccurs", "unbounded") 456 .attr("minOccurs", "0") 457 .ceTag().nl(i+2); 458 w.eTag(i+1, "sequence").nl(i+1); 459 } else { 460 Namespace cNs = first(elementType.getExtendedMeta(XmlClassMeta.class).getNamespace(), cm.getExtendedMeta(XmlClassMeta.class).getNamespace(), defaultNs); 461 schemas.queueType(cNs, null, elementType); 462 w.sTag(i+1, "sequence").nl(i+1); 463 w.oTag(i+2, "any") 464 .attr("processContents", "skip") 465 .attr("maxOccurs", "unbounded") 466 .attr("minOccurs", "0") 467 .ceTag().nl(i+2); 468 w.eTag(i+1, "sequence").nl(i+1); 469 } 470 471 //----- Map ----- 472 } else if (cm.isMap() || cm.isAbstract() || cm.isObject()) { 473 w.sTag(i+1, "sequence").nl(i+1); 474 w.oTag(i+2, "any") 475 .attr("processContents", "skip") 476 .attr("maxOccurs", "unbounded") 477 .attr("minOccurs", "0") 478 .ceTag().nl(i+2); 479 w.eTag(i+1, "sequence").nl(i+1); 480 } 481 482 w.oTag(i+1, "attribute") 483 .attr("name", getBeanTypePropertyName(null)) 484 .attr("type", "string") 485 .ceTag().nl(i+1); 486 } 487 488 w.eTag(i, "complexType").nl(i); 489 schemas.processQueue(); 490 491 return true; 492 } 493 494 private String getElementName(ClassMeta<?> cm) { 495 cm = cm.getSerializedClassMeta(schemas.session); 496 String name = cm.getDictionaryName(); 497 498 if (name == null) { 499 if (cm.isBoolean()) 500 name = "boolean"; 501 else if (cm.isNumber()) 502 name = "number"; 503 else if (cm.isCollectionOrArray()) 504 name = "array"; 505 else if (! (cm.isMapOrBean() || cm.isCollectionOrArray() || cm.isObject() || cm.isAbstract())) 506 name = "string"; 507 else 508 name = "object"; 509 } 510 return name; 511 } 512 513 @Override /* Object */ 514 public String toString() { 515 try { 516 w.eTag(indent, "schema").nl(indent); 517 } catch (IOException e) { 518 throw new RuntimeException(e); // Shouldn't happen. 519 } 520 return sw.toString(); 521 } 522 523 private String getXmlType(Namespace currentNs, ClassMeta<?> cm) { 524 String name = null; 525 cm = cm.getSerializedClassMeta(schemas.session); 526 if (currentNs == targetNs) { 527 if (cm.isPrimitive()) { 528 if (cm.isBoolean()) 529 name = "boolean"; 530 else if (cm.isNumber()) { 531 if (cm.isDecimal()) 532 name = "decimal"; 533 else 534 name = "integer"; 535 } 536 } 537 } 538 if (name == null) { 539 name = XmlUtils.encodeElementName(cm); 540 schemas.queueType(currentNs, name, cm); 541 return currentNs.getName() + ":" + name; 542 } 543 544 return name; 545 } 546 } 547 548 @SafeVarargs 549 static <T> T first(T...tt) { 550 for (T t : tt) 551 if (t != null) 552 return t; 553 return null; 554 } 555 556 static String getXmlAttrType(ClassMeta<?> cm) { 557 if (cm.isBoolean()) 558 return "boolean"; 559 if (cm.isNumber()) { 560 if (cm.isDecimal()) 561 return "decimal"; 562 return "integer"; 563 } 564 return "string"; 565 } 566}