Debian Codegraph @

net/sf/saxon/query/QueryReader.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.query;
9
10 import net.sf.saxon.functions.UnparsedTextFunction;
11 import net.sf.saxon.trans.Err;
12 import net.sf.saxon.trans.XPathException;
13 import net.sf.saxon.tree.util.FastStringBuffer;
14 import net.sf.saxon.value.Whitespace;
15
16 import javax.xml.transform.stream.StreamSource;
17 import java.io.*;
18 import java.util.function.IntPredicate;
19
20 /**
21 * This class contains static methods used to read a query as a byte stream, infer the encoding if
22 * necessary, and return the text of the query as a string; also methods to import functions and variables
23 * from one module into another, and check their consistency.
24 */
25 public class QueryReader {
26
27 /**
28 * The class is never instantiated
29 */
30 private QueryReader() {
31 }
32
33 /**
34 * Read a query module given a StreamSource
35 *
36 * @param ss the supplied StreamSource. This must contain a non-null systemID which defines the base
37 * URI of the query module, and either an InputStream or a Reader containing the query text. In the
38 * case of an InputStream the method attempts to infer the encoding; in the case of a Reader, this has
39 * already been done, and the encoding specified within the query itself is ignored.
40 * <p>The method reads from the InputStream or Reader contained in the StreamSource up to the end
41 * of file unless a fatal error occurs. It does not close the InputStream or Reader; this is the caller's
42 * responsibility.</p>
43 * @param charChecker this checks XML characters against either the XML 1.0 or XML 1.1 rules
44 * @return the text of the query
45 */
46
47 public static String readSourceQuery(/*@NotNull*/ StreamSource ss, IntPredicate charChecker) throws XPathException {
48 CharSequence queryText;
49 if (ss.getInputStream() != null) {
50 InputStream is = ss.getInputStream();
51 if (!is.markSupported()) {
52 is = new BufferedInputStream(is);
53 }
54 String encoding = readEncoding(is);
55 queryText = readInputStream(is, encoding, charChecker);
56 } else if (ss.getReader() != null) {
57 queryText = readQueryFromReader(ss.getReader(), charChecker);
58 } else {
59 throw new XPathException("Module URI Resolver must supply either an InputStream or a Reader");
60 }
61 return queryText.toString();
62 }
63
64 /**
65 * Read an input stream non-destructively to determine the encoding from the Query Prolog
66 *
67 * @param is the input stream: this must satisfy the precondition is.markSupported() = true.
68 * @return the encoding to be used: defaults to UTF-8 if no encoding was specified explicitly
69 * in the query prolog
70 * @throws XPathException if the input stream cannot be read
71 */
72
73 public static String readEncoding(/*@NotNull*/ InputStream is) throws XPathException {
74 try {
75 if (!is.markSupported()) {
76 throw new IllegalArgumentException("InputStream must have markSupported() = true");
77 }
78 is.mark(100);
79 byte[] start = new byte[100];
80 int read = is.read(start, 0, 100);
81 if (read == -1) {
82 throw new XPathException("Query source file is empty");
83 }
84 is.reset();
85 return inferEncoding(start, read);
86 } catch (IOException e) {
87 throw new XPathException("Failed to read query source file", e);
88 }
89 }
90
91 /**
92 * Read a query from an InputStream. The method checks that all characters are valid XML
93 * characters, and also performs normalization of line endings.
94 *
95 * @param is the input stream
96 * @param encoding the encoding, or null if the encoding is unknown
97 * @param nameChecker the predicate to be used for checking characters
98 * @return the content of the InputStream as a string
99 */
100
101 public static String readInputStream(InputStream is, String encoding, IntPredicate nameChecker) throws XPathException {
102 if (encoding == null) {
103 if (!is.markSupported()) {
104 is = new BufferedInputStream(is);
105 }
106 encoding = readEncoding(is);
107 }
108 try {
109 Reader reader = new BufferedReader(new InputStreamReader(is, encoding));
110 return readQueryFromReader(reader, nameChecker);
111 } catch (UnsupportedEncodingException encErr) {
112 XPathException err = new XPathException("Unknown encoding " + Err.wrap(encoding), encErr);
113 err.setErrorCode("XQST0087");
114 throw err;
115 }
116 }
117
118 /**
119 * Read a query from a Reader. The method checks that all characters are valid XML
120 * characters.
121 *
122 * @param reader The Reader supplying the input
123 * @param charChecker used to check characters are valid XML characters
124 * @return the text of the query module, as a string
125 * @throws XPathException if the file cannot be read or contains illegal characters
126 */
127
128 private static String readQueryFromReader(Reader reader, IntPredicate charChecker) throws XPathException {
129 try {
130 CharSequence content = UnparsedTextFunction.readFile(charChecker, reader);
131 return content.toString();
132 } catch (XPathException err) {
133 err.setErrorCode("XPST0003");
134 err.setIsStaticError(true);
135 throw err;
136 } catch (IOException ioErr) {
137 throw new XPathException("Failed to read supplied query file", ioErr);
138 }
139 }
140
141 /**
142 * Attempt to infer the encoding of a file by reading its byte order mark and if necessary
143 * the encoding declaration in the query prolog
144 *
145 * @param start the bytes appearing at the start of the file
146 * @param read the number of bytes supplied
147 * @return the inferred encoding
148 * @throws XPathException if, for example, an explicit encoding is specified but it is unsupported
149 */
150
151 private static String inferEncoding(byte[] start, int read) throws XPathException {
152 // Debugging code
153 // StringBuffer sb = new StringBuffer(read*5);
154 // for (int i=0; i<read; i++) sb.append(Integer.toHexString(start[i]&255) + ", ");
155 // System.err.println(sb);
156 // End of debugging code
157
158 if (read >= 2) {
159 if (ch(start[0]) == 0xFE && ch(start[1]) == 0xFF) {
160 return "UTF-16";
161 } else if (ch(start[0]) == 0xFF && ch(start[1]) == 0xFE) {
162 return "UTF-16LE";
163 }
164 }
165 if (read >= 3) {
166 if (ch(start[0]) == 0xEF && ch(start[1]) == 0xBB && ch(start[2]) == 0xBF) {
167 return "UTF-8";
168 }
169 }
170
171 // Try to handle a UTF-16 file with no BOM
172 if (read >= 8 && start[0] == 0 && start[2] == 0 && start[4] == 0 && start[6] == 0) {
173 return "UTF-16";
174 }
175 if (read >= 8 && start[1] == 0 && start[3] == 0 && start[5] == 0 && start[7] == 0) {
176 return "UTF-16LE";
177 }
178
179 // In all other cases, we assume an encoding that has ISO646 as a subset
180
181 // Note, we don't care about syntax errors here: they'll be reported later. We just need to
182 // establish the encoding.
183 int i = 0;
184 String tok = readToken(start, i, read);
185 if (Whitespace.trim(tok).equals("xquery")) {
186 i += tok.length();
187 } else {
188 return "UTF-8";
189 }
190 tok = readToken(start, i, read);
191 if (Whitespace.trim(tok).equals("encoding")) {
192 // "version" can be omitted in XQuery 3.0
193 i += tok.length();
194 } else {
195 if (Whitespace.trim(tok).equals("version")) {
196 i += tok.length();
197 } else {
198 return "UTF-8";
199 }
200 tok = readToken(start, i, read);
201 i += tok.length();
202 tok = readToken(start, i, read);
203 if (Whitespace.trim(tok).equals("encoding")) {
204 i += tok.length();
205 } else {
206 return "UTF-8";
207 }
208 }
209 tok = Whitespace.trim(readToken(start, i, read));
210 if (tok.startsWith("\"") && tok.endsWith("\"") && tok.length() > 2) {
211 return tok.substring(1, tok.length() - 1);
212 } else if (tok.startsWith("'") && tok.endsWith("'") && tok.length() > 2) {
213 return tok.substring(1, tok.length() - 1);
214 } else {
215 throw new XPathException("Unrecognized encoding " + Err.wrap(tok) + " in query prolog");
216 }
217
218 }
219
220 /**
221 * Simple tokenizer for use when reading the encoding declaration in the query prolog. A token
222 * is a sequence of characters delimited either by whitespace, or by single or double quotes; the
223 * quotes if present are returned as part of the token.
224 *
225 * @param in the character buffer
226 * @param i offset where to start reading
227 * @param len the length of buffer
228 * @return the next token
229 */
230
231 private static String readToken(byte[] in, int i, int len) {
232 int p = i;
233 while (p < len && " \n\r\t".indexOf(ch(in[p])) >= 0) {
234 p++;
235 }
236 if (ch(in[p]) == '"') {
237 p++;
238 while (p < len && ch(in[p]) != '"') {
239 p++;
240 }
241 } else if (ch(in[p]) == '\'') {
242 p++;
243 while (p < len && ch(in[p]) != '\'') {
244 p++;
245 }
246 } else {
247 while (p < len && " \n\r\t".indexOf(ch(in[p])) < 0) {
248 p++;
249 }
250 }
251 if (p >= len) {
252 return new String(in, i, len - i);
253 }
254 FastStringBuffer sb = new FastStringBuffer(p - i + 1);
255 for (int c = i; c <= p; c++) {
256 sb.append((char) ch(in[c]));
257 }
258 return sb.toString();
259 }
260
261 /**
262 * Convert a byte containing an ASCII character to that character
263 *
264 * @param b the input byte
265 * @return the ASCII character
266 */
267
268 private static int ch(byte b) {
269 return (int) b & 0xff;
270 }
271
272 }
273