View Javadoc
1   package org.codehaus.modello.plugin.xsd;
2   
3   /*
4    * Copyright (c) 2005, Codehaus.org
5    *
6    * Permission is hereby granted, free of charge, to any person obtaining a copy of
7    * this software and associated documentation files (the "Software"), to deal in
8    * the Software without restriction, including without limitation the rights to
9    * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10   * of the Software, and to permit persons to whom the Software is furnished to do
11   * so, subject to the following conditions:
12   *
13   * The above copyright notice and this permission notice shall be included in all
14   * copies or substantial portions of the Software.
15   *
16   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22   * SOFTWARE.
23   */
24  
25  import javax.inject.Named;
26  
27  import java.io.File;
28  import java.io.IOException;
29  import java.io.Writer;
30  import java.nio.charset.StandardCharsets;
31  import java.util.HashSet;
32  import java.util.List;
33  import java.util.Map;
34  import java.util.Properties;
35  import java.util.Set;
36  
37  import org.codehaus.modello.ModelloException;
38  import org.codehaus.modello.ModelloParameterConstants;
39  import org.codehaus.modello.model.Model;
40  import org.codehaus.modello.model.ModelAssociation;
41  import org.codehaus.modello.model.ModelClass;
42  import org.codehaus.modello.model.ModelField;
43  import org.codehaus.modello.plugin.xsd.metadata.XsdClassMetadata;
44  import org.codehaus.modello.plugin.xsd.metadata.XsdFieldMetadata;
45  import org.codehaus.modello.plugins.xml.AbstractXmlGenerator;
46  import org.codehaus.modello.plugins.xml.metadata.XmlAssociationMetadata;
47  import org.codehaus.modello.plugins.xml.metadata.XmlFieldMetadata;
48  import org.codehaus.plexus.util.StringUtils;
49  import org.codehaus.plexus.util.io.CachingWriter;
50  import org.codehaus.plexus.util.xml.PrettyPrintXMLWriter;
51  import org.codehaus.plexus.util.xml.XMLWriter;
52  
53  /**
54   * @author <a href="mailto:brett@codehaus.org">Brett Porter</a>
55   */
56  @Named("xsd")
57  public class XsdGenerator extends AbstractXmlGenerator {
58      /**
59       * Value standing for any element name (used on xml.tagName)
60       */
61      private static final String ANY_NAME = "*";
62  
63      protected static final String LS = System.lineSeparator();
64  
65      @Override
66      public void generate(Model model, Map<String, Object> parameters) throws ModelloException {
67          initialize(model, parameters);
68  
69          try {
70              generateXsd(parameters);
71          } catch (IOException ex) {
72              throw new ModelloException("Exception while generating xsd.", ex);
73          }
74      }
75  
76      private void generateXsd(Map<String, Object> parameters) throws IOException, ModelloException {
77          Model objectModel = getModel();
78  
79          File directory = getOutputDirectory();
80  
81          if (isPackageWithVersion()) {
82              directory = new File(directory, getGeneratedVersion().toString());
83          }
84  
85          if (!directory.exists()) {
86              directory.mkdirs();
87          }
88  
89          // we assume parameters not null
90          String xsdFileName = (String) parameters.get(ModelloParameterConstants.OUTPUT_XSD_FILE_NAME);
91          // enforceMandatoryElements parameter is kept for backward compatibility but is no longer used.
92          // Required fields are now always enforced based on field.isRequired() value.
93          boolean enforceMandatoryElements =
94                  Boolean.parseBoolean((String) parameters.get(ModelloParameterConstants.XSD_ENFORCE_MANDATORY_ELEMENTS));
95  
96          File f = new File(directory, objectModel.getId() + "-" + getGeneratedVersion() + ".xsd");
97  
98          if (xsdFileName != null) {
99              f = new File(directory, xsdFileName);
100         }
101 
102         try (Writer writer = new CachingWriter(f, StandardCharsets.UTF_8)) {
103             XMLWriter w = new PrettyPrintXMLWriter(writer);
104 
105             writer.append("<?xml version=\"1.0\"?>").write(LS);
106 
107             initHeader(w);
108 
109             // TODO: the writer should be knowledgeable of namespaces, but this works
110             w.startElement("xs:schema");
111             w.addAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
112             w.addAttribute("elementFormDefault", "qualified");
113 
114             ModelClass root = objectModel.getClass(objectModel.getRoot(getGeneratedVersion()), getGeneratedVersion());
115 
116             String namespace = XsdModelHelper.getNamespace(root.getModel(), getGeneratedVersion());
117 
118             w.addAttribute("xmlns", namespace);
119 
120             String targetNamespace =
121                     XsdModelHelper.getTargetNamespace(root.getModel(), getGeneratedVersion(), namespace);
122 
123             // add targetNamespace if attribute is not blank (specifically set to avoid a target namespace)
124             if (StringUtils.isNotBlank(targetNamespace)) {
125                 w.addAttribute("targetNamespace", targetNamespace);
126             }
127 
128             w.startElement("xs:element");
129             String tagName = resolveTagName(root);
130             w.addAttribute("name", tagName);
131             w.addAttribute("type", root.getName());
132 
133             writeClassDocumentation(w, root);
134 
135             w.endElement();
136 
137             // Element descriptors
138             // Traverse from root so "abstract" models aren't included
139             int initialCapacity = objectModel.getClasses(getGeneratedVersion()).size();
140             writeComplexTypeDescriptor(w, objectModel, root, new HashSet<>(initialCapacity), enforceMandatoryElements);
141 
142             w.endElement();
143         }
144     }
145 
146     private static void writeClassDocumentation(XMLWriter w, ModelClass modelClass) {
147         writeDocumentation(w, modelClass.getVersionRange().toString(), modelClass.getDescription());
148     }
149 
150     private static void writeFieldDocumentation(XMLWriter w, ModelField field) {
151         writeDocumentation(w, field.getVersionRange().toString(), field.getDescription());
152     }
153 
154     private static void writeDocumentation(XMLWriter w, String version, String description) {
155         if (version != null || description != null) {
156             w.startElement("xs:annotation");
157 
158             if (version != null) {
159                 w.startElement("xs:documentation");
160                 w.addAttribute("source", "version");
161                 w.writeText(version);
162                 w.endElement();
163             }
164 
165             if (description != null) {
166                 w.startElement("xs:documentation");
167                 w.addAttribute("source", "description");
168                 w.writeText(description);
169                 w.endElement();
170             }
171 
172             w.endElement();
173         }
174     }
175 
176     private void writeComplexTypeDescriptor(
177             XMLWriter w,
178             Model objectModel,
179             ModelClass modelClass,
180             Set<ModelClass> written,
181             boolean enforceMandatoryElements) {
182         written.add(modelClass);
183 
184         w.startElement("xs:complexType");
185         w.addAttribute("name", modelClass.getName());
186 
187         List<ModelField> fields = getFieldsForXml(modelClass, getGeneratedVersion());
188 
189         ModelField contentField = getContentField(fields);
190 
191         boolean hasContentField = contentField != null;
192 
193         List<ModelField> attributeFields = getXmlAttributeFields(fields);
194 
195         fields.removeAll(attributeFields);
196 
197         // If any element field carries xml.format="mixed" without an xml.tagName override,
198         // the class body itself accepts both text and child elements (mixed content).
199         // Fields with xml.tagName produce a *wrapper* child element; mixed content lives
200         // inside that wrapper and is handled by writeListElement, not here.
201         if (!hasContentField
202                 && fields.stream()
203                         .map(f -> (XmlFieldMetadata) f.getMetadata(XmlFieldMetadata.ID))
204                         .anyMatch(m -> "mixed".equals(m.getFormat()) && m.getTagName() == null)) {
205             w.addAttribute("mixed", "true");
206         }
207 
208         if (hasContentField) {
209             // yes it's only an extension of xs:string
210             w.startElement("xs:simpleContent");
211 
212             w.startElement("xs:extension");
213 
214             w.addAttribute("base", getXsdType(contentField.getType()));
215         }
216 
217         writeClassDocumentation(w, modelClass);
218 
219         Set<ModelClass> toWrite = new HashSet<>();
220 
221         if (!fields.isEmpty()) {
222             XsdClassMetadata xsdClassMetadata = (XsdClassMetadata) modelClass.getMetadata(XsdClassMetadata.ID);
223             boolean compositorAll = XsdClassMetadata.COMPOSITOR_ALL.equals(xsdClassMetadata.getCompositor());
224 
225             if (!hasContentField) {
226                 if (compositorAll) {
227                     w.startElement("xs:all");
228                 } else {
229                     w.startElement("xs:sequence");
230                 }
231             }
232 
233             for (ModelField field : fields) {
234                 XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID);
235 
236                 String fieldTagName = resolveTagName(field, xmlFieldMetadata);
237 
238                 if (!hasContentField) {
239                     if (fieldTagName.equals(ANY_NAME)) {
240                         w.startElement("xs:any");
241                         w.addAttribute("minOccurs", "0");
242                         w.addAttribute("maxOccurs", "unbounded");
243                         w.addAttribute("processContents", "skip");
244                         w.endElement();
245                         continue;
246                     }
247                     w.startElement("xs:element");
248 
249                     if (!field.isRequired()) {
250                         w.addAttribute("minOccurs", "0");
251                     }
252                 }
253 
254                 String xsdType = getXsdType(field.getType());
255 
256                 if ("Date".equals(field.getType()) && "long".equals(xmlFieldMetadata.getFormat())) {
257                     xsdType = getXsdType("long");
258                 }
259 
260                 if (xmlFieldMetadata.isContent()) {
261                     // nothing to add
262                 } else if ((xsdType != null) || "char".equals(field.getType()) || "Character".equals(field.getType())) {
263                     w.addAttribute("name", fieldTagName);
264 
265                     XsdFieldMetadata xsdFieldMetadata = (XsdFieldMetadata) field.getMetadata(XsdFieldMetadata.ID);
266                     boolean hasConstraint = hasXsdConstraint(xsdFieldMetadata);
267 
268                     if (xsdType != null && !hasConstraint) {
269                         // schema built-in datatype
270                         w.addAttribute("type", xsdType);
271                     }
272 
273                     if (field.getDefaultValue() != null) {
274                         // \0 is the implicit default value for char/Character but \0 isn't a valid XML char
275                         if (field.getDefaultValue() != "\0") {
276                             w.addAttribute("default", field.getDefaultValue());
277                         }
278                     }
279 
280                     writeFieldDocumentation(w, field);
281 
282                     if (xsdType == null) {
283                         writeCharElement(w);
284                     } else if (hasConstraint) {
285                         writeConstrainedStringElement(w, xsdFieldMetadata);
286                     }
287                 } else {
288                     // TODO cleanup/split this part it's no really human readable :-)
289                     if (isInnerAssociation(field)) {
290                         ModelAssociation association = (ModelAssociation) field;
291                         ModelClass fieldModelClass = objectModel.getClass(association.getTo(), getGeneratedVersion());
292 
293                         toWrite.add(fieldModelClass);
294 
295                         if (association.isManyMultiplicity()) {
296                             XmlAssociationMetadata xmlAssociationMetadata = (XmlAssociationMetadata)
297                                     association.getAssociationMetadata(XmlAssociationMetadata.ID);
298 
299                             if (xmlAssociationMetadata.isWrappedItems()) {
300                                 w.addAttribute("name", fieldTagName);
301                                 writeFieldDocumentation(w, field);
302 
303                                 writeListElement(
304                                         w, xmlFieldMetadata, xmlAssociationMetadata, field, fieldModelClass.getName());
305                             } else {
306                                 if (compositorAll) {
307                                     // xs:all does not accept maxOccurs="unbounded", xs:sequence MUST be used
308                                     // to be able to represent this constraint
309                                     throw new IllegalStateException(
310                                             field.getName() + " field is declared as xml.listStyle=\"flat\" "
311                                                     + "then class " + modelClass.getName()
312                                                     + " MUST be declared as xsd.compositor=\"sequence\"");
313                                 }
314 
315                                 w.addAttribute("name", resolveTagName(fieldTagName, xmlAssociationMetadata));
316 
317                                 w.addAttribute("type", fieldModelClass.getName());
318                                 w.addAttribute("maxOccurs", "unbounded");
319 
320                                 writeFieldDocumentation(w, field);
321                             }
322                         } else {
323                             // not many multiplicity
324                             w.addAttribute("name", fieldTagName);
325                             w.addAttribute("type", fieldModelClass.getName());
326                             writeFieldDocumentation(w, field);
327                         }
328                     } else // not inner association
329                     {
330                         w.addAttribute("name", fieldTagName);
331 
332                         writeFieldDocumentation(w, field);
333 
334                         if (List.class.getName().equals(field.getType())
335                                 || Set.class.getName().equals(field.getType())) {
336                             ModelAssociation association = (ModelAssociation) field;
337 
338                             XmlAssociationMetadata xmlAssociationMetadata = (XmlAssociationMetadata)
339                                     association.getAssociationMetadata(XmlAssociationMetadata.ID);
340 
341                             writeListElement(w, xmlFieldMetadata, xmlAssociationMetadata, field, getXsdType("String"));
342                         } else if (Properties.class.getName().equals(field.getType())
343                                 || "DOM".equals(field.getType())) {
344                             writePropertiesElement(w, "DOM".equals(field.getType()));
345                         } else {
346                             throw new IllegalStateException("Non-association field of a non-primitive type '"
347                                     + field.getType() + "' for '" + field.getName() + "' in '"
348                                     + modelClass.getName() + "' model class");
349                         }
350                     }
351                 }
352                 if (!hasContentField) {
353                     w.endElement();
354                 }
355             } // end fields iterator
356 
357             if (!hasContentField) {
358                 w.endElement(); // xs:all or xs:sequence
359             }
360         }
361 
362         for (ModelField field : attributeFields) {
363             XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID);
364 
365             w.startElement("xs:attribute");
366 
367             String xsdType = getXsdType(field.getType());
368 
369             String tagName = resolveTagName(field, xmlFieldMetadata);
370 
371             w.addAttribute("name", tagName);
372 
373             XsdFieldMetadata xsdFieldMetadata = (XsdFieldMetadata) field.getMetadata(XsdFieldMetadata.ID);
374             boolean hasConstraint = hasXsdConstraint(xsdFieldMetadata);
375 
376             if (xsdType != null && !hasConstraint) {
377                 w.addAttribute("type", xsdType);
378             }
379 
380             if (field.getDefaultValue() != null) {
381                 w.addAttribute("default", field.getDefaultValue());
382             }
383 
384             w.addAttribute("use", field.isRequired() ? "required" : "optional");
385 
386             writeFieldDocumentation(w, field);
387 
388             if ("char".equals(field.getType()) || "Character".equals(field.getType())) {
389                 writeCharElement(w);
390             } else if (hasConstraint) {
391                 writeConstrainedStringElement(w, xsdFieldMetadata);
392             } else if (xsdType == null) {
393                 throw new IllegalStateException("Attribute field of a non-primitive type '" + field.getType()
394                         + "' for '" + field.getName() + "' in '" + modelClass.getName() + "' model class");
395             }
396 
397             w.endElement();
398         }
399 
400         if (hasContentField) {
401             w.endElement(); // xs:extension
402 
403             w.endElement(); // xs:simpleContent
404         }
405 
406         w.endElement(); // xs:complexType
407 
408         for (ModelClass fieldModelClass : toWrite) {
409             if (!written.contains(fieldModelClass)) {
410                 writeComplexTypeDescriptor(w, objectModel, fieldModelClass, written, enforceMandatoryElements);
411             }
412         }
413     }
414 
415     private static void writeCharElement(XMLWriter w) {
416         // a char, described as a simpleType base on string with a length restriction to 1
417         w.startElement("xs:simpleType");
418 
419         w.startElement("xs:restriction");
420         w.addAttribute("base", "xs:string");
421 
422         w.startElement("xs:length");
423         w.addAttribute("value", "1");
424         w.addAttribute("fixed", "true");
425 
426         w.endElement();
427 
428         w.endElement();
429 
430         w.endElement();
431     }
432 
433     /**
434      * Writes the complexType of a field holding free-form XML content: either a {@code java.util.Properties} or
435      * a {@code DOM} field.
436      *
437      * @param w the writer
438      * @param dom whether the field is a {@code DOM} field, in which case arbitrary attributes are allowed on the
439      *            element itself, so that DOM merge hints such as {@code combine.self} or {@code combine.children}
440      *            validate. A {@code Properties} element carries no attributes, so none are allowed there.
441      */
442     private static void writePropertiesElement(XMLWriter w, boolean dom) {
443         w.startElement("xs:complexType");
444 
445         w.startElement("xs:sequence");
446 
447         w.startElement("xs:any");
448         w.addAttribute("minOccurs", "0");
449         w.addAttribute("maxOccurs", "unbounded");
450         w.addAttribute("processContents", "skip");
451 
452         w.endElement();
453 
454         w.endElement();
455 
456         if (dom) {
457             w.startElement("xs:anyAttribute");
458             w.addAttribute("processContents", "skip");
459 
460             w.endElement();
461         }
462 
463         w.endElement();
464     }
465 
466     private void writeListElement(
467             XMLWriter w,
468             XmlFieldMetadata xmlFieldMetadata,
469             XmlAssociationMetadata xmlAssociationMetadata,
470             ModelField field,
471             String type) {
472         String fieldTagName = resolveTagName(field, xmlFieldMetadata);
473 
474         String valuesTagName = resolveTagName(fieldTagName, xmlAssociationMetadata);
475 
476         w.startElement("xs:complexType");
477 
478         if ("mixed".equals(xmlFieldMetadata.getFormat())) {
479             w.addAttribute("mixed", "true");
480         }
481 
482         w.startElement("xs:sequence");
483 
484         if (valuesTagName.equals(ANY_NAME)) {
485             w.startElement("xs:any");
486             w.addAttribute("processContents", "skip");
487         } else {
488             w.startElement("xs:element");
489             w.addAttribute("type", type);
490             w.addAttribute("name", valuesTagName);
491         }
492         w.addAttribute("minOccurs", "0");
493         w.addAttribute("maxOccurs", "unbounded");
494 
495         w.endElement();
496 
497         w.endElement();
498 
499         w.endElement();
500     }
501 
502     private static boolean hasXsdConstraint(XsdFieldMetadata xsdFieldMetadata) {
503         return !xsdFieldMetadata.getEnumerations().isEmpty()
504                 || !xsdFieldMetadata.getSuggestions().isEmpty()
505                 || (xsdFieldMetadata.getPattern() != null
506                         && !xsdFieldMetadata.getPattern().isEmpty());
507     }
508 
509     /**
510      * Writes an inline {@code xs:simpleType} for a constrained String field.
511      * <ul>
512      *   <li>If {@link XsdFieldMetadata#getEnumerations()} is non-empty, generates a strict
513      *       {@code xs:restriction} with one {@code xs:enumeration} per value.</li>
514      *   <li>If {@link XsdFieldMetadata#getSuggestions()} is non-empty, generates an
515      *       {@code xs:union} of a fixed enumeration and plain {@code xs:string}, giving
516      *       IDE autocompletion without schema-level rejection of unknown values.</li>
517      *   <li>If {@link XsdFieldMetadata#getPattern()} is set, generates a
518      *       {@code xs:restriction base="xs:string"} with an {@code xs:pattern} facet.</li>
519      * </ul>
520      */
521     private static void writeConstrainedStringElement(XMLWriter w, XsdFieldMetadata xsdFieldMetadata) {
522         if (!xsdFieldMetadata.getEnumerations().isEmpty()) {
523             // Strict enumeration: only the listed values are schema-valid.
524             w.startElement("xs:simpleType");
525             w.startElement("xs:restriction");
526             w.addAttribute("base", "xs:string");
527             for (String value : xsdFieldMetadata.getEnumerations()) {
528                 w.startElement("xs:enumeration");
529                 w.addAttribute("value", value);
530                 w.endElement();
531             }
532             w.endElement(); // xs:restriction
533             w.endElement(); // xs:simpleType
534         } else if (!xsdFieldMetadata.getSuggestions().isEmpty()) {
535             // Non-strict union: IDE offers completion while still accepting any custom value.
536             w.startElement("xs:simpleType");
537             w.startElement("xs:union");
538             // memberTypes must reference named types — use an anonymous inner simpleType instead
539             w.startElement("xs:simpleType");
540             w.startElement("xs:restriction");
541             w.addAttribute("base", "xs:string");
542             for (String value : xsdFieldMetadata.getSuggestions()) {
543                 w.startElement("xs:enumeration");
544                 w.addAttribute("value", value);
545                 w.endElement();
546             }
547             w.endElement(); // xs:restriction
548             w.endElement(); // xs:simpleType (enumeration member)
549             w.startElement("xs:simpleType");
550             w.startElement("xs:restriction");
551             w.addAttribute("base", "xs:string");
552             w.endElement(); // xs:restriction
553             w.endElement(); // xs:simpleType (xs:string member)
554             w.endElement(); // xs:union
555             w.endElement(); // xs:simpleType
556         } else if (xsdFieldMetadata.getPattern() != null
557                 && !xsdFieldMetadata.getPattern().isEmpty()) {
558             // Pattern restriction.
559             w.startElement("xs:simpleType");
560             w.startElement("xs:restriction");
561             w.addAttribute("base", "xs:string");
562             w.startElement("xs:pattern");
563             w.addAttribute("value", xsdFieldMetadata.getPattern());
564             w.endElement(); // xs:pattern
565             w.endElement(); // xs:restriction
566             w.endElement(); // xs:simpleType
567         }
568     }
569 
570     private static String getXsdType(String type) {
571         if ("String".equals(type)) {
572             return "xs:string";
573         } else if ("boolean".equals(type) || "Boolean".equals(type)) {
574             return "xs:boolean";
575         } else if ("byte".equals(type) || "Byte".equals(type)) {
576             return "xs:byte";
577         } else if ("short".equals(type) || "Short".equals(type)) {
578             return "xs:short";
579         } else if ("int".equals(type) || "Integer".equals(type)) {
580             return "xs:int";
581         } else if ("long".equals(type) || "Long".equals(type)) {
582             return "xs:long";
583         } else if ("float".equals(type) || "Float".equals(type)) {
584             return "xs:float";
585         } else if ("double".equals(type) || "Double".equals(type)) {
586             return "xs:double";
587         } else if ("Date".equals(type)) {
588             return "xs:dateTime";
589         } else {
590             return null;
591         }
592     }
593 }