Debian Codegraph @

net/sf/saxon/lib/StandardUnparsedTextResolver.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.lib;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.resource.BinaryResource;
12 import net.sf.saxon.resource.DataURIScheme;
13 import net.sf.saxon.resource.UnparsedTextResource;
14 import net.sf.saxon.trans.XPathException;
15 import net.sf.saxon.tree.util.FastStringBuffer;
16
17 import java.io.*;
18 import java.net.MalformedURLException;
19 import java.net.URI;
20 import java.net.URL;
21 import java.net.URLConnection;
22 import java.nio.charset.*;
23 import java.util.zip.GZIPInputStream;
24
25 /**
26 * Default implementation of the UnparsedTextURIResolver, used if no other implementation
27 * is nominated to the Configuration. This implementation
28 * * handles anything that the java URL class will handle, plus the <code>classpath</code>
29 * * URI scheme defined in the Spring framework, and the <code>data</code> URI scheme defined in
30 * * RFC 2397.
31 */
32
33 public class StandardUnparsedTextResolver implements UnparsedTextURIResolver {
34
35 private boolean debug = false;
36
37 /**
38 * Set debugging on or off. In debugging mode, information is written to System.err
39 * to trace the process of deducing an encoding.
40 *
41 * @param debug set to true to enable debugging
42 */
43
44 public void setDebugging(boolean debug) {
45 this.debug = debug;
46 }
47
48 /**
49 * Resolve the URI passed to the XSLT unparsed-text() function, after resolving
50 * against the base URI.
51 *
52 * @param absoluteURI the absolute URI obtained by resolving the supplied
53 * URI against the base URI
54 * @param encoding the encoding requested in the call of unparsed-text(), if any. Otherwise null.
55 * @param config The configuration. Provided in case the URI resolver
56 * needs it.
57 * @return a Reader, which Saxon will use to read the unparsed text. After the text has been read,
58 * the close() method of the Reader will be called.
59 * @throws net.sf.saxon.trans.XPathException
60 * if any failure occurs
61 * @since 8.9
62 */
63
64 public Reader resolve(URI absoluteURI, String encoding, Configuration config) throws XPathException {
65 URL absoluteURL;
66 Logger err = config.getLogger();
67 if (debug) {
68 err.info("unparsed-text(): processing " + absoluteURI);
69 err.info("unparsed-text(): requested encoding = " + encoding);
70 }
71 if (!absoluteURI.isAbsolute()) {
72 throw new XPathException("Resolved URI supplied to unparsed-text() is not absolute: " + absoluteURI.toString(),
73 "FOUT1170");
74 }
75 InputStream inputStream = null;
76 String contentEncoding;
77 boolean isXmlMediaType = false;
78 if (absoluteURI.getScheme().equals("data")) {
79 Resource resource;
80 try {
81 resource = DataURIScheme.decode(absoluteURI);
82 } catch (IllegalArgumentException e) {
83 throw new XPathException("Invalid URI in 'data' scheme: " + e.getMessage(), "FOUT1170");
84 }
85 if (resource instanceof BinaryResource) {
86 byte[] octets = ((BinaryResource) resource).getData();
87 inputStream = new ByteArrayInputStream(octets);
88 contentEncoding = "utf-8";
89
90 } else {
91 assert resource instanceof UnparsedTextResource;
92 inputStream = ((UnparsedTextResource) resource).getInputStream();
93 contentEncoding = ((UnparsedTextResource) resource).getEncoding();
94 }
95 if (encoding == null) {
96 encoding = contentEncoding;
97 }
98 String mediaType = resource.getContentType();
99 isXmlMediaType = (mediaType.startsWith("application/") || mediaType.startsWith("text/")) &&
100 (mediaType.endsWith("/xml") || mediaType.endsWith("+xml"));
101 } else if (absoluteURI.getScheme().equals("classpath")) {
102 InputStream is = config.getDynamicLoader().getResourceAsStream(absoluteURI.toString().substring(10));
103 if (is != null) {
104 try {
105 if (encoding == null) {
106 encoding = "UTF-8";
107 }
108 return new InputStreamReader(is, encoding);
109 } catch (UnsupportedEncodingException e) {
110 throw new AssertionError(e);
111 }
112 }
113 } else {
114 try {
115 absoluteURL = absoluteURI.toURL();
116 } catch (MalformedURLException mue) {
117 XPathException e = new XPathException("Cannot convert absolute URI to URL", mue);
118 e.setErrorCode("FOUT1170");
119 throw e;
120 }
121 try {
122
123 URLConnection connection = absoluteURL.openConnection();
124 connection.setRequestProperty("Accept-Encoding", "gzip");
125 try {
126 connection.connect();
127 } catch (IOException ioe) {
128 if (debug) {
129 err.error("unparsed-text(): connection failure. " + ioe.getMessage());
130 }
131 XPathException xpe = new XPathException("Failed to read input file", ioe);
132 xpe.setErrorCode("FOUT1170");
133 throw xpe;
134 }
135
136 inputStream = connection.getInputStream();
137 contentEncoding = connection.getContentEncoding();
138
139 if ("gzip".equals(contentEncoding)) {
140 inputStream = new GZIPInputStream(inputStream);
141 }
142 if (debug) {
143 err.info("unparsed-text(): established connection " +
144 ("gzip".equals(contentEncoding) ? " (zipped)" : ""));
145 }
146
147
148 if (!inputStream.markSupported()) {
149 inputStream = new BufferedInputStream(inputStream);
150 }
151
152 // Get any external (HTTP) encoding label.
153 isXmlMediaType = false;
154
155 // The file:// URL scheme gives no useful information...
156 if (!"file".equals(connection.getURL().getProtocol())) {
157
158 // Use the contentType from the HTTP header if available
159 String contentType = connection.getContentType();
160 if (debug) {
161 err.info("unparsed-text(): content type = " + contentType);
162 }
163 if (contentType != null) {
164 String mediaType;
165 int pos = contentType.indexOf(';');
166 if (pos >= 0) {
167 mediaType = contentType.substring(0, pos);
168 } else {
169 mediaType = contentType;
170 }
171 mediaType = mediaType.trim();
172 if (debug) {
173 err.info("unparsed-text(): media type = " + mediaType);
174 }
175 isXmlMediaType = (mediaType.startsWith("application/") || mediaType.startsWith("text/")) &&
176 (mediaType.endsWith("/xml") || mediaType.endsWith("+xml"));
177
178 String charset = "";
179 pos = contentType.toLowerCase().indexOf("charset");
180 if (pos >= 0) {
181 pos = contentType.indexOf('=', pos + 7);
182 if (pos >= 0) {
183 charset = contentType.substring(pos + 1);
184 }
185 if ((pos = charset.indexOf(';')) > 0) {
186 charset = charset.substring(0, pos);
187 }
188
189 // attributes can have comment fields (RFC 822)
190 if ((pos = charset.indexOf('(')) > 0) {
191 charset = charset.substring(0, pos);
192 }
193 // ... and values may be quoted
194 if ((pos = charset.indexOf('"')) > 0) {
195 charset = charset.substring(pos + 1,
196 charset.indexOf('"', pos + 2));
197 }
198 if (debug) {
199 err.info("unparsed-text(): charset = " + charset.trim());
200 }
201 encoding = charset.trim();
202 }
203 }
204 }
205
206
207 try {
208 if (encoding == null || isXmlMediaType) {
209 encoding = inferStreamEncoding(inputStream, debug ? err : null);
210 if (debug) {
211 err.info("unparsed-text(): inferred encoding = " + encoding);
212 }
213 }
214 } catch (IOException e) {
215 encoding = "UTF-8";
216 }
217
218 } catch (IOException ioe) {
219 throw new XPathException(ioe.getMessage(), "FOUT1170");
220 } catch (IllegalCharsetNameException icne) {
221 throw new XPathException("Invalid encoding name: " + encoding, "FOUT1190");
222 } catch (UnsupportedCharsetException uce) {
223 throw new XPathException("Invalid encoding name: " + encoding, "FOUT1190");
224 }
225
226 }
227
228 // The following is necessary to ensure that encoding errors are not recovered.
229 Charset charset = Charset.forName(encoding);
230 CharsetDecoder decoder = charset.newDecoder();
231 decoder = decoder.onMalformedInput(CodingErrorAction.REPORT);
232 decoder = decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
233 return new BufferedReader(new InputStreamReader(inputStream, decoder));
234
235 }
236
237
238 /**
239 * Try to detect the encoding from the start of the input stream
240 *
241 * @param is the input stream
242 * @param err logger to be used for diagnostics, or null
243 * @return the inferred encoding, defaulting to UTF-8
244 * @throws IOException if it isn't possible to mark the current position on the input stream and read ahead
245 */
246
247 public static String inferStreamEncoding(InputStream is, Logger err) throws IOException {
248 is.mark(100);
249 byte[] start = new byte[100];
250 int read = is.read(start, 0, 100);
251 is.reset();
252 return inferEncoding(start, read, err);
253 }
254
255 /**
256 * Infer the encoding of a file by reading the first few bytes of the file
257 *
258 * @param start the first few bytes of the file
259 * @param read the number of bytes that have been read
260 * @param logger Logger to receive diagnostic messages, or null
261 * @return the inferred encoding
262 */
263
264 private static String inferEncoding(byte[] start, int read, Logger logger) {
265 boolean debug = logger != null;
266 if (read >= 2) {
267 if (ch(start[0]) == 0xFE && ch(start[1]) == 0xFF) {
268 if (debug) {
269 logger.info("unparsed-text(): found UTF-16 byte order mark");
270 }
271 return "UTF-16";
272 } else if (ch(start[0]) == 0xFF && ch(start[1]) == 0xFE) {
273 if (debug) {
274 logger.info("unparsed-text(): found UTF-16LE byte order mark");
275 }
276 return "UTF-16LE";
277 }
278 }
279 if (read >= 3) {
280 if (ch(start[0]) == 0xEF && ch(start[1]) == 0xBB && ch(start[2]) == 0xBF) {
281 if (debug) {
282 logger.info("unparsed-text(): found UTF-8 byte order mark");
283 }
284 return "UTF-8";
285 }
286 }
287 if (read >= 4) {
288 if (ch(start[0]) == '<' && ch(start[1]) == '?' &&
289 ch(start[2]) == 'x' && ch(start[3]) == 'm' && ch(start[4]) == 'l') {
290 if (debug) {
291 logger.info("unparsed-text(): found XML declaration");
292 }
293 FastStringBuffer sb = new FastStringBuffer(read);
294 for (int b = 0; b < read; b++) {
295 sb.append((char) start[b]);
296 }
297 String p = sb.toString();
298 int v = p.indexOf("encoding");
299 if (v >= 0) {
300 v += 8;
301 while (v < p.length() && " \n\r\t=\"'".indexOf(p.charAt(v)) >= 0) {
302 v++;
303 }
304 sb.setLength(0);
305 while (v < p.length() && p.charAt(v) != '"' && p.charAt(v) != '\'') {
306 sb.append(p.charAt(v++));
307 }
308 if (debug) {
309 logger.info("unparsed-text(): encoding in XML declaration = " + sb.toString());
310 }
311 return sb.toString();
312 }
313 if (debug) {
314 logger.info("unparsed-text(): no encoding found in XML declaration");
315 }
316 }
317 } else if (read > 0 && start[0] == 0 && start[2] == 0 && start[4] == 0 && start[6] == 0) {
318 if (debug) {
319 logger.info("unparsed-text(): even-numbered bytes are zero, inferring UTF-16");
320 }
321 return "UTF-16";
322 } else if (read > 1 && start[1] == 0 && start[3] == 0 && start[5] == 0 && start[7] == 0) {
323 if (debug) {
324 logger.info("unparsed-text(): odd-numbered bytes are zero, inferring UTF-16LE");
325 }
326 return "UTF-16LE";
327 }
328 // If all else fails, assume UTF-8
329 if (debug) {
330 logger.info("unparsed-text(): assuming fallback encoding (UTF-8)");
331 }
332 return "UTF-8";
333 }
334
335 private static int ch(byte b) {
336 return (int)b & 0xff;
337 }
338 }
339