Debian Codegraph @

net/sf/saxon/resource/AbstractResourceCollection.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.resource;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.Controller;
12 import net.sf.saxon.expr.XPathContext;
13 import net.sf.saxon.functions.URIQueryParameters;
14 import net.sf.saxon.lib.*;
15 import net.sf.saxon.om.SpaceStrippingRule;
16 import net.sf.saxon.trans.Maker;
17 import net.sf.saxon.trans.XPathException;
18 import org.xml.sax.XMLReader;
19
20 import javax.xml.transform.TransformerException;
21 import java.io.*;
22 import java.net.*;
23
24 /**
25 * AbstractCollection is an abstract superclass for the various implementations
26 * of ResourceCollection within Saxon. It provides common services such as
27 * mapping of file extensions to MIME types, and mapping of MIME types to
28 * resource factories.
29 */
30 public abstract class AbstractResourceCollection implements ResourceCollection {
31
32 protected Configuration config;
33 protected String collectionURI;
34 protected URIQueryParameters params = null;
35
36 public AbstractResourceCollection(Configuration config) {
37 this.config = config;
38 }
39
40 public String getCollectionURI() {
41 return collectionURI;
42 }
43
44 /**
45 * Ask whether the collection is stable. This method should only be called after
46 * calling {@link #getResources(XPathContext)} or {@link #getResourceURIs(XPathContext)}
47 *
48 * @param context the XPath evaluation context.
49 * @return true if the collection is defined to be stable, that is, if a subsequent call
50 * on collection() with the same URI is guaranteed to return the same result. The method returns
51 * true if the query parameter stable=yes is present in the URI, or if the configuration property
52 * {@link FeatureKeys#STABLE_COLLECTION_URI} is set.
53 */
54
55 public boolean isStable(XPathContext context) {
56 if (params == null) {
57 return false;
58 }
59 Boolean stable = params.getStable();
60 if (stable == null) {
61 return context.getConfiguration().getBooleanProperty(Feature.STABLE_COLLECTION_URI);
62 } else {
63 return stable;
64 }
65 }
66
67 /**
68 * Associate a media type with a resource factory.
69 * Since 9.7.0.6 this registers the content type with the configuration, making the register
70 * of content types more accessible to applications.
71 * @param contentType a media type or MIME type, for example application/xsd+xml
72 * @param factory a ResourceFactory used to parse (or otherwise process) resources of that type
73 */
74
75 public void registerContentType(String contentType, ResourceFactory factory) {
76 config.registerMediaType(contentType, factory);
77 }
78
79 protected ParseOptions optionsFromQueryParameters(URIQueryParameters params, XPathContext context) {
80 ParseOptions options = new ParseOptions(context.getConfiguration().getParseOptions());
81
82 if (params != null) {
83 Integer v = params.getValidationMode();
84 if (v != null) {
85 options.setSchemaValidationMode(v);
86 }
87
88 Boolean xInclude = params.getXInclude();
89 if (xInclude != null) {
90 options.setXIncludeAware(xInclude);
91 }
92
93 SpaceStrippingRule stripSpace = params.getSpaceStrippingRule();
94 if (stripSpace != null) {
95 options.setSpaceStrippingRule(stripSpace);
96 }
97
98 Maker<XMLReader> p = params.getXMLReaderMaker();
99 if (p != null) {
100 options.setXMLReaderMaker(p);
101 }
102
103
104 // If the URI requested suppression of errors, or that errors should be treated
105 // as warnings, we set up a special ErrorListener to achieve this
106
107 int onError = URIQueryParameters.ON_ERROR_FAIL;
108 if (params.getOnError() != null) {
109 onError = params.getOnError();
110 }
111 final Controller controller = context.getController();
112 // final PipelineConfiguration oldPipe = context.getConfiguration().makePipelineConfiguration();
113 // oldPipe.setController(context.getController());
114 // final PipelineConfiguration newPipe = new PipelineConfiguration(oldPipe);
115 final UnfailingErrorListener oldErrorListener =
116 controller == null ? new StandardErrorListener() : controller.getErrorListener();
117
118 setupErrorHandlingForCollection(options, onError, oldErrorListener);
119 }
120 return options;
121 }
122
123 public static void setupErrorHandlingForCollection(ParseOptions options, int onError, UnfailingErrorListener oldErrorListener) {
124 if (onError == URIQueryParameters.ON_ERROR_IGNORE) {
125 options.setErrorListener(new UnfailingErrorListener() {
126 public void warning(TransformerException exception) {
127 }
128
129 public void error(TransformerException exception) {
130 }
131
132 public void fatalError(TransformerException exception) {
133 }
134 });
135 } else if (onError == URIQueryParameters.ON_ERROR_WARNING) {
136 options.setErrorListener(new UnfailingErrorListener() {
137 public void warning(TransformerException exception) {
138 oldErrorListener.warning(exception);
139 }
140
141 public void error(TransformerException exception) {
142 oldErrorListener.warning(exception);
143 XPathException supp = new XPathException("The document will be excluded from the collection");
144 supp.setLocator(exception.getLocator());
145 oldErrorListener.warning(supp);
146 }
147
148 public void fatalError(TransformerException exception) {
149 error(exception);
150 }
151 });
152 }
153 }
154
155 public static class InputDetails {
156 public InputStream inputStream;
157 public String contentType;
158 public String encoding;
159 public ParseOptions parseOptions;
160 public int onError = URIQueryParameters.ON_ERROR_FAIL;
161 }
162
163 protected InputDetails getInputDetails(String resourceURI) throws XPathException {
164
165 InputDetails inputDetails = new InputDetails();
166 try {
167
168 URI uri = new URI(resourceURI);
169
170 if ("file".equals(uri.getScheme())) {
171 File file = new File(uri);
172 inputDetails.inputStream = new BufferedInputStream(new FileInputStream(file));
173 } else {
174 URL url = uri.toURL();
175 URLConnection connection = url.openConnection();
176 inputDetails.inputStream = connection.getInputStream();
177 inputDetails.contentType = connection.getContentType();
178 inputDetails.encoding = connection.getContentEncoding();
179 for (String param : inputDetails.contentType.replace(" ", "").split(";")) {
180 if (param.startsWith("charset=")) {
181 inputDetails.encoding = param.split("=", 2)[1];
182 } else {
183 inputDetails.contentType = param;
184 }
185 }
186
187 }
188 } catch (URISyntaxException | IOException e) {
189 throw new XPathException(e);
190 }
191 if (inputDetails.contentType == null || config.getResourceFactoryForMediaType(inputDetails.contentType) == null) {
192 inputDetails.contentType = guessContentType(resourceURI, inputDetails.inputStream);
193 }
194 if (params != null && params.getOnError() != null) {
195 inputDetails.onError = params.getOnError();
196 }
197 return inputDetails;
198
199 }
200
201 /**
202 * Guess the content type of a resource from its name and/or its content
203 *
204 * @param resourceURI the resource URI
205 * @param stream the content of the resource. The stream must be positioned at the start.
206 * The method looks ahead in this stream
207 * but resets the current position on exit.
208 * @return the media type, or null.
209 */
210
211 protected String guessContentType(String resourceURI, InputStream stream) {
212 String contentTypeFromStream = null;
213 try {
214 contentTypeFromStream = URLConnection.guessContentTypeFromStream(stream);
215 } catch (IOException err) {
216 // ignore the error
217 }
218 String contentTypeFromName = URLConnection.guessContentTypeFromName(resourceURI);
219 String extension = null;
220 if (contentTypeFromName == null) {
221 extension = getFileExtension(resourceURI);
222 if (extension != null) {
223 contentTypeFromName = config.getMediaTypeForFileExtension(extension);
224 }
225 }
226 if (contentTypeFromName == null) {
227 return contentTypeFromStream;
228 } else {
229 if (contentTypeFromStream == null) {
230 return contentTypeFromName;
231 } else if (contentTypeFromStream.equals(contentTypeFromName)) {
232 return contentTypeFromStream;
233 } else {
234 // we've got two candidates: which is more reliable?
235 // At this stage, it's pure pragmatism
236 if ("xsl".equals(extension) || "xslt".equals(extension) || "xml".equals(extension)) {
237 return contentTypeFromName;
238 } else {
239 return contentTypeFromStream;
240 }
241 }
242 }
243 }
244
245 /**
246 * Get the file extension from a file name or URI
247 *
248 * @param name the file name or URI
249 * @return the part after the last dot, or null if there is no dot after the last slash or backslash.
250 */
251
252 private String getFileExtension(String name) {
253 int i = name.lastIndexOf('.');
254 int p = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\'));
255 if (i > p && i + 1 < name.length()) {
256 return name.substring(i + 1);
257 }
258 return null;
259 }
260
261 /**
262 * Internal method to make a resource for a single entry in the ZIP or JAR file. This involves
263 * making decisions about the type of resource. This method can be overridden in a user-defined
264 * subclass.
265 *
266 * @param config The Saxon configuration
267 * @param details Details of the input, including the input stream delivering the content of the resource.
268 * The method is expected to
269 * consume this input stream; the caller will close it on return.
270 * @param resourceURI the URI of the entry within the ZIP or JAR file; this will by default be
271 * in the form collectionURI!path
272 * @return a newly created Resource representing the content of this entry in the ZIP or JAR file
273 */
274
275 public Resource makeResource(Configuration config, InputDetails details, String resourceURI) throws XPathException {
276
277 ResourceFactory factory = null;
278 String contentType = details.contentType;
279 if (contentType != null) {
280 factory = config.getResourceFactoryForMediaType(contentType);
281 }
282 if (factory == null) {
283 factory = BinaryResource.FACTORY;
284 }
285
286 return factory.makeResource(config, resourceURI, contentType, details);
287 }
288
289 public Resource makeTypedResource(Configuration config, Resource basicResource) throws XPathException {
290
291 String mediaType = basicResource.getContentType();
292 ResourceFactory factory = config.getResourceFactoryForMediaType(mediaType);
293 if (factory == null) {
294 return basicResource;
295 }
296 if (basicResource instanceof BinaryResource) {
297 InputDetails details = new InputDetails();
298 details.inputStream = new ByteArrayInputStream(((BinaryResource)basicResource).getData());
299 details.contentType = mediaType;
300 return factory.makeResource(config, basicResource.getResourceURI(), mediaType, details);
301 } else if (basicResource instanceof UnparsedTextResource) {
302 InputDetails details = new InputDetails();
303 details.inputStream = ((UnparsedTextResource) basicResource).getInputStream();
304 details.contentType = mediaType;
305 return factory.makeResource(config, basicResource.getResourceURI(), mediaType, details);
306 } else {
307 return basicResource;
308 }
309
310 }
311
312 /**
313 * Default method to make a resource, given a resource URI
314 * @param resourceURI the resource URI
315 * @return the corresponding resource
316 */
317
318 public Resource makeResource(Configuration config, String resourceURI) throws XPathException {
319 InputDetails details = getInputDetails(resourceURI);
320 return makeResource(config, details, resourceURI);
321 }
322
323 /**
324 * Supply information about the whitespace stripping rules that apply to this collection.
325 * This method will only be called when the collection() function is invoked from XSLT.
326 *
327 * @param rules the space-stripping rules that apply to this collection, derived from
328 * the xsl:strip-space and xsl:preserve-space declarations in the stylesheet
329 * package containing the call to the collection() function.
330 * @return true if the collection finder intends to take responsibility for whitespace
331 * stripping according to these rules; false if it wishes Saxon itself to post-process
332 * any returned XML documents to strip whitespace. Returning true may either indicate
333 * that the collection finder will strip whitespace before returning a document, or it
334 * may indicate that it does not wish the space stripping rules to be applied. The
335 * default (returned by this method if not overridden) is false.
336 */
337
338 public boolean stripWhitespace(SpaceStrippingRule rules) {
339 return false;
340 }
341
342
343 }
344