1   /*
2    * SPDX-FileCopyrightText: none
3    * SPDX-License-Identifier: CC0-1.0
4    */
5   
6   package gov.nist.secauto.metaschema.schemagen.xml.impl;
7   
8   import gov.nist.secauto.metaschema.core.configuration.IConfiguration;
9   import gov.nist.secauto.metaschema.core.datatype.IDataTypeAdapter;
10  import gov.nist.secauto.metaschema.core.model.IAssemblyDefinition;
11  import gov.nist.secauto.metaschema.core.model.IDefinition;
12  import gov.nist.secauto.metaschema.core.model.IFieldDefinition;
13  import gov.nist.secauto.metaschema.core.model.IFlagDefinition;
14  import gov.nist.secauto.metaschema.core.model.IModelElement;
15  import gov.nist.secauto.metaschema.core.model.IModule;
16  import gov.nist.secauto.metaschema.core.model.IValuedDefinition;
17  import gov.nist.secauto.metaschema.core.model.constraint.IAllowedValue;
18  import gov.nist.secauto.metaschema.core.util.AutoCloser;
19  import gov.nist.secauto.metaschema.core.util.ObjectUtils;
20  import gov.nist.secauto.metaschema.schemagen.AbstractGenerationState;
21  import gov.nist.secauto.metaschema.schemagen.SchemaGenerationException;
22  import gov.nist.secauto.metaschema.schemagen.SchemaGenerationFeature;
23  import gov.nist.secauto.metaschema.schemagen.xml.XmlDatatypeManager;
24  import gov.nist.secauto.metaschema.schemagen.xml.impl.schematype.IXmlComplexType;
25  import gov.nist.secauto.metaschema.schemagen.xml.impl.schematype.IXmlSimpleType;
26  import gov.nist.secauto.metaschema.schemagen.xml.impl.schematype.IXmlType;
27  import gov.nist.secauto.metaschema.schemagen.xml.impl.schematype.XmlComplexTypeAssemblyDefinition;
28  import gov.nist.secauto.metaschema.schemagen.xml.impl.schematype.XmlComplexTypeFieldDefinition;
29  import gov.nist.secauto.metaschema.schemagen.xml.impl.schematype.XmlSimpleTypeDataTypeReference;
30  import gov.nist.secauto.metaschema.schemagen.xml.impl.schematype.XmlSimpleTypeDataTypeRestriction;
31  import gov.nist.secauto.metaschema.schemagen.xml.impl.schematype.XmlSimpleTypeUnion;
32  
33  import org.codehaus.stax2.XMLStreamWriter2;
34  
35  import java.io.IOException;
36  import java.util.List;
37  import java.util.Map;
38  import java.util.concurrent.ConcurrentHashMap;
39  import java.util.concurrent.atomic.AtomicInteger;
40  
41  import javax.xml.namespace.QName;
42  import javax.xml.stream.XMLStreamException;
43  
44  import edu.umd.cs.findbugs.annotations.NonNull;
45  import edu.umd.cs.findbugs.annotations.Nullable;
46  
47  public class XmlGenerationState
48      extends AbstractGenerationState<AutoCloser<XMLStreamWriter2, SchemaGenerationException>, XmlDatatypeManager> {
49    @NonNull
50    private final String defaultNS;
51    @NonNull
52    private final Map<String, String> namespaceToPrefixMap = new ConcurrentHashMap<>();
53    @NonNull
54    private final Map<IDataTypeAdapter<?>, IXmlSimpleType> dataTypeToSimpleTypeMap = new ConcurrentHashMap<>();
55    @NonNull
56    private final Map<IValuedDefinition, IXmlSimpleType> definitionToSimpleTypeMap = new ConcurrentHashMap<>();
57    @NonNull
58    private final Map<IDefinition, IXmlType> definitionToTypeMap = new ConcurrentHashMap<>();
59  
60    private final AtomicInteger prefixNum = new AtomicInteger(); // 0
61  
62    public XmlGenerationState(
63        @NonNull IModule module,
64        @NonNull AutoCloser<XMLStreamWriter2, SchemaGenerationException> writer,
65        @NonNull IConfiguration<SchemaGenerationFeature<?>> configuration) {
66      super(module, writer, configuration, new XmlDatatypeManager());
67      this.defaultNS = ObjectUtils.notNull(module.getXmlNamespace().toASCIIString());
68    }
69  
70    @SuppressWarnings("resource")
71    @NonNull
72    public XMLStreamWriter2 getXMLStreamWriter() {
73      return getWriter().getResource();
74    }
75  
76    @NonNull
77    public String getDefaultNS() {
78      return defaultNS;
79    }
80  
81    @NonNull
82    public String getDatatypeNS() {
83      return getDefaultNS();
84    }
85  
86    @SuppressWarnings("null")
87    @NonNull
88    public String getNS(@NonNull IModelElement modelElement) {
89      return modelElement.getContainingModule().getXmlNamespace().toASCIIString();
90    }
91  
92    public String getNSPrefix(String namespace) {
93      String retval = null;
94      if (!getDefaultNS().equals(namespace)) {
95        retval = namespaceToPrefixMap.computeIfAbsent(
96            namespace,
97            key -> String.format("ns%d", prefixNum.incrementAndGet()));
98      }
99      return retval;
100   }
101 
102   @NonNull
103   protected QName newQName(
104       @NonNull String localName,
105       @NonNull String namespace) {
106     String prefix = null;
107     if (!getDefaultNS().equals(namespace)) {
108       prefix = getNSPrefix(namespace);
109     }
110 
111     return ObjectUtils.notNull(
112         prefix == null ? new QName(namespace, localName) : new QName(namespace, localName, prefix));
113   }
114 
115   @NonNull
116   protected QName newQName(
117       @NonNull IDefinition definition,
118       @Nullable String suffix) {
119     return newQName(
120         getTypeNameForDefinition(definition, suffix),
121         getNS(definition));
122   }
123 
124   public IXmlType getXmlForDefinition(@NonNull IDefinition definition) {
125     IXmlType retval = definitionToTypeMap.get(definition);
126     if (retval == null) {
127       switch (definition.getModelType()) {
128       case FIELD: {
129         IFieldDefinition field = (IFieldDefinition) definition;
130         if (field.getFlagInstances().isEmpty()) {
131           retval = getSimpleType(field);
132         } else {
133           retval = newComplexType(field);
134         }
135         break;
136       }
137       case ASSEMBLY: {
138         retval = newComplexType((IAssemblyDefinition) definition);
139         break;
140       }
141       case FLAG:
142         retval = getSimpleType((IFlagDefinition) definition);
143         break;
144       case CHOICE_GROUP:
145       case CHOICE:
146       default:
147         throw new UnsupportedOperationException(definition.getModelType().toString());
148       }
149       definitionToTypeMap.put(definition, retval);
150     }
151     return retval;
152   }
153 
154   @NonNull
155   public IXmlSimpleType getSimpleType(@NonNull IDataTypeAdapter<?> dataType) {
156     IXmlSimpleType type = dataTypeToSimpleTypeMap.get(dataType);
157     if (type == null) {
158       // lazy initialize and cache the type
159       QName qname = newQName(
160           getDatatypeManager().getTypeNameForDatatype(dataType),
161           getDatatypeNS());
162       type = new XmlSimpleTypeDataTypeReference(qname, dataType);
163       dataTypeToSimpleTypeMap.put(dataType, type);
164     }
165     return type;
166   }
167 
168   @NonNull
169   public IXmlSimpleType getSimpleType(@NonNull IValuedDefinition definition) {
170     IXmlSimpleType simpleType = definitionToSimpleTypeMap.get(definition);
171     if (simpleType == null) {
172       AllowedValueCollection allowedValuesCollection = getContextIndependentEnumeratedValues(definition);
173       List<IAllowedValue> allowedValues = allowedValuesCollection.getValues();
174 
175       IDataTypeAdapter<?> dataType = definition.getJavaTypeAdapter();
176       if (allowedValues.isEmpty()) {
177         // just use the built-in type
178         simpleType = getSimpleType(dataType);
179       } else {
180 
181         // generate a restriction on the built-in type for the enumerated values
182         simpleType = new XmlSimpleTypeDataTypeRestriction(
183             newQName(definition, null),
184             definition,
185             allowedValuesCollection);
186 
187         if (!allowedValuesCollection.isClosed()) {
188           // if other values are allowed, we need to make a union of the restriction type
189           // and the base
190           // built-in type
191           simpleType = new XmlSimpleTypeUnion(
192               newQName(definition, "Union"),
193               definition,
194               getSimpleType(dataType),
195               simpleType);
196         }
197       }
198 
199       definitionToSimpleTypeMap.put(definition, simpleType);
200     }
201     return simpleType;
202   }
203 
204   @NonNull
205   protected IXmlComplexType newComplexType(@NonNull IFieldDefinition definition) {
206     QName qname = newQName(definition, null);
207     return new XmlComplexTypeFieldDefinition(qname, definition);
208   }
209 
210   @NonNull
211   protected IXmlComplexType newComplexType(@NonNull IAssemblyDefinition definition) {
212     QName qname = newQName(definition, null);
213     return new XmlComplexTypeAssemblyDefinition(qname, definition);
214   }
215 
216   public void generateXmlTypes() throws XMLStreamException {
217 
218     for (IXmlType type : definitionToTypeMap.values()) {
219       if (!type.isInline(this) && type.isGeneratedType(this) && type.isReferenced(this)) {
220         type.generate(this);
221       } else {
222         assert !type.isGeneratedType(this) || type.isInline(this) || !type.isReferenced(this);
223       }
224     }
225     getDatatypeManager().generateDatatypes(getXMLStreamWriter());
226   }
227 
228   public void writeAttribute(@NonNull String localName, @NonNull String value) throws XMLStreamException {
229     getXMLStreamWriter().writeAttribute(localName, value);
230   }
231 
232   public void writeStartElement(@NonNull String namespaceUri, @NonNull String localName) throws XMLStreamException {
233     getXMLStreamWriter().writeStartElement(namespaceUri, localName);
234   }
235 
236   public void writeStartElement(
237       @NonNull String prefix,
238       @NonNull String localName,
239       @NonNull String namespaceUri) throws XMLStreamException {
240     getXMLStreamWriter().writeStartElement(prefix, localName, namespaceUri);
241 
242   }
243 
244   public void writeEndElement() throws XMLStreamException {
245     getXMLStreamWriter().writeEndElement();
246   }
247 
248   public void writeCharacters(@NonNull String text) throws XMLStreamException {
249     getXMLStreamWriter().writeCharacters(text);
250   }
251 
252   public void writeNamespace(String prefix, String namespaceUri) throws XMLStreamException {
253     getXMLStreamWriter().writeNamespace(prefix, namespaceUri);
254   }
255 
256   @SuppressWarnings("resource")
257   @Override
258   public void flushWriter() throws IOException {
259     try {
260       getWriter().getResource().flush();
261     } catch (XMLStreamException ex) {
262       throw new IOException(ex);
263     }
264   }
265 }