001/* 002 * (C) Copyright 2006-2012 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Bogdan Stefanescu 018 * Wojciech Sulejman 019 * Florent Guillaume 020 * Thierry Delprat 021 * Nicolas Chapurlat <nchapurlat@nuxeo.com> 022 */ 023package org.nuxeo.ecm.core.schema; 024 025import static com.sun.xml.xsom.XSFacet.FACET_ENUMERATION; 026import static com.sun.xml.xsom.XSFacet.FACET_LENGTH; 027import static com.sun.xml.xsom.XSFacet.FACET_MAXEXCLUSIVE; 028import static com.sun.xml.xsom.XSFacet.FACET_MAXINCLUSIVE; 029import static com.sun.xml.xsom.XSFacet.FACET_MAXLENGTH; 030import static com.sun.xml.xsom.XSFacet.FACET_MINEXCLUSIVE; 031import static com.sun.xml.xsom.XSFacet.FACET_MININCLUSIVE; 032import static com.sun.xml.xsom.XSFacet.FACET_MINLENGTH; 033import static com.sun.xml.xsom.XSFacet.FACET_PATTERN; 034 035import java.io.File; 036import java.io.IOException; 037import java.net.URL; 038import java.util.ArrayList; 039import java.util.Collection; 040import java.util.HashMap; 041import java.util.HashSet; 042import java.util.List; 043import java.util.Map; 044import java.util.Set; 045 046import org.apache.commons.logging.Log; 047import org.apache.commons.logging.LogFactory; 048import org.nuxeo.ecm.core.schema.types.ComplexType; 049import org.nuxeo.ecm.core.schema.types.ComplexTypeImpl; 050import org.nuxeo.ecm.core.schema.types.Field; 051import org.nuxeo.ecm.core.schema.types.ListType; 052import org.nuxeo.ecm.core.schema.types.ListTypeImpl; 053import org.nuxeo.ecm.core.schema.types.Schema; 054import org.nuxeo.ecm.core.schema.types.SchemaImpl; 055import org.nuxeo.ecm.core.schema.types.SimpleType; 056import org.nuxeo.ecm.core.schema.types.SimpleTypeImpl; 057import org.nuxeo.ecm.core.schema.types.Type; 058import org.nuxeo.ecm.core.schema.types.TypeBindingException; 059import org.nuxeo.ecm.core.schema.types.TypeException; 060import org.nuxeo.ecm.core.schema.types.constraints.Constraint; 061import org.nuxeo.ecm.core.schema.types.constraints.ConstraintUtils; 062import org.nuxeo.ecm.core.schema.types.constraints.DateIntervalConstraint; 063import org.nuxeo.ecm.core.schema.types.constraints.EnumConstraint; 064import org.nuxeo.ecm.core.schema.types.constraints.LengthConstraint; 065import org.nuxeo.ecm.core.schema.types.constraints.NotNullConstraint; 066import org.nuxeo.ecm.core.schema.types.constraints.NumericIntervalConstraint; 067import org.nuxeo.ecm.core.schema.types.constraints.ObjectResolverConstraint; 068import org.nuxeo.ecm.core.schema.types.constraints.PatternConstraint; 069import org.nuxeo.ecm.core.schema.types.resolver.ObjectResolver; 070import org.nuxeo.ecm.core.schema.types.resolver.ObjectResolverService; 071import org.nuxeo.runtime.api.Framework; 072import org.xml.sax.EntityResolver; 073import org.xml.sax.ErrorHandler; 074import org.xml.sax.InputSource; 075import org.xml.sax.SAXException; 076import org.xml.sax.SAXParseException; 077 078import com.sun.xml.xsom.ForeignAttributes; 079import com.sun.xml.xsom.XSAttributeDecl; 080import com.sun.xml.xsom.XSAttributeUse; 081import com.sun.xml.xsom.XSComplexType; 082import com.sun.xml.xsom.XSContentType; 083import com.sun.xml.xsom.XSElementDecl; 084import com.sun.xml.xsom.XSFacet; 085import com.sun.xml.xsom.XSListSimpleType; 086import com.sun.xml.xsom.XSModelGroup; 087import com.sun.xml.xsom.XSParticle; 088import com.sun.xml.xsom.XSSchema; 089import com.sun.xml.xsom.XSSchemaSet; 090import com.sun.xml.xsom.XSTerm; 091import com.sun.xml.xsom.XSType; 092import com.sun.xml.xsom.XmlString; 093import com.sun.xml.xsom.impl.RestrictionSimpleTypeImpl; 094import com.sun.xml.xsom.parser.XSOMParser; 095 096/** 097 * Loader of XSD schemas into Nuxeo Schema objects. 098 */ 099public class XSDLoader { 100 101 private static final String ATTR_CORE_EXTERNAL_REFERENCES = "resolver"; 102 103 private static final Log log = LogFactory.getLog(XSDLoader.class); 104 105 private static final String ANONYMOUS_TYPE_SUFFIX = "#anonymousType"; 106 107 private static final String NAMESPACE_CORE_VALIDATION = "http://www.nuxeo.org/ecm/schemas/core/validation/"; 108 109 private static final String NAMESPACE_CORE_EXTERNAL_REFERENCES = "http://www.nuxeo.org/ecm/schemas/core/external-references/"; 110 111 private static final String NS_XSD = "http://www.w3.org/2001/XMLSchema"; 112 113 protected final SchemaManagerImpl schemaManager; 114 115 protected List<String> referencedXSD = new ArrayList<String>(); 116 117 protected boolean collectReferencedXSD = false; 118 119 protected SchemaBindingDescriptor sd; 120 121 private ObjectResolverService referenceService; 122 123 protected ObjectResolverService getObjectResolverService() { 124 if (referenceService == null) { 125 referenceService = Framework.getService(ObjectResolverService.class); 126 } 127 return referenceService; 128 } 129 130 public XSDLoader(SchemaManagerImpl schemaManager) { 131 this.schemaManager = schemaManager; 132 } 133 134 public XSDLoader(SchemaManagerImpl schemaManager, SchemaBindingDescriptor sd) { 135 this.schemaManager = schemaManager; 136 this.sd = sd; 137 } 138 139 public XSDLoader(SchemaManagerImpl schemaManager, boolean collectReferencedXSD) { 140 this.schemaManager = schemaManager; 141 this.collectReferencedXSD = collectReferencedXSD; 142 } 143 144 protected void registerSchema(Schema schema) { 145 schemaManager.registerSchema(schema); 146 } 147 148 protected Type getType(String name) { 149 return schemaManager.getType(name); 150 } 151 152 protected XSOMParser getParser() { 153 XSOMParser parser = new XSOMParser(); 154 ErrorHandler errorHandler = new SchemaErrorHandler(); 155 parser.setErrorHandler(errorHandler); 156 if (sd != null) { 157 parser.setEntityResolver(new NXSchemaResolver(schemaManager, sd)); 158 } 159 return parser; 160 } 161 162 protected static class NXSchemaResolver implements EntityResolver { 163 164 protected SchemaManagerImpl schemaManager; 165 166 protected SchemaBindingDescriptor sd; 167 168 NXSchemaResolver(SchemaManagerImpl schemaManager, SchemaBindingDescriptor sd) { 169 this.schemaManager = schemaManager; 170 this.sd = sd; 171 } 172 173 @Override 174 public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { 175 176 String[] parts = systemId.split("/" + SchemaManagerImpl.SCHEMAS_DIR_NAME + "/"); 177 String importXSDSubPath = parts[1]; 178 179 File xsd = new File(schemaManager.getSchemasDir(), importXSDSubPath); 180 if (!xsd.exists()) { 181 int idx = sd.src.lastIndexOf("/"); 182 importXSDSubPath = sd.src.substring(0, idx + 1) + importXSDSubPath; 183 URL url = sd.context.getLocalResource(importXSDSubPath); 184 if (url == null) { 185 // try asking the class loader 186 url = sd.context.getResource(importXSDSubPath); 187 } 188 if (url != null) { 189 return new InputSource(url.openStream()); 190 } 191 } 192 193 return null; 194 } 195 196 } 197 198 protected static class SchemaErrorHandler implements ErrorHandler { 199 @Override 200 public void error(SAXParseException e) throws SAXException { 201 log.error("Error: " + e.getMessage()); 202 throw e; 203 } 204 205 @Override 206 public void fatalError(SAXParseException e) throws SAXException { 207 log.error("FatalError: " + e.getMessage()); 208 throw e; 209 } 210 211 @Override 212 public void warning(SAXParseException e) throws SAXException { 213 log.error("Warning: " + e.getMessage()); 214 } 215 } 216 217 // called by SchemaManagerImpl 218 public Schema loadSchema(String name, String prefix, File file) throws SAXException, IOException, TypeException { 219 return loadSchema(name, prefix, file, null); 220 } 221 222 /** 223 * Called by schema manager. 224 * 225 * @since 5.7 226 */ 227 public Schema loadSchema(String name, String prefix, File file, String xsdElement) 228 throws SAXException, IOException, TypeException { 229 return loadSchema(name, prefix, file, null, false); 230 } 231 232 /** 233 * @param isVersionWritable if true, the schema's fields will be writable even for Version document. 234 * @since 8.4 235 */ 236 public Schema loadSchema(String name, String prefix, File file, String xsdElement, boolean isVersionWritable) 237 throws SAXException, IOException, TypeException { 238 XSOMParser parser = getParser(); 239 String systemId = file.toURI().toURL().toExternalForm(); 240 if (file.getPath().startsWith("\\\\")) { // Windows UNC share 241 // work around a bug in Xerces due to 242 // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5086147 243 // (xsom passes a systemId of the form file://server/share/... 244 // but this is not parsed correctly when turned back into 245 // a File object inside Xerces) 246 systemId = systemId.replace("file://", "file:////"); 247 } 248 try { 249 parser.parse(systemId); 250 } catch (SAXParseException e) { 251 throw new SAXException("Error parsing schema: " + systemId, e); 252 } 253 254 XSSchemaSet xsSchemas = parser.getResult(); 255 if (collectReferencedXSD) { 256 collectReferencedXSD(xsSchemas); 257 } 258 return loadSchema(name, prefix, xsSchemas, xsdElement, isVersionWritable); 259 } 260 261 protected void collectReferencedXSD(XSSchemaSet xsSchemas) { 262 263 Collection<XSSchema> schemas = xsSchemas.getSchemas(); 264 String ns = null; 265 for (XSSchema s : schemas) { 266 ns = s.getTargetNamespace(); 267 if (ns.length() <= 0 || ns.equals(NS_XSD)) { 268 continue; 269 } 270 271 String systemId = s.getLocator().getSystemId(); 272 if (systemId != null && systemId.startsWith("file:/")) { 273 String filePath = systemId.substring(6); 274 if (!referencedXSD.contains(filePath)) { 275 referencedXSD.add(filePath); 276 } 277 } 278 } 279 280 } 281 282 /** 283 * Create Nuxeo schema from a XSD resource. If xsdElement is non null and correspont to the name of a complex 284 * element, the schema is created from the target complex type instead of from the global schema 285 * 286 * @since 5.7 287 * @param name schema name 288 * @param prefix schema prefix 289 * @param url url to load the XSD resource 290 * @param xsdElement name of the complex element to use as root of the schema 291 * @return 292 * @throws SAXException 293 * @throws TypeException 294 * @since 5.7 295 */ 296 public Schema loadSchema(String name, String prefix, URL url, String xsdElement) 297 throws SAXException, TypeException { 298 XSOMParser parser = getParser(); 299 parser.parse(url); 300 XSSchemaSet xsSchemas = parser.getResult(); 301 return loadSchema(name, prefix, xsSchemas, xsdElement); 302 } 303 304 // called by tests 305 public Schema loadSchema(String name, String prefix, URL url) throws SAXException, TypeException { 306 return loadSchema(name, prefix, url, null); 307 } 308 309 /** 310 * @since 8.4 311 */ 312 protected Schema loadSchema(String name, String prefix, XSSchemaSet schemaSet, String xsdElement) 313 throws SAXException, TypeException { 314 return loadSchema(name, prefix, schemaSet, xsdElement, false); 315 } 316 317 protected Schema loadSchema(String name, String prefix, XSSchemaSet schemaSet, String xsdElement, 318 boolean isVersionWritable) throws SAXException, TypeException { 319 if (schemaSet == null) { 320 return null; 321 } 322 Collection<XSSchema> schemas = schemaSet.getSchemas(); 323 XSSchema schema = null; 324 String ns = null; 325 for (XSSchema s : schemas) { 326 ns = s.getTargetNamespace(); 327 if (ns.length() > 0 && !ns.equals(NS_XSD)) { 328 schema = s; 329 break; 330 } 331 } 332 if (schema == null) { 333 return null; 334 } 335 Schema ecmSchema = new SchemaImpl(name, new Namespace(ns, prefix), isVersionWritable); 336 337 // load elements 338 Collection<XSElementDecl> elements = schema.getElementDecls().values(); 339 for (XSElementDecl el : elements) { 340 // register the type if not yet registered 341 Type ecmType = loadType(ecmSchema, el.getType(), el.getName()); 342 if (ecmType != null) { 343 // add the field to the schema 344 createField(ecmSchema, el, ecmType); 345 } else { 346 log.warn("Failed to load field " + el.getName() + " : " + el.getType()); 347 } 348 } 349 350 // load attributes 351 Collection<XSAttributeDecl> attributes = schema.getAttributeDecls().values(); 352 for (XSAttributeDecl att : attributes) { 353 // register the type if not yet registered 354 Type ecmType = loadType(ecmSchema, att.getType(), att.getName()); 355 if (ecmType != null) { 356 // add the field to the schema 357 createField(ecmSchema, att, ecmType, true); 358 } else { 359 log.warn("Failed to load field from attribute " + att.getName() + " : " + att.getType()); 360 } 361 } 362 363 if (xsdElement != null) { 364 Field singleComplexField = ecmSchema.getField(xsdElement); 365 if (singleComplexField == null) { 366 log.warn("Unable to find element " + xsdElement + " to rebase schema " + name); 367 } else { 368 if (singleComplexField.getType().isComplexType()) { 369 ComplexType singleComplexFieldType = (ComplexType) singleComplexField.getType(); 370 ecmSchema = new SchemaImpl(singleComplexFieldType, name, new Namespace(ns, prefix), 371 isVersionWritable); 372 } else { 373 log.warn("can not rebase schema " + name + " on " + xsdElement + " that is not a complex type"); 374 } 375 } 376 } 377 378 registerSchema(ecmSchema); 379 return ecmSchema; 380 } 381 382 protected Type loadType(Schema schema, XSType type, String fieldName) throws TypeBindingException { 383 String name; 384 if (type.getName() == null || type.isLocal()) { 385 name = getAnonymousTypeName(type, fieldName); 386 if (name == null) { 387 log.warn("Unable to load type - no name found"); 388 return null; 389 } 390 } else { 391 name = type.getName(); 392 } 393 // look into global types 394 Type ecmType = getType(name); 395 if (ecmType != null) { 396 return ecmType; 397 } 398 // look into user types for this schema 399 ecmType = schema.getType(name); 400 if (ecmType != null) { 401 return ecmType; 402 } 403 // maybe an alias to a primitive type? 404 if (type.getTargetNamespace().equals(NS_XSD)) { 405 ecmType = XSDTypes.getType(name); // find alias 406 if (ecmType == null) { 407 log.warn("Cannot use unknown XSD type: " + name); 408 } 409 return ecmType; 410 } 411 if (type.isSimpleType()) { 412 if (type instanceof XSListSimpleType) { 413 ecmType = loadListType(schema, (XSListSimpleType) type, fieldName); 414 } else { 415 ecmType = loadSimpleType(schema, type, fieldName); 416 } 417 } else { 418 ecmType = loadComplexType(schema, name, type.asComplexType()); 419 } 420 if (ecmType != null) { 421 schema.registerType(ecmType); 422 } else { 423 log.warn("loadType for " + fieldName + " of " + type + " returns null"); 424 } 425 return ecmType; 426 } 427 428 /** 429 * @param name the type name (note, the type may have a null name if an anonymous type) 430 * @param type 431 * @return 432 */ 433 protected Type loadComplexType(Schema schema, String name, XSType type) throws TypeBindingException { 434 XSType baseType = type.getBaseType(); 435 ComplexType superType = null; 436 // the anyType is the basetype of itself 437 if (baseType.getBaseType() != baseType) { // have a base type 438 if (baseType.isComplexType()) { 439 superType = (ComplexType) loadType(schema, baseType, name); 440 } else { 441 log.warn("Complex type has a non complex type super type???"); 442 } 443 } 444 XSComplexType xsct = type.asComplexType(); 445 // try to get the delta content 446 XSContentType content = xsct.getExplicitContent(); 447 // if none get the entire content 448 if (content == null) { 449 content = xsct.getContentType(); 450 } 451 Type ret = createComplexType(schema, superType, name, content, xsct.isAbstract()); 452 if (ret != null && ret instanceof ComplexType) { 453 // load attributes if any 454 loadAttributes(schema, xsct, (ComplexType) ret); 455 } 456 457 return ret; 458 } 459 460 protected void loadAttributes(Schema schema, XSComplexType xsct, ComplexType ct) throws TypeBindingException { 461 Collection<? extends XSAttributeUse> attrs = xsct.getAttributeUses(); 462 for (XSAttributeUse attr : attrs) { 463 XSAttributeDecl at = attr.getDecl(); 464 Type fieldType = loadType(schema, at.getType(), at.getName()); 465 if (fieldType == null) { 466 throw new TypeBindingException("Cannot add type for '" + at.getName() + "'"); 467 } 468 createField(ct, at, fieldType, !attr.isRequired()); 469 } 470 } 471 472 protected SimpleType loadSimpleType(Schema schema, XSType type, String fieldName) throws TypeBindingException { 473 String name = type.getName(); 474 if (name == null) { 475 // probably a local type 476 name = fieldName + ANONYMOUS_TYPE_SUFFIX; 477 } 478 XSType baseType = type.getBaseType(); 479 SimpleType superType = null; 480 if (baseType != type) { 481 // have a base type 482 superType = (SimpleType) loadType(schema, baseType, fieldName); 483 } 484 SimpleTypeImpl simpleType = new SimpleTypeImpl(superType, schema.getName(), name); 485 486 // add constraints/restrictions to the simple type 487 if (type instanceof RestrictionSimpleTypeImpl) { 488 RestrictionSimpleTypeImpl restrictionType = (RestrictionSimpleTypeImpl) type; 489 490 List<Constraint> constraints = new ArrayList<Constraint>(); 491 492 // pattern 493 XSFacet patternFacet = restrictionType.getFacet(FACET_PATTERN); 494 if (patternFacet != null) { 495 if (simpleType.getPrimitiveType().support(PatternConstraint.class)) { 496 // String pattern 497 String pattern = patternFacet.getValue().toString(); 498 Constraint constraint = new PatternConstraint(pattern); 499 constraints.add(constraint); 500 } else { 501 logUnsupportedFacetRestriction(schema, fieldName, simpleType, FACET_PATTERN); 502 } 503 } 504 505 // length 506 XSFacet minLengthFacet = restrictionType.getFacet(FACET_MINLENGTH); 507 XSFacet maxLengthFacet = restrictionType.getFacet(FACET_MAXLENGTH); 508 XSFacet lengthFacet = restrictionType.getFacet(FACET_LENGTH); 509 if (maxLengthFacet != null || minLengthFacet != null || lengthFacet != null) { 510 if (simpleType.getPrimitiveType().support(LengthConstraint.class)) { 511 // String Length 512 Object min = null, max = null; 513 if (lengthFacet != null) { 514 min = lengthFacet.getValue().toString(); 515 max = min; 516 } else { 517 if (minLengthFacet != null) { 518 min = minLengthFacet.getValue(); 519 } 520 if (maxLengthFacet != null) { 521 max = maxLengthFacet.getValue(); 522 } 523 } 524 Constraint constraint = new LengthConstraint(min, max); 525 constraints.add(constraint); 526 } else { 527 logUnsupportedFacetRestriction(schema, fieldName, simpleType, FACET_MINLENGTH, FACET_MAXLENGTH, 528 FACET_LENGTH); 529 } 530 } 531 532 // Intervals 533 XSFacet minExclusiveFacet = restrictionType.getFacet(FACET_MINEXCLUSIVE); 534 XSFacet minInclusiveFacet = restrictionType.getFacet(FACET_MININCLUSIVE); 535 XSFacet maxExclusiveFacet = restrictionType.getFacet(FACET_MAXEXCLUSIVE); 536 XSFacet maxInclusiveFacet = restrictionType.getFacet(FACET_MAXINCLUSIVE); 537 if (minExclusiveFacet != null || minInclusiveFacet != null || maxExclusiveFacet != null 538 || maxInclusiveFacet != null) { 539 if (simpleType.getPrimitiveType().support(NumericIntervalConstraint.class)) { 540 // Numeric Interval 541 Object min = null, max = null; 542 boolean includingMin = true, includingMax = true; 543 if (minExclusiveFacet != null) { 544 min = minExclusiveFacet.getValue(); 545 includingMin = false; 546 } else if (minInclusiveFacet != null) { 547 min = minInclusiveFacet.getValue(); 548 includingMin = true; 549 } 550 if (maxExclusiveFacet != null) { 551 max = maxExclusiveFacet.getValue(); 552 includingMax = false; 553 } else if (maxInclusiveFacet != null) { 554 max = maxInclusiveFacet.getValue(); 555 includingMax = true; 556 } 557 Constraint constraint = new NumericIntervalConstraint(min, includingMin, max, includingMax); 558 constraints.add(constraint); 559 } else if (simpleType.getPrimitiveType().support(DateIntervalConstraint.class)) { 560 // Date Interval 561 Object min = null, max = null; 562 boolean includingMin = true, includingMax = true; 563 if (minExclusiveFacet != null) { 564 min = minExclusiveFacet.getValue(); 565 includingMin = false; 566 } 567 if (minInclusiveFacet != null) { 568 min = minInclusiveFacet.getValue(); 569 includingMin = true; 570 } 571 if (maxExclusiveFacet != null) { 572 max = maxExclusiveFacet.getValue(); 573 includingMax = false; 574 } 575 if (maxInclusiveFacet != null) { 576 max = maxInclusiveFacet.getValue(); 577 includingMax = true; 578 } 579 Constraint constraint = new DateIntervalConstraint(min, includingMin, max, includingMax); 580 constraints.add(constraint); 581 } else { 582 logUnsupportedFacetRestriction(schema, fieldName, simpleType, FACET_MINEXCLUSIVE, 583 FACET_MININCLUSIVE, FACET_MAXEXCLUSIVE, FACET_MAXINCLUSIVE); 584 } 585 } 586 587 // Enumeration 588 List<XSFacet> enumFacets = restrictionType.getFacets("enumeration"); 589 if (enumFacets != null && enumFacets.size() > 0) { 590 if (simpleType.getPrimitiveType().support(EnumConstraint.class)) { 591 // string enumeration 592 List<String> enumValues = new ArrayList<String>(); 593 for (XSFacet enumFacet : enumFacets) { 594 enumValues.add(enumFacet.getValue().toString()); 595 } 596 Constraint constraint = new EnumConstraint(enumValues); 597 constraints.add(constraint); 598 } else { 599 logUnsupportedFacetRestriction(schema, fieldName, simpleType, FACET_ENUMERATION); 600 } 601 } 602 603 String refName = restrictionType.getForeignAttribute(NAMESPACE_CORE_EXTERNAL_REFERENCES, 604 ATTR_CORE_EXTERNAL_REFERENCES); 605 Map<String, String> refParameters = new HashMap<String, String>(); 606 for (ForeignAttributes attr : restrictionType.getForeignAttributes()) { 607 for (int index = 0; index < attr.getLength(); index++) { 608 String attrNS = attr.getURI(index); 609 String attrName = attr.getLocalName(index); 610 String attrValue = attr.getValue(index); 611 if (NAMESPACE_CORE_EXTERNAL_REFERENCES.equals(attrNS)) { 612 if (!ATTR_CORE_EXTERNAL_REFERENCES.equals(attrName)) { 613 refParameters.put(attrName, attrValue); 614 } 615 } 616 } 617 } 618 if (refName != null) { 619 ObjectResolver resolver = getObjectResolverService().getResolver(refName, refParameters); 620 if (resolver != null) { 621 simpleType.setResolver(resolver); 622 constraints.add(new ObjectResolverConstraint(resolver)); 623 } else { 624 log.info("type of " + fieldName + "|" + type.getName() 625 + " targets ObjectResolver namespace but has no matching resolver registered " 626 + "(please contribute to component : org.nuxeo.ecm.core.schema.ObjectResolverService)"); 627 } 628 } 629 630 simpleType.addConstraints(constraints); 631 } 632 633 return simpleType; 634 } 635 636 private void logUnsupportedFacetRestriction(Schema schema, String fieldName, SimpleTypeImpl simpleType, 637 String... facetNames) { 638 StringBuilder msg = new StringBuilder(); 639 msg.append("schema|field|type : ").append(schema.getName()); 640 msg.append("|").append(fieldName); 641 msg.append("|").append(simpleType.getPrimitiveType()); 642 msg.append(" following restriction facet are not handled by constraints API for this type :"); 643 for (String facetName : facetNames) { 644 msg.append(facetName).append(" "); 645 } 646 log.warn(msg.toString()); 647 } 648 649 protected ListType loadListType(Schema schema, XSListSimpleType type, String fieldName) 650 throws TypeBindingException { 651 String name = type.getName(); 652 if (name == null) { 653 // probably a local type 654 name = fieldName + ANONYMOUS_TYPE_SUFFIX; 655 } 656 XSType xsItemType = type.getItemType(); 657 Type itemType; 658 if (xsItemType.getTargetNamespace().equals(NS_XSD)) { 659 itemType = XSDTypes.getType(xsItemType.getName()); 660 } else { 661 itemType = loadSimpleType(schema, xsItemType != null ? xsItemType : type.getSimpleBaseType(), null); 662 } 663 if (itemType == null) { 664 log.error("list item type was not defined -> you should define first the item type"); 665 return null; 666 } 667 return new ListTypeImpl(schema.getName(), name, itemType); 668 } 669 670 protected Type createComplexType(Schema schema, ComplexType superType, String name, XSContentType content, 671 boolean abstractType) throws TypeBindingException { 672 673 ComplexType ct = new ComplexTypeImpl(superType, schema.getName(), name); 674 675 // -------- Workaround - we register now the complex type - to fix 676 // recursive references to the same type 677 schema.registerType(ct); 678 679 // ------------------------------------------ 680 XSParticle particle = content.asParticle(); 681 if (particle == null) { 682 // complex type without particle -> may be it contains only 683 // attributes -> return it as is 684 return ct; 685 } 686 XSTerm term = particle.getTerm(); 687 XSModelGroup mg = term.asModelGroup(); 688 689 return processModelGroup(schema, superType, name, ct, mg, abstractType); 690 } 691 692 protected Type createFakeComplexType(Schema schema, ComplexType superType, String name, XSModelGroup mg) 693 throws TypeBindingException { 694 695 ComplexType ct = new ComplexTypeImpl(superType, schema.getName(), name); 696 // -------- Workaround - we register now the complex type - to fix 697 // recursive references to the same type 698 schema.registerType(ct); 699 700 return processModelGroup(schema, superType, name, ct, mg, false); 701 } 702 703 protected Type processModelGroup(Schema schema, ComplexType superType, String name, ComplexType ct, XSModelGroup mg, 704 boolean abstractType) throws TypeBindingException { 705 if (mg == null) { 706 // TODO don't know how to handle this for now 707 throw new TypeBindingException("unsupported complex type"); 708 } 709 XSParticle[] group = mg.getChildren(); 710 if (group.length == 0) { 711 return null; 712 } 713 if (group.length == 1 && superType == null && group[0].isRepeated()) { 714 // a list ? 715 // only convert to list of type is not abstract 716 if (!abstractType) { 717 return createListType(schema, name, group[0]); 718 } 719 } 720 for (XSParticle child : group) { 721 XSTerm term = child.getTerm(); 722 XSElementDecl element = term.asElementDecl(); 723 int maxOccur = child.getMaxOccurs().intValue(); 724 725 if (element == null) { 726 // assume this is a xs:choice group 727 // (did not find any other way to detect ! 728 // 729 // => make an aggregation of xs:choice subfields 730 if (maxOccur < 0 || maxOccur > 1) { 731 // means this is a list 732 // 733 // first create a fake complex type 734 Type fakeType = createFakeComplexType(schema, superType, name + "#anonymousListItem", 735 term.asModelGroup()); 736 // wrap it as a list 737 ListType listType = createListType(schema, name + "#anonymousListType", fakeType, 0, maxOccur); 738 // add the listfield to the current CT 739 String fieldName = ct.getName() + "#anonymousList"; 740 ct.addField(fieldName, listType, null, 0, null); 741 } else { 742 processModelGroup(schema, superType, name, ct, term.asModelGroup(), abstractType); 743 } 744 } else { 745 if (maxOccur < 0 || maxOccur > 1) { 746 Type fieldType = loadType(schema, element.getType(), element.getName()); 747 if (fieldType != null) { 748 ListType listType = createListType(schema, element.getName() + "#anonymousListType", fieldType, 749 0, maxOccur); 750 // add the listfield to the current CT 751 String fieldName = element.getName(); 752 ct.addField(fieldName, listType, null, 0, null); 753 } 754 } else { 755 loadComplexTypeElement(schema, ct, element); 756 } 757 } 758 } 759 760 // add fields from Parent 761 if (superType != null && superType.isComplexType()) { 762 for (Field parentField : superType.getFields()) { 763 ct.addField(parentField.getName().getLocalName(), parentField.getType(), 764 (String) parentField.getDefaultValue(), 0, null); 765 } 766 } 767 return ct; 768 } 769 770 protected ListType createListType(Schema schema, String name, XSParticle particle) throws TypeBindingException { 771 XSElementDecl element = particle.getTerm().asElementDecl(); 772 if (element == null) { 773 log.warn("Ignoring " + name + " unsupported list type"); 774 return null; 775 } 776 Type type = loadType(schema, element.getType(), element.getName()); 777 if (type == null) { 778 log.warn("Unable to find type for " + element.getName()); 779 return null; 780 } 781 782 XmlString dv = element.getDefaultValue(); 783 String defValue = null; 784 if (dv != null) { 785 defValue = dv.value; 786 } 787 int flags = 0; 788 if (defValue == null) { 789 dv = element.getFixedValue(); 790 if (dv != null) { 791 defValue = dv.value; 792 flags |= Field.CONSTANT; 793 } 794 } 795 boolean computedNillable = isNillable(element); 796 if (computedNillable) { 797 flags |= Field.NILLABLE; 798 } 799 800 Set<Constraint> constraints = new HashSet<Constraint>(); 801 if (!computedNillable) { 802 constraints.add(NotNullConstraint.get()); 803 } 804 if (type instanceof SimpleType) { 805 SimpleType st = (SimpleType) type; 806 constraints.addAll(st.getConstraints()); 807 } 808 809 return new ListTypeImpl(schema.getName(), name, type, element.getName(), defValue, flags, constraints, 810 particle.getMinOccurs().intValue(), particle.getMaxOccurs().intValue()); 811 } 812 813 protected static ListType createListType(Schema schema, String name, Type itemType, int min, int max) 814 throws TypeBindingException { 815 String elementName = name + "#item"; 816 return new ListTypeImpl(schema.getName(), name, itemType, elementName, null, min, max); 817 } 818 819 protected void loadComplexTypeElement(Schema schema, ComplexType type, XSElementDecl element) 820 throws TypeBindingException { 821 XSType elementType = element.getType(); 822 823 Type fieldType = loadType(schema, elementType, element.getName()); 824 if (fieldType != null) { 825 createField(type, element, fieldType); 826 } 827 } 828 829 protected static Field createField(ComplexType type, XSElementDecl element, Type fieldType) { 830 String elementName = element.getName(); 831 XmlString dv = element.getDefaultValue(); 832 String defValue = null; 833 if (dv != null) { 834 defValue = dv.value; 835 } 836 int flags = 0; 837 if (defValue == null) { 838 dv = element.getFixedValue(); 839 if (dv != null) { 840 defValue = dv.value; 841 flags |= Field.CONSTANT; 842 } 843 } 844 845 boolean computedNillable = isNillable(element); 846 847 if (computedNillable) { 848 flags |= Field.NILLABLE; 849 } 850 851 Set<Constraint> constraints = new HashSet<Constraint>(); 852 if (!computedNillable) { 853 constraints.add(NotNullConstraint.get()); 854 } 855 if (fieldType instanceof SimpleType) { 856 SimpleType st = (SimpleType) fieldType; 857 constraints.addAll(st.getConstraints()); 858 } 859 Field field = type.addField(elementName, fieldType, defValue, flags, constraints); 860 861 // set the max field length from the constraints 862 if (fieldType instanceof SimpleTypeImpl) { 863 LengthConstraint lc = ConstraintUtils.getConstraint(field.getConstraints(), LengthConstraint.class); 864 if (lc != null && lc.getMax() != null) { 865 field.setMaxLength(lc.getMax().intValue()); 866 } 867 } 868 869 return field; 870 } 871 872 protected static Field createField(ComplexType type, XSAttributeDecl element, Type fieldType, boolean isNillable) { 873 String elementName = element.getName(); 874 XmlString dv = element.getDefaultValue(); 875 String defValue = null; 876 if (dv != null) { 877 defValue = dv.value; 878 } 879 int flags = 0; 880 if (defValue == null) { 881 dv = element.getFixedValue(); 882 if (dv != null) { 883 defValue = dv.value; 884 flags |= Field.CONSTANT; 885 } 886 } 887 Set<Constraint> constraints = new HashSet<Constraint>(); 888 if (!isNillable) { 889 constraints.add(NotNullConstraint.get()); 890 } 891 if (fieldType.isSimpleType()) { 892 constraints.addAll(((SimpleType) fieldType).getConstraints()); 893 } 894 return type.addField(elementName, fieldType, defValue, flags, constraints); 895 } 896 897 protected static String getAnonymousTypeName(XSType type, String fieldName) { 898 if (type.isComplexType()) { 899 XSElementDecl container = type.asComplexType().getScope(); 900 String elName = container.getName(); 901 return elName + ANONYMOUS_TYPE_SUFFIX; 902 } else { 903 return fieldName + ANONYMOUS_TYPE_SUFFIX; 904 } 905 } 906 907 public List<String> getReferencedXSD() { 908 return referencedXSD; 909 } 910 911 /** 912 * ignore case where xsd:nillable is recognized as false by xsom (we don't know if it's not specified and we want to 913 * preserve a default value to true. Therefore, we provide a custom attribute nxs:nillable to force nillable as 914 * false) NB: if xsd:nillable is present and sets to true, deducted value will be true even if nxs:nillable is false 915 * 916 * @since 7.1 917 */ 918 protected static boolean isNillable(XSElementDecl element) { 919 boolean computedNillable; 920 String value = element.getForeignAttribute(NAMESPACE_CORE_VALIDATION, "nillable"); 921 if (!element.isNillable() && value != null && !Boolean.valueOf(value)) { 922 computedNillable = false; 923 } else { 924 computedNillable = true; 925 } 926 return computedNillable; 927 } 928 929}