Debian Codegraph @

net/sf/saxon/functions/UnparsedTextFunction.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.functions;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.Expression;
12 import net.sf.saxon.expr.StaticProperty;
13 import net.sf.saxon.expr.XPathContext;
14 import net.sf.saxon.lib.Feature;
15 import net.sf.saxon.regex.LatinString;
16 import net.sf.saxon.serialize.charcode.UTF16CharacterSet;
17 import net.sf.saxon.trans.Err;
18 import net.sf.saxon.trans.XPathException;
19 import net.sf.saxon.tree.util.FastStringBuffer;
20
21 import java.util.function.IntPredicate;
22
23 import java.io.IOException;
24 import java.io.Reader;
25 import java.net.URI;
26 import java.nio.charset.CharacterCodingException;
27 import java.nio.charset.MalformedInputException;
28 import java.nio.charset.UnmappableCharacterException;
29
30
31 /**
32 * Abstract superclass containing common code supporting the functions
33 * unparsed-text(), unparsed-text-lines(), and unparsed-text-available()
34 */
35
36 public abstract class UnparsedTextFunction extends SystemFunction {
37
38 public int getSpecialProperties(Expression[] arguments) {
39 int p = super.getSpecialProperties(arguments);
40 if (getRetainedStaticContext().getConfiguration().getBooleanProperty(Feature.STABLE_UNPARSED_TEXT)) {
41 return p;
42 } else {
43 return p & ~StaticProperty.NO_NODES_NEWLY_CREATED;
44 // Pretend the function is creative to prevent the result going into a global variable,
45 // which takes excessive memory. Unless we're caching anyway, for stability reasons.
46 }
47 }
48
49
50 /**
51 * Supporting routine to load one external file given a URI (href) and a baseURI
52 * @param absoluteURI the absolutized URI
53 * @param encoding the character encoding
54 * @param context the XPath dynamic context
55 * @return the content of the file
56 * @throws XPathException if the file cannot be read
57 */
58
59 public static CharSequence readFile(URI absoluteURI, String encoding, XPathContext context)
60 throws XPathException {
61
62 final Configuration config = context.getConfiguration();
63 IntPredicate checker = config.getValidCharacterChecker();
64
65 // Use the URI machinery to validate and resolve the URIs
66
67 Reader reader;
68 try {
69 reader = context.getController().getUnparsedTextURIResolver().resolve(absoluteURI, encoding, config);
70 } catch (XPathException err) {
71 err.maybeSetErrorCode("FOUT1170");
72 throw err;
73 }
74 try {
75 return readFile(checker, reader);
76 } catch (java.io.UnsupportedEncodingException encErr) {
77 XPathException e = new XPathException("Unknown encoding " + Err.wrap(encoding), encErr);
78 e.setErrorCode("FOUT1190");
79 throw e;
80 } catch (java.io.IOException ioErr) {
81 // System.err.println("ProxyHost: " + System.getProperty("http.proxyHost"));
82 // System.err.println("ProxyPort: " + System.getProperty("http.proxyPort"));
83 throw handleIOError(absoluteURI, ioErr, context);
84 }
85 }
86
87 public static URI getAbsoluteURI(String href, String baseURI, XPathContext context) throws XPathException {
88 URI absoluteURI;
89 try {
90 absoluteURI = ResolveURI.makeAbsolute(href, baseURI);
91 } catch (java.net.URISyntaxException err) {
92 XPathException e = new XPathException(err.getReason() + ": " + err.getInput(), err);
93 e.setErrorCode("FOUT1170");
94 throw e;
95 }
96
97 if (absoluteURI.getFragment() != null) {
98 XPathException e = new XPathException("URI for unparsed-text() must not contain a fragment identifier");
99 e.setErrorCode("FOUT1170");
100 throw e;
101 }
102
103 // The URL dereferencing classes throw all kinds of strange exceptions if given
104 // ill-formed sequences of %hh escape characters. So we do a sanity check that the
105 // escaping is well-formed according to UTF-8 rules
106
107 EncodeForUri.checkPercentEncoding(absoluteURI.toString());
108 return absoluteURI;
109 }
110
111 public static XPathException handleIOError(URI absoluteURI, IOException ioErr, XPathContext context) {
112 String message = "Failed to read input file";
113 if (absoluteURI != null && !ioErr.getMessage().equals(absoluteURI.toString())) {
114 message += ' ' + absoluteURI.toString();
115 }
116 message += " (" + ioErr.getClass().getName() + ')';
117 XPathException e = new XPathException(message, ioErr);
118 String errorCode = getErrorCode(ioErr);
119 e.setErrorCode(errorCode);
120 return e;
121 }
122
123 private static String getErrorCode(IOException ioErr) {
124 // FOUT1200 should be used when the encoding was inferred, FOUT1190 when it was explicit. We rely on the
125 // caller to change FOUT1200 to FOUT1190 when necessary
126 if (ioErr instanceof MalformedInputException) {
127 return "FOUT1200";
128 } else if (ioErr instanceof UnmappableCharacterException) {
129 return "FOUT1200";
130 } else if (ioErr instanceof CharacterCodingException) {
131 return "FOUT1200";
132 } else {
133 return "FOUT1170";
134 }
135 }
136
137 /**
138 * Read the contents of an unparsed text file
139 *
140 * @param checker predicate for checking whether characters are valid XML characters
141 * @param reader Reader to be used for reading the file
142 * @return a CharSequence representing the contents of the file
143 * @throws IOException if a failure occurs reading the file
144 * @throws XPathException if the file contains illegal characters
145 */
146
147 public static CharSequence readFile(IntPredicate checker, Reader reader) throws IOException, XPathException {
148 FastStringBuffer sb = new FastStringBuffer(2048);
149 char[] buffer = new char[2048];
150 boolean first = true;
151 int actual;
152 int line = 1;
153 int column = 1;
154 boolean latin = true;
155 while (true) {
156 actual = reader.read(buffer, 0, buffer.length);
157 if (actual < 0) {
158 break;
159 }
160 for (int c = 0; c < actual; ) {
161 int ch32 = buffer[c++];
162 if (ch32 == '\n') {
163 line++;
164 column = 0;
165 }
166 column++;
167 if (ch32 > 255) {
168 latin = false;
169 if (UTF16CharacterSet.isHighSurrogate(ch32)) {
170 if (c == actual) { // bug 3785, test case fn-unparsed-text-055
171 // We've got a high surrogate right at the end of the buffer.
172 // The path of least resistance is to extend the buffer.
173 char[] buffer2 = new char[2048];
174 int actual2 = reader.read(buffer2, 0, 2048);
175 char[] buffer3 = new char[actual + actual2];
176 System.arraycopy(buffer, 0, buffer3, 0, actual);
177 System.arraycopy(buffer2, 0, buffer3, actual, actual2);
178 buffer = buffer3;
179 actual = actual + actual2;
180 }
181 char low = buffer[c++];
182 ch32 = UTF16CharacterSet.combinePair((char) ch32, low);
183 }
184 }
185 if (!checker.test(ch32)) {
186 XPathException err = new XPathException("The text file contains a character that is illegal in XML (line=" +
187 line + " column=" + column + " value=hex " + Integer.toHexString(ch32) + ')');
188 err.setErrorCode("FOUT1190");
189 throw err;
190 }
191 }
192 if (first) {
193 first = false;
194 if (buffer[0] == '\ufeff') {
195 // don't include the BOM in the result
196 sb.append(buffer, 1, actual - 1);
197 } else {
198 sb.append(buffer, 0, actual);
199 }
200 } else {
201 sb.append(buffer, 0, actual);
202 }
203 }
204 reader.close();
205 if (latin) {
206 return new LatinString(sb);
207 } else {
208 return sb.condense();
209 }
210 }
211
212
213 }
214