1   /*
2    * SPDX-FileCopyrightText: none
3    * SPDX-License-Identifier: CC0-1.0
4    */
5   
6   package gov.nist.secauto.metaschema.schemagen.xml; // NOPMD
7   
8   import com.ctc.wstx.stax.WstxOutputFactory;
9   
10  import gov.nist.secauto.metaschema.core.configuration.IConfiguration;
11  import gov.nist.secauto.metaschema.core.datatype.markup.MarkupMultiline;
12  import gov.nist.secauto.metaschema.core.model.IAssemblyDefinition;
13  import gov.nist.secauto.metaschema.core.model.IModule;
14  import gov.nist.secauto.metaschema.core.util.AutoCloser;
15  import gov.nist.secauto.metaschema.core.util.ObjectUtils;
16  import gov.nist.secauto.metaschema.schemagen.AbstractSchemaGenerator;
17  import gov.nist.secauto.metaschema.schemagen.SchemaGenerationException;
18  import gov.nist.secauto.metaschema.schemagen.SchemaGenerationFeature;
19  import gov.nist.secauto.metaschema.schemagen.xml.impl.XmlGenerationState;
20  import gov.nist.secauto.metaschema.schemagen.xml.impl.schematype.IXmlType;
21  
22  import org.codehaus.stax2.XMLOutputFactory2;
23  import org.codehaus.stax2.XMLStreamWriter2;
24  
25  import java.io.IOException;
26  import java.io.InputStream;
27  import java.io.StringReader;
28  import java.io.StringWriter;
29  import java.io.Writer;
30  import java.util.HashMap;
31  import java.util.List;
32  import java.util.Map;
33  
34  import javax.xml.namespace.QName;
35  import javax.xml.stream.XMLOutputFactory;
36  import javax.xml.stream.XMLStreamException;
37  import javax.xml.transform.Source;
38  import javax.xml.transform.Transformer;
39  import javax.xml.transform.TransformerConfigurationException;
40  import javax.xml.transform.TransformerException;
41  import javax.xml.transform.TransformerFactory;
42  import javax.xml.transform.stream.StreamResult;
43  import javax.xml.transform.stream.StreamSource;
44  
45  import edu.umd.cs.findbugs.annotations.NonNull;
46  import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
47  
48  public class XmlSchemaGenerator
49      extends AbstractSchemaGenerator<
50          AutoCloser<XMLStreamWriter2, SchemaGenerationException>,
51          XmlDatatypeManager,
52          XmlGenerationState> {
53    // private static final Logger LOGGER =
54    // LogManager.getLogger(XmlSchemaGenerator.class);
55  
56    @NonNull
57    public static final String PREFIX_XML_SCHEMA = "xs";
58    @NonNull
59    public static final String NS_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
60    @NonNull
61    private static final String PREFIX_XML_SCHEMA_VERSIONING = "vs";
62    @NonNull
63    private static final String NS_XML_SCHEMA_VERSIONING = "http://www.w3.org/2007/XMLSchema-versioning";
64    @NonNull
65    public static final String NS_XHTML = "http://www.w3.org/1999/xhtml";
66  
67    @NonNull
68    private final XMLOutputFactory2 xmlOutputFactory;
69  
70    @NonNull
71    private static XMLOutputFactory2 defaultXMLOutputFactory() {
72      XMLOutputFactory2 xmlOutputFactory = (XMLOutputFactory2) XMLOutputFactory.newInstance();
73      assert xmlOutputFactory instanceof WstxOutputFactory;
74      xmlOutputFactory.configureForSpeed();
75      xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
76      return xmlOutputFactory;
77    }
78  
79    public XmlSchemaGenerator() {
80      this(defaultXMLOutputFactory());
81    }
82  
83    @SuppressFBWarnings("EI_EXPOSE_REP2")
84    public XmlSchemaGenerator(@NonNull XMLOutputFactory2 xmlOutputFactory) {
85      this.xmlOutputFactory = xmlOutputFactory;
86    }
87  
88    protected XMLOutputFactory2 getXmlOutputFactory() {
89      return xmlOutputFactory;
90    }
91  
92    @Override
93    protected AutoCloser<XMLStreamWriter2, SchemaGenerationException> newWriter(
94        Writer out) {
95      XMLStreamWriter2 writer;
96      try {
97        writer = ObjectUtils.notNull((XMLStreamWriter2) getXmlOutputFactory().createXMLStreamWriter(out));
98      } catch (XMLStreamException ex) {
99        throw new SchemaGenerationException(ex);
100     }
101     return AutoCloser.autoClose(writer, t -> {
102       try {
103         t.close();
104       } catch (XMLStreamException ex) {
105         throw new SchemaGenerationException(ex);
106       }
107     });
108   }
109 
110   @Override
111   protected XmlGenerationState newGenerationState(
112       IModule module,
113       AutoCloser<XMLStreamWriter2, SchemaGenerationException> schemaWriter,
114       IConfiguration<SchemaGenerationFeature<?>> configuration) {
115     return new XmlGenerationState(module, schemaWriter, configuration);
116   }
117 
118   @Override
119   public void generateFromModule(
120       @NonNull IModule module,
121       @NonNull Writer out,
122       @NonNull IConfiguration<SchemaGenerationFeature<?>> configuration) {
123     // super.generateFromModule(module, out, configuration);
124 
125     String generatedSchema;
126     try (StringWriter stringWriter = new StringWriter()) {
127       super.generateFromModule(module, stringWriter, configuration);
128       generatedSchema = stringWriter.toString();
129     } catch (IOException ex) {
130       throw new SchemaGenerationException(ex);
131     }
132 
133     try (InputStream is = getClass().getResourceAsStream("/identity.xsl")) {
134       Source xsltSource = new StreamSource(is);
135 
136       // TransformerFactory transformerFactory = TransformerFactory.newInstance();
137       TransformerFactory transformerFactory = new net.sf.saxon.TransformerFactoryImpl();
138       Transformer transformer = transformerFactory.newTransformer(xsltSource);
139 
140       try (StringReader stringReader = new StringReader(generatedSchema)) {
141         Source xmlSource = new StreamSource(stringReader);
142 
143         StreamResult result = new StreamResult(out);
144         transformer.transform(xmlSource, result);
145       } catch (TransformerException ex) {
146         throw new SchemaGenerationException(ex);
147       }
148     } catch (IOException | TransformerConfigurationException ex) {
149       throw new SchemaGenerationException(ex);
150     }
151   }
152 
153   @Override
154   protected void generateSchema(XmlGenerationState state) {
155 
156     try {
157       String targetNS = state.getDefaultNS();
158 
159       // analyze all definitions
160       Map<String, String> prefixToNamespaceMap = new HashMap<>(); // NOPMD concurrency not needed
161       final List<IAssemblyDefinition> rootAssemblyDefinitions = analyzeDefinitions(
162           state,
163           (entry, definition) -> {
164             assert entry != null;
165             assert definition != null;
166             IXmlType type = state.getXmlForDefinition(definition);
167             if (!entry.isInline()) {
168               QName qname = type.getQName();
169               String namespace = qname.getNamespaceURI();
170               if (!targetNS.equals(namespace)) {
171                 // collect namespaces and prefixes for definitions with a different namespace
172                 prefixToNamespaceMap.computeIfAbsent(qname.getPrefix(), x -> namespace);
173               }
174             }
175           });
176 
177       // write some root elements
178       XMLStreamWriter2 writer = state.getXMLStreamWriter();
179       writer.writeStartDocument("UTF-8", "1.0");
180       writer.writeStartElement(PREFIX_XML_SCHEMA, "schema", NS_XML_SCHEMA);
181       writer.writeDefaultNamespace(targetNS);
182       writer.writeNamespace(PREFIX_XML_SCHEMA_VERSIONING, NS_XML_SCHEMA_VERSIONING);
183 
184       // write namespaces for all indexed definitions
185       for (Map.Entry<String, String> entry : prefixToNamespaceMap.entrySet()) {
186         state.writeNamespace(entry.getKey(), entry.getValue());
187       }
188 
189       IModule module = state.getModule();
190 
191       // write remaining root attributes
192       writer.writeAttribute("targetNamespace", targetNS);
193       writer.writeAttribute("elementFormDefault", "qualified");
194       writer.writeAttribute(NS_XML_SCHEMA_VERSIONING, "minVersion", "1.0");
195       writer.writeAttribute(NS_XML_SCHEMA_VERSIONING, "maxVersion", "1.1");
196       writer.writeAttribute("version", module.getVersion());
197 
198       generateSchemaMetadata(module, state);
199 
200       for (IAssemblyDefinition definition : rootAssemblyDefinitions) {
201         QName xmlQName = definition.getRootXmlQName();
202         if (xmlQName != null
203             && (xmlQName.getNamespaceURI() == null || state.getDefaultNS().equals(xmlQName.getNamespaceURI()))) {
204           generateRootElement(definition, state);
205         }
206       }
207 
208       state.generateXmlTypes();
209 
210       writer.writeEndElement(); // xs:schema
211       writer.writeEndDocument();
212       writer.flush();
213     } catch (XMLStreamException ex) {
214       throw new SchemaGenerationException(ex);
215     }
216   }
217 
218   protected static void generateSchemaMetadata(
219       @NonNull IModule module,
220       @NonNull XmlGenerationState state)
221       throws XMLStreamException {
222     String targetNS = ObjectUtils.notNull(module.getXmlNamespace().toASCIIString());
223     state.writeStartElement(PREFIX_XML_SCHEMA, "annotation", NS_XML_SCHEMA);
224     state.writeStartElement(PREFIX_XML_SCHEMA, "appinfo", NS_XML_SCHEMA);
225 
226     state.writeStartElement(targetNS, "schema-name");
227 
228     module.getName().writeXHtml(targetNS, state.getXMLStreamWriter());
229 
230     state.writeEndElement();
231 
232     state.writeStartElement(targetNS, "schema-version");
233     state.writeCharacters(module.getVersion());
234     state.writeEndElement();
235 
236     state.writeStartElement(targetNS, "short-name");
237     state.writeCharacters(module.getShortName());
238     state.writeEndElement();
239 
240     state.writeEndElement();
241 
242     MarkupMultiline remarks = module.getRemarks();
243     if (remarks != null) {
244       state.writeStartElement(PREFIX_XML_SCHEMA, "documentation", NS_XML_SCHEMA);
245 
246       remarks.writeXHtml(targetNS, state.getXMLStreamWriter());
247       state.writeEndElement();
248     }
249 
250     state.writeEndElement();
251   }
252 
253   private static void generateRootElement(@NonNull IAssemblyDefinition definition, @NonNull XmlGenerationState state)
254       throws XMLStreamException {
255     assert definition.isRoot();
256 
257     XMLStreamWriter2 writer = state.getXMLStreamWriter();
258     QName xmlQName = definition.getRootXmlQName();
259 
260     writer.writeStartElement(PREFIX_XML_SCHEMA, "element", NS_XML_SCHEMA);
261     writer.writeAttribute("name", xmlQName.getLocalPart());
262     writer.writeAttribute("type", state.getXmlForDefinition(definition).getTypeReference());
263 
264     writer.writeEndElement();
265   }
266 }