Debian Codegraph @

net/sf/saxon/serialize/ExpandedStreamResult.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.Configuration;
11 import net.sf.saxon.lib.SaxonOutputKeys;
12 import net.sf.saxon.serialize.charcode.CharacterSet;
13 import net.sf.saxon.serialize.charcode.UTF16CharacterSet;
14 import net.sf.saxon.serialize.charcode.UTF8CharacterSet;
15 import net.sf.saxon.trans.SaxonErrorCode;
16 import net.sf.saxon.trans.XPathException;
17
18 import javax.xml.transform.OutputKeys;
19 import javax.xml.transform.stream.StreamResult;
20 import java.io.*;
21 import java.net.URI;
22 import java.net.URISyntaxException;
23 import java.util.Properties;
24
25 /**
26 * An ExpandedStreamResult is similar to a StreamResult, and is created from a StreamResult. It contains
27 * methods to construct a Writer from an OutputStream, and an OutputStream from a File or URI, and
28 * (unlike StreamResult) its getWriter() and getOutputStream() methods can therefore be used whether
29 * or not the writer and outputstream were explicitly set.
30 */
31 public class ExpandedStreamResult {
32
33 private Configuration config;
34 private Properties outputProperties;
35 private String systemId;
36 private Writer writer;
37 private OutputStream outputStream;
38 private CharacterSet characterSet;
39 private String encoding;
40 private boolean mustClose;
41 private boolean allCharactersEncodable;
42
43 public ExpandedStreamResult(Configuration config, StreamResult result, Properties outputProperties) throws XPathException {
44 this.config = config;
45 this.systemId = result.getSystemId();
46 this.writer = result.getWriter();
47 this.outputStream = result.getOutputStream();
48 this.encoding = outputProperties.getProperty(OutputKeys.ENCODING);
49 if (encoding == null) {
50 encoding = "UTF8";
51 allCharactersEncodable = true;
52 } else if (encoding.equalsIgnoreCase("UTF-8")) {
53 encoding = "UTF8";
54 allCharactersEncodable = true;
55 } else if (encoding.equalsIgnoreCase("UTF-16")) {
56 encoding = "UTF16";
57 }
58
59 if (characterSet == null) {
60 characterSet = config.getCharacterSetFactory().getCharacterSet(encoding);
61 }
62
63 String byteOrderMark = outputProperties.getProperty(SaxonOutputKeys.BYTE_ORDER_MARK);
64 if ("no".equals(byteOrderMark) && "UTF16".equals(encoding)) {
65 // Java always writes a bom for UTF-16, so if the user doesn't want one, use utf16-be
66 encoding = "UTF-16BE";
67 } else if (!(characterSet instanceof UTF8CharacterSet)) {
68
69 //if (characterSet instanceof PluggableCharacterSet) {
70 encoding = characterSet.getCanonicalName();
71 }
72
73 }
74
75 /**
76 * Make a Writer for this Emitter to use, given a StreamResult.
77 *
78 * @throws net.sf.saxon.trans.XPathException if an error occurs
79 */
80
81 public Writer obtainWriter() throws XPathException {
82 if (writer != null) {
83 return writer;
84 } else {
85 OutputStream os = obtainOutputStream();
86 writer = makeWriterFromOutputStream(os);
87 return writer;
88 }
89 }
90
91 protected OutputStream obtainOutputStream() throws XPathException {
92 if (outputStream != null) {
93 return outputStream;
94 }
95 String uriString = systemId;
96 if (uriString == null) {
97 throw new XPathException("Result has no system ID, writer, or output stream defined");
98 }
99
100 try {
101 File file = makeWritableOutputFile(uriString);
102 outputStream = new FileOutputStream(file);
103 // Set the outputstream in the StreamResult object so that the
104 // call on OutputURIResolver.close() can close it
105 //streamResult.setOutputStream(outputStream);
106 mustClose = true;
107 } catch (FileNotFoundException | URISyntaxException | IllegalArgumentException fnf) {
108 // for example, the system ID doesn't use the file: scheme
109 throw new XPathException(fnf);
110 }
111
112 return outputStream;
113 }
114
115 public static File makeWritableOutputFile(String uriString) throws URISyntaxException, XPathException {
116 URI uri = new URI(uriString);
117 if (!uri.isAbsolute()) {
118 try {
119 uri = new File(uriString).getAbsoluteFile().toURI();
120 } catch (Exception e) {
121 // if we fail, we'll get another exception
122 }
123 }
124 File file = new File(uri);
125 try {
126 if ("file".equals(uri.getScheme()) && !file.exists()) {
127 File directory = file.getParentFile();
128 if (directory != null && !directory.exists()) {
129 directory.mkdirs();
130 }
131 file.createNewFile();
132 }
133 if (file.isDirectory()) {
134 throw new XPathException("Cannot write to a directory: " + uriString, SaxonErrorCode.SXRD0004);
135 }
136 if (!file.canWrite()) {
137 throw new XPathException("Cannot write to URI " + uriString, SaxonErrorCode.SXRD0004);
138 }
139 } catch (IOException err) {
140 throw new XPathException("Failed to create output file " + uri, err);
141 }
142 return file;
143 }
144
145 /**
146 * Determine whether the Emitter wants a Writer for character output or
147 * an OutputStream for binary output. The standard Emitters all use a Writer, so
148 * this returns true; but a subclass can override this if it wants to use an OutputStream
149 *
150 * @return true if a Writer is needed, as distinct from an OutputStream
151 */
152
153 public boolean usesWriter() {
154 return true;
155 }
156
157 /**
158 * Set the output destination as a character stream
159 *
160 * @param writer the Writer to use as an output destination
161 * @throws net.sf.saxon.trans.XPathException if an error occurs
162 */
163
164 public void setWriter(Writer writer) throws XPathException {
165 this.writer = writer;
166
167 // If the writer uses a known encoding, change the encoding in the XML declaration
168 // to match. Any encoding actually specified in xsl:output is ignored, because encoding
169 // is being done by the user-supplied Writer, and not by Saxon itself.
170
171 if (writer instanceof OutputStreamWriter && outputProperties != null) {
172 String enc = ((OutputStreamWriter) writer).getEncoding();
173 outputProperties.setProperty(OutputKeys.ENCODING, enc);
174 characterSet = config.getCharacterSetFactory().getCharacterSet(outputProperties);
175 allCharactersEncodable = characterSet instanceof UTF8CharacterSet ||
176 characterSet instanceof UTF16CharacterSet;
177 }
178 }
179
180 /**
181 * Get the output writer
182 *
183 * @return the Writer being used as an output destination, if any
184 */
185
186 public Writer getWriter() {
187 return writer;
188 }
189
190 /**
191 * Set the output destination as a byte stream.
192 * <p>Note that if a specific encoding (other than the default, UTF-8) is required, then
193 * it must be defined in the output properties</p>
194 *
195 * @param stream the OutputStream being used as an output destination
196 * @throws net.sf.saxon.trans.XPathException if an error occurs
197 */
198
199 private Writer makeWriterFromOutputStream(OutputStream stream) throws XPathException {
200 outputStream = stream;
201
202 // If the user supplied an OutputStream, but the Emitter is written to
203 // use a Writer (this is the most common case), then we create a Writer
204 // to wrap the supplied OutputStream; the complications are to ensure that
205 // the character encoding is correct.
206
207 //if (usesWriter()) {
208
209
210 //while (true) {
211 try {
212 String javaEncoding = encoding;
213 if (encoding.equalsIgnoreCase("iso-646") || encoding.equalsIgnoreCase("iso646")) {
214 javaEncoding = "US-ASCII";
215 }
216 if (encoding.equalsIgnoreCase("UTF8")) {
217 writer = new UTF8Writer(outputStream);
218 } else {
219 writer = new BufferedWriter(
220 new OutputStreamWriter(
221 outputStream, javaEncoding));
222 }
223 return writer;
224 //break;
225 } catch (Exception err) {
226 if (encoding.equalsIgnoreCase("UTF8")) {
227 throw new XPathException("Failed to create a UTF8 output writer");
228 }
229 throw new XPathException("Encoding " + encoding + " is not supported", "SESU0007");
230 // XPathException de = new XPathException("Encoding " + encoding + " is not supported: using UTF8");
231 // de.setErrorCode("SESU0007");
232 // getPipelineConfiguration().getErrorListener().error(de);
233 // encoding = "UTF8";
234 // characterSet = UTF8CharacterSet.getInstance();
235 // allCharactersEncodable = true;
236 // outputProperties.setProperty(OutputKeys.ENCODING, "UTF-8");
237 }
238 //}
239 //}
240
241 }
242
243 /**
244 * Get the output stream
245 *
246 * @return the OutputStream being used as an output destination, if any
247 */
248
249 public OutputStream getOutputStream() {
250 return outputStream;
251 }
252
253 /**
254 * Get the character set
255 */
256
257 public CharacterSet getCharacterSet() {
258 return characterSet;
259 }
260
261 }
262