Debian Codegraph @

net/sf/saxon/resource/DirectoryCollection.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.expr.XPathContext;
12 import net.sf.saxon.functions.URIQueryParameters;
13 import net.sf.saxon.lib.ParseOptions;
14 import net.sf.saxon.lib.Resource;
15 import net.sf.saxon.om.GroundedValue;
16 import net.sf.saxon.om.SpaceStrippingRule;
17 import net.sf.saxon.trans.XPathException;
18 import net.sf.saxon.tree.jiter.MappingJavaIterator;
19 import net.sf.saxon.value.BooleanValue;
20 import net.sf.saxon.value.DateTimeValue;
21 import net.sf.saxon.value.Int64Value;
22 import net.sf.saxon.value.StringValue;
23
24 import java.io.File;
25 import java.io.FilenameFilter;
26 import java.io.IOException;
27 import java.net.URI;
28 import java.net.URISyntaxException;
29 import java.util.*;
30
31 /**
32 * This class represents a resource collection containing all, or selected, files within a filestore
33 * directory.
34 */
35
36 public class DirectoryCollection extends AbstractResourceCollection {
37
38 private File dirFile;
39 private SpaceStrippingRule whitespaceRules;
40
41 /**
42 * Create a directory collection
43 * @param collectionURI the collection URI
44 * @param file the directory containing the files
45 * @param params query parameters supplied as part of the URI
46 */
47 public DirectoryCollection(Configuration config, String collectionURI,
48 File file, URIQueryParameters params) throws XPathException {
49 super(config);
50 if (collectionURI == null) {
51 throw new NullPointerException();
52 }
53 this.collectionURI = collectionURI;
54 dirFile = file;
55 if (params == null) {
56 this.params = new URIQueryParameters("", config);
57 } else {
58 this.params = params;
59 }
60 }
61
62 /**
63 * Supply information about the whitespace stripping rules that apply to this collection.
64 * This method will only be called when the collection() function is invoked from XSLT.
65 *
66 * @param rules the space-stripping rules that apply to this collection, derived from
67 * the xsl:strip-space and xsl:preserve-space declarations in the stylesheet
68 * package containing the call to the collection() function.
69 * @return true if the collection finder intends to take responsibility for whitespace
70 * stripping according to these rules; false if it wishes Saxon itself to post-process
71 * any returned XML documents to strip whitespace. Returning true may either indicate
72 * that the collection finder will strip whitespace before returning a document, or it
73 * may indicate that it does not wish the space stripping rules to be applied. The
74 * default (returned by this method if not overridden) is false.
75 */
76 @Override
77 public boolean stripWhitespace(SpaceStrippingRule rules) {
78 this.whitespaceRules = rules;
79 return true;
80 }
81
82 public Iterator<String> getResourceURIs(XPathContext context) {
83 return directoryContents(dirFile, params);
84 }
85
86 public Iterator<Resource> getResources(final XPathContext context) {
87 final ParseOptions options = optionsFromQueryParameters(params, context);
88 options.setSpaceStrippingRule(whitespaceRules);
89 Boolean metadataParam = params.getMetaData();
90 final boolean metadata = metadataParam != null && metadataParam;
91 Iterator<String> resourceURIs = getResourceURIs(context);
92
93 return new MappingJavaIterator<>(resourceURIs,
94 in -> {
95 try {
96 InputDetails details = getInputDetails(in);
97 details.parseOptions = options;
98 Resource resource = makeResource(context.getConfiguration(), details, in);
99 if (resource != null) {
100 if (metadata) {
101 return makeMetadataResource(resource, details);
102 } else {
103 return resource;
104 }
105 }
106 return null;
107 } catch (XPathException e) {
108 int onError = params.getOnError();
109 if (onError == URIQueryParameters.ON_ERROR_FAIL) {
110 return new FailedResource(in, e);
111 } else if (onError == URIQueryParameters.ON_ERROR_WARNING) {
112 context.getController().warning("collection(): failed to parse " + in + ": " + e.getMessage(), e.getErrorCodeLocalPart(), null);
113 return null;
114 } else {
115 return null;
116 }
117 }
118 });
119 }
120
121 /**
122 * Make a metadata resource: that is, a resource containing not only the content of a file within
123 * the directory structure, but properties of that file in the form of name/value pairs.
124 * @param resource a resource representing the content of the file
125 * @param details details about where the resource came from
126 * @return a MetadataResource, being an object containing both the original content resource,
127 * and an extensible set of properties of that resource.
128 */
129
130 private MetadataResource makeMetadataResource(Resource resource, InputDetails details) {
131 Map<String, GroundedValue<?>> properties = new HashMap<>();
132 try {
133
134 URI uri = new URI(resource.getResourceURI());
135
136 if (details.contentType != null) {
137 properties.put("content-type", StringValue.makeStringValue(details.contentType));
138 }
139 if (details.encoding != null) {
140 properties.put("encoding", StringValue.makeStringValue(details.encoding));
141 }
142
143 if ("file".equals(uri.getScheme())) {
144 File file = new File(uri);
145 properties.put("path", StringValue.makeStringValue(file.getPath()));
146 properties.put("absolute-path", StringValue.makeStringValue(file.getAbsolutePath()));
147 properties.put("canonical-path", StringValue.makeStringValue(file.getCanonicalPath()));
148 properties.put("can-read", BooleanValue.get(file.canRead()));
149 properties.put("can-write", BooleanValue.get(file.canWrite()));
150 properties.put("can-execute", BooleanValue.get(file.canExecute()));
151 properties.put("is-hidden", BooleanValue.get(file.isHidden()));
152 try {
153 properties.put("last-modified", DateTimeValue.fromJavaTime(file.lastModified()));
154 } catch (XPathException e) {
155 // ignore the failure
156 }
157 properties.put("length", new Int64Value(file.length()));
158
159 }
160 } catch (URISyntaxException | IOException e) {
161 // ignore
162 }
163
164 return new MetadataResource(resource.getResourceURI(), resource, properties);
165 }
166
167
168 /**
169 * Return the contents of a collection that maps to a directory in filestore
170 *
171 * @param directory the directory to be processed
172 * @param params parameters indicating whether to process recursively, what to do on
173 * errors, and which files to select
174 * @return an iterator over the absolute URIs of the documents in the collection
175 */
176
177 protected Iterator<String> directoryContents(File directory, URIQueryParameters params) {
178
179 FilenameFilter filter = null;
180 boolean recurse = false;
181 if (params != null) {
182 FilenameFilter f = params.getFilenameFilter();
183 if (f != null) {
184 filter = f;
185 }
186 Boolean r = params.getRecurse();
187 if (r != null) {
188 recurse = r;
189 }
190 }
191
192 Stack<Iterator<File>> directories = new Stack<>();
193 directories.push(Arrays.asList(directory.listFiles(filter)).iterator());
194 return new DirectoryIterator(directories, recurse, filter);
195
196 }
197
198 private static class DirectoryIterator implements Iterator<String> {
199
200 private Stack<Iterator<File>> directories;
201 private FilenameFilter filter;
202 private boolean recurse;
203 private String next = null;
204
205 public DirectoryIterator(Stack<Iterator<File>> directories, boolean recurse, FilenameFilter filter) {
206 this.directories = directories;
207 this.recurse = recurse;
208 this.filter = filter;
209 advance();
210 }
211
212 public boolean hasNext() {
213 return next != null;
214 }
215
216 public String next() {
217 String s = next;
218 advance();
219 return s;
220 }
221
222 public void remove() {
223 throw new UnsupportedOperationException();
224 }
225
226 private void advance() {
227 if (directories.isEmpty()) {
228 next = null;
229 } else {
230 Iterator<File> files = directories.peek();
231 while (!files.hasNext()) {
232 directories.pop();
233 if (directories.isEmpty()) {
234 next = null;
235 return;
236 }
237 files = directories.peek();
238 }
239 File nextFile = files.next();
240 if (nextFile.isDirectory()) {
241 if (recurse) {
242 directories.push(Arrays.asList(nextFile.listFiles(filter)).iterator());
243 }
244 advance();
245 } else {
246 next = nextFile.toURI().toString();
247 }
248 }
249 }
250 }
251
252
253
254
255
256 }