Debian Codegraph @

net/sf/saxon/serialize/Emitter.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.serialize;
9
10 import net.sf.saxon.event.ReceiverWithOutputProperties;
11 import net.sf.saxon.event.SequenceReceiver;
12 import net.sf.saxon.expr.parser.Location;
13 import net.sf.saxon.lib.SaxonOutputKeys;
14 import net.sf.saxon.om.Item;
15 import net.sf.saxon.om.NodeInfo;
16 import net.sf.saxon.serialize.charcode.CharacterSet;
17 import net.sf.saxon.serialize.charcode.UTF16CharacterSet;
18 import net.sf.saxon.serialize.charcode.UTF8CharacterSet;
19 import net.sf.saxon.trans.SaxonErrorCode;
20 import net.sf.saxon.trans.XPathException;
21
22 import javax.xml.transform.OutputKeys;
23 import javax.xml.transform.stream.StreamResult;
24 import java.io.*;
25 import java.net.URISyntaxException;
26 import java.util.Properties;
27
28
29 /**
30 * Emitter: This abstract class defines methods that must be implemented by
31 * components that format SAXON output. There is one emitter for XML,
32 * one for HTML, and so on. Additional methods are concerned with
33 * setting options and providing a Writer.
34 * <p>The interface is deliberately designed to be as close as possible to the
35 * standard SAX2 ContentHandler interface, however, it allows additional
36 * information to be made available.</p>
37 * <p>An Emitter is a Receiver, specifically it is a Receiver that can direct output
38 * to a Writer or OutputStream, using serialization properties defined in a Properties
39 * object.</p>
40 */
41
42 public abstract class Emitter extends SequenceReceiver implements ReceiverWithOutputProperties {
43 protected StreamResult streamResult;
44 protected Writer writer;
45 protected OutputStream outputStream;
46 protected Properties outputProperties;
47 protected CharacterSet characterSet;
48 protected boolean allCharactersEncodable = false;
49 private boolean mustClose = false;
50
51 public Emitter() {
52 super(null);
53 }
54
55 /**
56 * Set output properties
57 *
58 * @param details the output serialization properties
59 * @throws net.sf.saxon.trans.XPathException
60 * if an error occurs finding the encoding property
61 */
62
63 public void setOutputProperties(Properties details) throws XPathException {
64 if (characterSet == null) {
65 characterSet = getConfiguration().getCharacterSetFactory().getCharacterSet(details);
66 allCharactersEncodable = (characterSet instanceof UTF8CharacterSet ||
67 characterSet instanceof UTF16CharacterSet);
68 }
69 outputProperties = details;
70 }
71
72 /**
73 * Get the output properties
74 *
75 * @return the output serialization properties. The returned value will be null if setOutputProperties()
76 * has not been called
77 */
78
79 public Properties getOutputProperties() {
80 return outputProperties;
81 }
82
83 /**
84 * Set the StreamResult acting as the output destination of the Emitter
85 *
86 * @param result the output destination
87 * @throws net.sf.saxon.trans.XPathException
88 * if an error occurs
89 */
90
91 public void setStreamResult(StreamResult result) throws XPathException {
92 streamResult = result;
93 if (systemId == null) {
94 systemId = result.getSystemId();
95 }
96 }
97
98 /**
99 * Make a Writer for this Emitter to use, given a StreamResult.
100 *
101 * @throws net.sf.saxon.trans.XPathException
102 * if an error occurs
103 */
104
105 protected void makeWriter() throws XPathException {
106 if (writer != null) {
107 return;
108 }
109 if (streamResult == null) {
110 throw new IllegalStateException("Emitter must have either a Writer or a StreamResult to write to");
111 }
112 writer = streamResult.getWriter();
113 if (writer == null) {
114 OutputStream os = streamResult.getOutputStream();
115 if (os != null) {
116 setOutputStream(os);
117 }
118 }
119 if (writer == null) {
120 makeOutputStream();
121 }
122 }
123
124 @SuppressWarnings({"ResultOfMethodCallIgnored"})
125 protected OutputStream makeOutputStream() throws XPathException {
126 String uriString = streamResult.getSystemId();
127 if (uriString == null) {
128 throw new XPathException("Result has no system ID, writer, or output stream defined");
129 }
130
131 try {
132 File file = ExpandedStreamResult.makeWritableOutputFile(uriString);
133 setOutputStream(new FileOutputStream(file));
134 // Set the outputstream in the StreamResult object so that the
135 // call on OutputURIResolver.close() can close it
136 streamResult.setOutputStream(outputStream);
137 mustClose = true;
138 } catch (FileNotFoundException | URISyntaxException | IllegalArgumentException fnf) {
139 XPathException err = new XPathException("Unable to write to output destination", fnf);
140 err.setErrorCode(SaxonErrorCode.SXRD0004);
141 throw err;
142
143 } // for example, the system ID doesn't use the file: scheme
144
145 return outputStream;
146 }
147
148 /**
149 * Determine whether the Emitter wants a Writer for character output or
150 * an OutputStream for binary output. The standard Emitters all use a Writer, so
151 * this returns true; but a subclass can override this if it wants to use an OutputStream
152 *
153 * @return true if a Writer is needed, as distinct from an OutputStream
154 */
155
156 public boolean usesWriter() {
157 return true;
158 }
159
160 /**
161 * Set the output destination as a character stream
162 *
163 * @param writer the Writer to use as an output destination
164 * @throws net.sf.saxon.trans.XPathException
165 * if an error occurs
166 */
167
168 public void setWriter(Writer writer) throws XPathException {
169 this.writer = writer;
170
171 // If the writer uses a known encoding, change the encoding in the XML declaration
172 // to match. Any encoding actually specified in xsl:output is ignored, because encoding
173 // is being done by the user-supplied Writer, and not by Saxon itself.
174
175 if (writer instanceof OutputStreamWriter && outputProperties != null) {
176 String enc = ((OutputStreamWriter) writer).getEncoding();
177 outputProperties.setProperty(OutputKeys.ENCODING, enc);
178 characterSet = getConfiguration().getCharacterSetFactory().getCharacterSet(outputProperties);
179 allCharactersEncodable = (characterSet instanceof UTF8CharacterSet ||
180 characterSet instanceof UTF16CharacterSet);
181 }
182 }
183
184 /**
185 * Get the output writer
186 *
187 * @return the Writer being used as an output destination, if any
188 */
189
190 public Writer getWriter() {
191 return writer;
192 }
193
194 /**
195 * Set the output destination as a byte stream.
196 * <p>Note that if a specific encoding (other than the default, UTF-8) is required, then
197 * {@link #setOutputProperties(java.util.Properties)} must be called <i>before</i> calling
198 * this method.</p>
199 *
200 * @param stream the OutputStream being used as an output destination
201 * @throws net.sf.saxon.trans.XPathException
202 * if an error occurs
203 */
204
205 public void setOutputStream(OutputStream stream) throws XPathException {
206 outputStream = stream;
207
208 // If the user supplied an OutputStream, but the Emitter is written to
209 // use a Writer (this is the most common case), then we create a Writer
210 // to wrap the supplied OutputStream; the complications are to ensure that
211 // the character encoding is correct.
212
213 if (usesWriter()) {
214
215 if (outputProperties == null) {
216 outputProperties = new Properties();
217 }
218
219 String encoding = outputProperties.getProperty(OutputKeys.ENCODING);
220 if (encoding == null) {
221 encoding = "UTF8";
222 allCharactersEncodable = true;
223 } else if (encoding.equalsIgnoreCase("UTF-8")) {
224 encoding = "UTF8";
225 allCharactersEncodable = true;
226 } else if (encoding.equalsIgnoreCase("UTF-16")) {
227 encoding = "UTF16";
228 }
229
230 if (characterSet == null) {
231 characterSet = getConfiguration().getCharacterSetFactory().getCharacterSet(outputProperties);
232 }
233
234 String byteOrderMark = outputProperties.getProperty(SaxonOutputKeys.BYTE_ORDER_MARK);
235 if ("no".equals(byteOrderMark) && "UTF16".equals(encoding)) {
236 // Java always writes a bom for UTF-16, so if the user doesn't want one, use utf16-be
237 encoding = "UTF-16BE";
238 } else if (!(characterSet instanceof UTF8CharacterSet)) {
239
240 //if (characterSet instanceof PluggableCharacterSet) {
241 encoding = characterSet.getCanonicalName();
242 }
243
244 while (true) {
245 try {
246 String javaEncoding = encoding;
247 if (encoding.equalsIgnoreCase("iso-646") || encoding.equalsIgnoreCase("iso646")) {
248 javaEncoding = "US-ASCII";
249 }
250 if (encoding.equalsIgnoreCase("UTF8")) {
251 writer = new UTF8Writer(outputStream);
252 } else {
253 writer = new BufferedWriter(
254 new OutputStreamWriter(
255 outputStream, javaEncoding));
256 }
257 break;
258 } catch (Exception err) {
259 if (encoding.equalsIgnoreCase("UTF8")) {
260 throw new XPathException("Failed to create a UTF8 output writer");
261 }
262 XPathException de = new XPathException("Encoding " + encoding + " is not supported: using UTF8");
263 de.setErrorCode("SESU0007");
264 getPipelineConfiguration().getErrorListener().error(de);
265 encoding = "UTF8";
266 characterSet = UTF8CharacterSet.getInstance();
267 allCharactersEncodable = true;
268 outputProperties.setProperty(OutputKeys.ENCODING, "UTF-8");
269 }
270 }
271 }
272
273 }
274
275 /**
276 * Get the output stream
277 *
278 * @return the OutputStream being used as an output destination, if any
279 */
280
281 public OutputStream getOutputStream() {
282 return outputStream;
283 }
284
285 /**
286 * Set unparsed entity URI. Needed to satisfy the Receiver interface, but not used,
287 * because unparsed entities can occur only in input documents, not in output documents.
288 *
289 * @param name the entity name
290 * @param uri the entity system ID
291 * @param publicId the entity public ID
292 */
293
294 public void setUnparsedEntity(String name, String uri, String publicId) throws XPathException {
295 }
296
297 /**
298 * Notify the end of the event stream
299 */
300
301 public void close() throws XPathException {
302 if (mustClose && outputStream != null) {
303 try {
304 outputStream.close();
305 } catch (IOException e) {
306 throw new XPathException("Failed to close output stream");
307 }
308 }
309 }
310
311 /**
312 * Ask whether this Receiver (or the downstream pipeline) makes any use of the type annotations
313 * supplied on element and attribute events
314 *
315 * @return true if the Receiver makes any use of this information. If false, the caller
316 * may supply untyped nodes instead of supplying the type annotation (or conversely, it may
317 * avoid stripping unwanted type annotations)
318 */
319 public boolean usesTypeAnnotations() {
320 return false;
321 }
322
323 /**
324 * Append an arbitrary item (node or atomic value) to the output
325 */
326
327 public void append(/*@Nullable*/ Item item, Location locationId, int copyNamespaces) throws XPathException {
328 if (item instanceof NodeInfo) {
329 decompose(item, locationId, copyNamespaces);
330 } else {
331 characters(item.getStringValueCS(), locationId, 0);
332 }
333 }
334
335 }
336