1   /*
2    * SPDX-FileCopyrightText: none
3    * SPDX-License-Identifier: CC0-1.0
4    */
5   
6   package dev.metaschema.schemagen.xml.impl;
7   
8   import org.codehaus.stax2.XMLStreamWriter2;
9   
10  import java.io.IOException;
11  import java.util.List;
12  import java.util.Map;
13  import java.util.concurrent.ConcurrentHashMap;
14  import java.util.concurrent.atomic.AtomicInteger;
15  
16  import javax.xml.namespace.QName;
17  import javax.xml.stream.XMLStreamException;
18  
19  import dev.metaschema.core.configuration.IConfiguration;
20  import dev.metaschema.core.datatype.IDataTypeAdapter;
21  import dev.metaschema.core.model.IAssemblyDefinition;
22  import dev.metaschema.core.model.IDefinition;
23  import dev.metaschema.core.model.IFieldDefinition;
24  import dev.metaschema.core.model.IFlagDefinition;
25  import dev.metaschema.core.model.IModelElement;
26  import dev.metaschema.core.model.IModule;
27  import dev.metaschema.core.model.IValuedDefinition;
28  import dev.metaschema.core.model.constraint.IAllowedValue;
29  import dev.metaschema.core.util.AutoCloser;
30  import dev.metaschema.core.util.ObjectUtils;
31  import dev.metaschema.schemagen.AbstractGenerationState;
32  import dev.metaschema.schemagen.SchemaGenerationException;
33  import dev.metaschema.schemagen.SchemaGenerationFeature;
34  import dev.metaschema.schemagen.xml.impl.schematype.IXmlComplexType;
35  import dev.metaschema.schemagen.xml.impl.schematype.IXmlSimpleType;
36  import dev.metaschema.schemagen.xml.impl.schematype.IXmlType;
37  import dev.metaschema.schemagen.xml.impl.schematype.XmlComplexTypeAssemblyDefinition;
38  import dev.metaschema.schemagen.xml.impl.schematype.XmlComplexTypeFieldDefinition;
39  import dev.metaschema.schemagen.xml.impl.schematype.XmlSimpleTypeDataTypeReference;
40  import dev.metaschema.schemagen.xml.impl.schematype.XmlSimpleTypeDataTypeRestriction;
41  import dev.metaschema.schemagen.xml.impl.schematype.XmlSimpleTypeUnion;
42  import edu.umd.cs.findbugs.annotations.NonNull;
43  import edu.umd.cs.findbugs.annotations.Nullable;
44  
45  /**
46   * Manages state and provides utility methods during XML Schema generation.
47   * <p>
48   * This class tracks types, namespaces, and provides methods for writing XML
49   * Schema elements during the schema generation process.
50   */
51  public class XmlGenerationState
52      extends AbstractGenerationState<AutoCloser<XMLStreamWriter2, SchemaGenerationException>, XmlDatatypeManager>
53      implements IXmlGenerationState {
54    @NonNull
55    private final String defaultNS;
56    @NonNull
57    private final Map<String, String> namespaceToPrefixMap = new ConcurrentHashMap<>();
58    @NonNull
59    private final Map<IDataTypeAdapter<?>, IXmlSimpleType> dataTypeToSimpleTypeMap = new ConcurrentHashMap<>();
60    @NonNull
61    private final Map<IValuedDefinition, IXmlSimpleType> definitionToSimpleTypeMap = new ConcurrentHashMap<>();
62    @NonNull
63    private final Map<IDefinition, IXmlType> definitionToTypeMap = new ConcurrentHashMap<>();
64  
65    private final AtomicInteger prefixNum = new AtomicInteger(); // 0
66  
67    /**
68     * Constructs a new XML generation state for the given module.
69     *
70     * @param module
71     *          the Metaschema module being generated
72     * @param writer
73     *          the auto-closing XML stream writer wrapper
74     * @param configuration
75     *          the schema generation configuration options
76     */
77    public XmlGenerationState(
78        @NonNull IModule module,
79        @NonNull AutoCloser<XMLStreamWriter2, SchemaGenerationException> writer,
80        @NonNull IConfiguration<SchemaGenerationFeature<?>> configuration) {
81      super(module, writer, configuration, new XmlDatatypeManager());
82      this.defaultNS = ObjectUtils.notNull(module.getXmlNamespace().toASCIIString());
83    }
84  
85    /**
86     * Retrieves the underlying XML stream writer.
87     *
88     * @return the XML stream writer
89     */
90    @Override
91    @NonNull
92    public XMLStreamWriter2 getXMLStreamWriter() {
93      return getWriter().getResource();
94    }
95  
96    /**
97     * Retrieves the default XML namespace for this schema.
98     *
99     * @return the default namespace URI
100    */
101   @Override
102   @NonNull
103   public String getDefaultNS() {
104     return defaultNS;
105   }
106 
107   /**
108    * Retrieves the namespace used for datatype definitions.
109    *
110    * @return the datatype namespace URI
111    */
112   @NonNull
113   public String getDatatypeNS() {
114     return getDefaultNS();
115   }
116 
117   /**
118    * Retrieves the XML namespace for the given model element.
119    *
120    * @param modelElement
121    *          the model element to get the namespace for
122    * @return the XML namespace URI
123    */
124   @SuppressWarnings("null")
125   @Override
126   @NonNull
127   public String getNS(@NonNull IModelElement modelElement) {
128     return modelElement.getContainingModule().getXmlNamespace().toASCIIString();
129   }
130 
131   /**
132    * Retrieves or generates a namespace prefix for the given namespace.
133    * <p>
134    * Returns {@code null} for the default namespace. For other namespaces,
135    * generates a unique prefix if one does not already exist.
136    *
137    * @param namespace
138    *          the namespace URI to get a prefix for
139    * @return the namespace prefix, or {@code null} if it is the default namespace
140    */
141   public String getNSPrefix(String namespace) {
142     String retval = null;
143     if (!getDefaultNS().equals(namespace)) {
144       retval = namespaceToPrefixMap.computeIfAbsent(
145           namespace,
146           key -> String.format("ns%d", prefixNum.incrementAndGet()));
147     }
148     return retval;
149   }
150 
151   /**
152    * Creates a new qualified name with the given local name and namespace.
153    *
154    * @param localName
155    *          the local name for the QName
156    * @param namespace
157    *          the namespace URI for the QName
158    * @return a new QName with an appropriate prefix
159    */
160   @NonNull
161   protected QName newQName(
162       @NonNull String localName,
163       @NonNull String namespace) {
164     String prefix = null;
165     if (!getDefaultNS().equals(namespace)) {
166       prefix = getNSPrefix(namespace);
167     }
168 
169     return ObjectUtils.notNull(
170         prefix == null ? new QName(namespace, localName) : new QName(namespace, localName, prefix));
171   }
172 
173   /**
174    * Creates a new qualified name for a definition type.
175    *
176    * @param definition
177    *          the definition to create a type name for
178    * @param suffix
179    *          an optional suffix to append to the type name, or {@code null}
180    * @return a new QName for the definition type
181    */
182   @NonNull
183   protected QName newQName(
184       @NonNull IDefinition definition,
185       @Nullable String suffix) {
186     return newQName(
187         getTypeNameForDefinition(definition, suffix),
188         getNS(definition));
189   }
190 
191   /**
192    * Retrieves or creates the XML type representation for a definition.
193    * <p>
194    * Creates and caches the appropriate XML type based on the definition's model
195    * type (flag, field, or assembly).
196    *
197    * @param definition
198    *          the definition to get the XML type for
199    * @return the XML type representing the definition
200    * @throws UnsupportedOperationException
201    *           if the definition is a choice or choice group
202    */
203   @Override
204   public IXmlType getXmlForDefinition(@NonNull IDefinition definition) {
205     IXmlType retval = definitionToTypeMap.get(definition);
206     if (retval == null) {
207       switch (definition.getModelType()) {
208       case FIELD: {
209         IFieldDefinition field = (IFieldDefinition) definition;
210         if (field.getFlagInstances().isEmpty()) {
211           retval = getSimpleType(field);
212         } else {
213           retval = newComplexType(field);
214         }
215         break;
216       }
217       case ASSEMBLY: {
218         retval = newComplexType((IAssemblyDefinition) definition);
219         break;
220       }
221       case FLAG:
222         retval = getSimpleType((IFlagDefinition) definition);
223         break;
224       case CHOICE_GROUP:
225       case CHOICE:
226         throw new UnsupportedOperationException(definition.getModelType().toString());
227       }
228       assert retval != null : definition.getModelType();
229       definitionToTypeMap.put(definition, retval);
230     }
231     return retval;
232   }
233 
234   /**
235    * Retrieves or creates a simple type for a data type adapter.
236    *
237    * @param dataType
238    *          the data type adapter
239    * @return the XML simple type representation
240    */
241   @Override
242   @NonNull
243   public IXmlSimpleType getSimpleType(@NonNull IDataTypeAdapter<?> dataType) {
244     IXmlSimpleType type = dataTypeToSimpleTypeMap.get(dataType);
245     if (type == null) {
246       // lazy initialize and cache the type
247       QName qname = newQName(
248           getDatatypeManager().getTypeNameForDatatype(dataType),
249           getDatatypeNS());
250       type = new XmlSimpleTypeDataTypeReference(qname, dataType);
251       dataTypeToSimpleTypeMap.put(dataType, type);
252     }
253     return type;
254   }
255 
256   /**
257    * Retrieves or creates a simple type for a valued definition.
258    * <p>
259    * If the definition has allowed value constraints, creates an appropriate
260    * restriction or union type. Otherwise, returns the simple type for the
261    * underlying data type.
262    *
263    * @param definition
264    *          the valued definition
265    * @return the XML simple type representation
266    */
267   @Override
268   @NonNull
269   public IXmlSimpleType getSimpleType(@NonNull IValuedDefinition definition) {
270     IXmlSimpleType simpleType = definitionToSimpleTypeMap.get(definition);
271     if (simpleType == null) {
272       AllowedValueCollection allowedValuesCollection = getContextIndependentEnumeratedValues(definition);
273       List<IAllowedValue> allowedValues = allowedValuesCollection.getValues();
274 
275       IDataTypeAdapter<?> dataType = definition.getJavaTypeAdapter();
276       if (allowedValues.isEmpty()) {
277         // just use the built-in type
278         simpleType = getSimpleType(dataType);
279       } else {
280 
281         // generate a restriction on the built-in type for the enumerated values
282         simpleType = new XmlSimpleTypeDataTypeRestriction(
283             newQName(definition, null),
284             definition,
285             allowedValuesCollection);
286 
287         if (!allowedValuesCollection.isClosed()) {
288           // if other values are allowed, we need to make a union of the restriction type
289           // and the base
290           // built-in type
291           simpleType = new XmlSimpleTypeUnion(
292               newQName(definition, "Union"),
293               definition,
294               getSimpleType(dataType),
295               simpleType);
296         }
297       }
298 
299       definitionToSimpleTypeMap.put(definition, simpleType);
300     }
301     return simpleType;
302   }
303 
304   /**
305    * Creates a new complex type for a field definition.
306    *
307    * @param definition
308    *          the field definition
309    * @return a new complex type representation
310    */
311   @NonNull
312   protected IXmlComplexType newComplexType(@NonNull IFieldDefinition definition) {
313     QName qname = newQName(definition, null);
314     return new XmlComplexTypeFieldDefinition(qname, definition);
315   }
316 
317   /**
318    * Creates a new complex type for an assembly definition.
319    *
320    * @param definition
321    *          the assembly definition
322    * @return a new complex type representation
323    */
324   @NonNull
325   protected IXmlComplexType newComplexType(@NonNull IAssemblyDefinition definition) {
326     QName qname = newQName(definition, null);
327     return new XmlComplexTypeAssemblyDefinition(qname, definition);
328   }
329 
330   /**
331    * Generates all XML types that are not inline and are referenced.
332    * <p>
333    * Iterates through all definitions and generates types that need to be written
334    * as separate type definitions in the schema.
335    *
336    * @throws XMLStreamException
337    *           if an error occurs while writing XML content
338    */
339   public void generateXmlTypes() throws XMLStreamException {
340 
341     for (IXmlType type : definitionToTypeMap.values()) {
342       if (!type.isInline(this) && type.isGeneratedType(this) && type.isReferenced(this)) {
343         type.generate(this);
344       } else {
345         assert !type.isGeneratedType(this) || type.isInline(this) || !type.isReferenced(this);
346       }
347     }
348     getDatatypeManager().generateDatatypes(getXMLStreamWriter());
349   }
350 
351   /**
352    * Writes an attribute to the current element.
353    *
354    * @param localName
355    *          the local name of the attribute
356    * @param value
357    *          the value of the attribute
358    * @throws XMLStreamException
359    *           if an error occurs while writing
360    */
361   @Override
362   public void writeAttribute(@NonNull String localName, @NonNull String value) throws XMLStreamException {
363     getXMLStreamWriter().writeAttribute(localName, value);
364   }
365 
366   /**
367    * Writes a start element with the given namespace and local name.
368    *
369    * @param namespaceUri
370    *          the namespace URI for the element
371    * @param localName
372    *          the local name of the element
373    * @throws XMLStreamException
374    *           if an error occurs while writing
375    */
376   @Override
377   public void writeStartElement(@NonNull String namespaceUri, @NonNull String localName) throws XMLStreamException {
378     getXMLStreamWriter().writeStartElement(namespaceUri, localName);
379   }
380 
381   /**
382    * Writes a start element with the given prefix, local name, and namespace.
383    *
384    * @param prefix
385    *          the namespace prefix for the element
386    * @param localName
387    *          the local name of the element
388    * @param namespaceUri
389    *          the namespace URI for the element
390    * @throws XMLStreamException
391    *           if an error occurs while writing
392    */
393   @Override
394   public void writeStartElement(
395       @NonNull String prefix,
396       @NonNull String localName,
397       @NonNull String namespaceUri) throws XMLStreamException {
398     getXMLStreamWriter().writeStartElement(prefix, localName, namespaceUri);
399   }
400 
401   /**
402    * Writes an end element for the current element.
403    *
404    * @throws XMLStreamException
405    *           if an error occurs while writing
406    */
407   @Override
408   public void writeEndElement() throws XMLStreamException {
409     getXMLStreamWriter().writeEndElement();
410   }
411 
412   /**
413    * Writes character content to the current element.
414    *
415    * @param text
416    *          the text content to write
417    * @throws XMLStreamException
418    *           if an error occurs while writing
419    */
420   @Override
421   public void writeCharacters(@NonNull String text) throws XMLStreamException {
422     getXMLStreamWriter().writeCharacters(text);
423   }
424 
425   /**
426    * Writes a namespace declaration.
427    *
428    * @param prefix
429    *          the namespace prefix
430    * @param namespaceUri
431    *          the namespace URI
432    * @throws XMLStreamException
433    *           if an error occurs while writing
434    */
435   @Override
436   public void writeNamespace(String prefix, String namespaceUri) throws XMLStreamException {
437     getXMLStreamWriter().writeNamespace(prefix, namespaceUri);
438   }
439 
440   @Override
441   public void flushWriter() throws IOException {
442     try {
443       getWriter().getResource().flush();
444     } catch (XMLStreamException ex) {
445       throw new IOException(ex);
446     }
447   }
448 }