Debian Codegraph @

net/sf/saxon/resource/JarCollection.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.expr.XPathContext;
11 import net.sf.saxon.functions.URIQueryParameters;
12 import net.sf.saxon.lib.ParseOptions;
13 import net.sf.saxon.lib.Resource;
14 import net.sf.saxon.om.GroundedValue;
15 import net.sf.saxon.om.SpaceStrippingRule;
16 import net.sf.saxon.trans.UncheckedXPathException;
17 import net.sf.saxon.trans.XPathException;
18 import net.sf.saxon.value.Base64BinaryValue;
19 import net.sf.saxon.value.DateTimeValue;
20 import net.sf.saxon.value.Int64Value;
21 import net.sf.saxon.value.StringValue;
22
23 import java.io.*;
24 import java.net.MalformedURLException;
25 import java.net.URL;
26 import java.net.URLConnection;
27 import java.util.*;
28 import java.util.zip.ZipEntry;
29 import java.util.zip.ZipInputStream;
30
31
32 /**
33 * A JarCollection represents a collection of resources held in a JAR or ZIP archive, accessed typically
34 * using a URI using the (Java-defined) "jar" URI scheme, or simply a "file" URI where the target
35 * file is a JAR or ZIP file.
36 */
37
38
39 public class JarCollection extends AbstractResourceCollection {
40
41 private XPathContext context;
42 private String collectionURI;
43 private SpaceStrippingRule whitespaceRules;
44
45
46 /**
47 * Create a JarCollection
48 * @param context The XPath dynamic context
49 * @param collectionURI the collection URI used to identify this collection (typically but not necessarily
50 * the location of the JAR file)
51 * @param params URI query parameters appearing on the collection URI
52 */
53
54 public JarCollection(XPathContext context, String collectionURI, URIQueryParameters params) {
55 super(context.getConfiguration());
56 this.context = context;
57 this.collectionURI = collectionURI;
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 /**
83 * Get the URI identifying this collection
84 *
85 * @return the collection URI
86 */
87
88 public String getCollectionURI() {
89 return collectionURI;
90 }
91
92 /**
93 * Get the URIs of the resources within the collection
94 *
95 * @return a list of all the URIs of resources within the collection. The resources are identified
96 * by URIs of the form collection-uri!entry-path
97 * @throws XPathException if any error occurs accessing the JAR file contents
98 * @param context dynamic evaluation context
99 */
100
101 public Iterator<String> getResourceURIs(XPathContext context) throws XPathException {
102 FilenameFilter filter = null;
103 boolean recurse = false;
104 if (params != null) {
105
106 FilenameFilter f = params.getFilenameFilter();
107 if (f != null) {
108 filter = f;
109 }
110
111 Boolean r = params.getRecurse();
112 if (r != null) {
113 recurse = r;
114 }
115
116 }
117
118 ZipInputStream zipInputStream = getZipInputStream();
119 List<String> result = new ArrayList<>();
120 try {
121 ZipEntry entry;
122 String dirStr = "";
123 while ((entry = zipInputStream.getNextEntry()) != null) {
124 if (entry.isDirectory()) {
125 dirStr = entry.getName();
126 }
127 if (!entry.isDirectory()) {
128 String entryName = entry.getName();
129
130 if (filter != null) {
131 if (dirStr.equals("") || !entryName.contains(dirStr)) {
132 if (entryName.contains("/")) {
133 dirStr = entryName.substring(0, entryName.lastIndexOf("/"));
134 } else {
135 dirStr = "";
136 }
137 }
138 if (filter.accept(new File(dirStr), entryName)) {
139 result.add(makeResourceURI(entryName));
140 }
141 } else {
142 result.add(makeResourceURI(entryName));
143 }
144 }
145 entry = zipInputStream.getNextEntry();
146
147 }
148 } catch (IOException e) {
149 throw new XPathException("Unable to extract entry in JAR/ZIP file: " + collectionURI, e);
150 }
151 return result.iterator();
152 }
153
154 private ZipInputStream getZipInputStream() throws XPathException {
155 URL url;
156 try {
157 url = new URL(collectionURI);
158 } catch (MalformedURLException e) {
159 throw new XPathException("Malformed JAR/ZIP file URI: " + collectionURI, e);
160 }
161 URLConnection connection;
162 try {
163 connection = url.openConnection();
164 } catch (IOException e) {
165 throw new XPathException("Unable to open connection to JAR/ZIP file URI: " + collectionURI, e);
166 }
167 InputStream stream;
168 try {
169 stream = connection.getInputStream();
170 } catch (IOException e) {
171 throw new XPathException("Unable to get input stream for JAR/ZIP file connection: " + collectionURI, e);
172 }
173 return new ZipInputStream(stream);
174 }
175
176 /**
177 * Get an iterator over the resources in the collection
178 * @param context the XPath evaluation context
179 * @return an iterator over the resources in the collection. This may include instances of
180 * {@link FailedResource} if there are resources that cannot be processed for some reason.
181 * @throws XPathException if it is not possible to get an iterator.
182 */
183
184 public Iterator<Resource> getResources(XPathContext context) throws XPathException {
185 FilenameFilter filter = null;
186 boolean recurse = false;
187 if (params != null) {
188
189 FilenameFilter f = params.getFilenameFilter();
190 if (f != null) {
191 filter = f;
192 }
193
194 Boolean r = params.getRecurse();
195 if (r != null) {
196 recurse = r;
197 }
198
199 }
200 ZipInputStream zipInputStream = getZipInputStream();
201 return new JarIterator(this.context, zipInputStream, filter);
202 }
203
204
205 private String makeResourceURI(String entryName) {
206 return
207 (collectionURI.startsWith("jar:") ? "" : "jar:") +
208 collectionURI + "!/" + entryName;
209 }
210
211
212 private class JarIterator implements Iterator<Resource>, Closeable {
213 private FilenameFilter filter;
214 private Resource next = null;
215 private XPathContext context;
216 private ZipInputStream zipInputStream;
217 private String dirStr = "";
218 private ParseOptions options;
219 private boolean metadata;
220
221
222 public JarIterator(XPathContext context, ZipInputStream zipInputStream, FilenameFilter filter) {
223 this.context = context;
224 this.filter = filter;
225 this.zipInputStream = zipInputStream;
226 this.options = optionsFromQueryParameters(params, context);
227 this.options.setSpaceStrippingRule(whitespaceRules);
228 Boolean metadataParam = params == null ? null : params.getMetaData();
229 metadata = metadataParam != null && metadataParam;
230
231 advance();
232 }
233
234 public boolean hasNext() {
235 boolean more = next != null;
236 if (!more) {
237 try {
238 zipInputStream.close();
239 } catch (IOException e) {
240 throw new UncheckedXPathException(new XPathException(e));
241 }
242 }
243 return more;
244 }
245
246 public Resource next() {
247 Resource current = next;
248 advance();
249 return current;
250 }
251
252 public void remove() {
253 throw new UnsupportedOperationException();
254 }
255
256 private void advance() {
257 while (true) {
258 ZipEntry entry;
259 try {
260 entry = zipInputStream.getNextEntry();
261 if (entry == null) {
262 next = null;
263 return;
264 }
265 } catch (IOException e) {
266 next = new FailedResource(null, new XPathException(e));
267 break;
268 }
269 if (entry.isDirectory()) {
270 dirStr = entry.getName();
271 } else {
272 String entryName = entry.getName();
273 if (filter != null) {
274 if (dirStr.equals("") || !entryName.contains(dirStr)) {
275 if (entryName.contains("/")) {
276 dirStr = entryName.substring(0, entryName.lastIndexOf("/"));
277 } else {
278 dirStr = "";
279 }
280 }
281 if (!filter.accept(new File(dirStr), entryName)) {
282 continue;
283 }
284 }
285 String resourceURI = null;
286 try {
287 InputStream is = zipInputStream;
288 ByteArrayOutputStream output = new ByteArrayOutputStream();
289 try {
290 byte[] buffer = new byte[4096];
291 int len = 0;
292 while ((len = is.read(buffer)) > 0) {
293 output.write(buffer, 0, len);
294 }
295 } catch (IOException err) {
296 throw new UncheckedXPathException(new XPathException(err));
297 } finally {
298 // we must always close the output file
299 try {
300 output.close();
301 } catch (IOException e) {
302 next = new FailedResource(null, new XPathException(e));
303 }
304 }
305 InputStream entryContent = new ByteArrayInputStream(output.toByteArray());
306 InputDetails details = new InputDetails();
307 details.inputStream = entryContent;
308 details.contentType = guessContentType(entry.getName(), entryContent);
309 details.parseOptions = options;
310 resourceURI = makeResourceURI(entry.getName());
311 next = makeResource(context.getConfiguration(), details, resourceURI);
312 if (metadata) {
313 Map<String, GroundedValue<?>> properties = makeProperties(entry);
314 next = new MetadataResource(resourceURI, next, properties);
315 }
316 return;
317 } catch (XPathException e) {
318 next = new FailedResource(resourceURI, e);
319 }
320 }
321 }
322
323 }
324
325 @Override
326 public void close() throws IOException {
327 zipInputStream.close();
328 }
329 }
330
331 /**
332 * Get the properties of a Zip file entry, for use when returning a MetadataResource containing this information
333 * @param entry the current Zip file entry
334 * @return a map containing the properties of this entry: comment, compressed-size, crc, extra, compression-method,
335 * entry-name, size, and last-modified.
336 */
337
338 protected Map<String, GroundedValue<?>> makeProperties(ZipEntry entry) {
339 HashMap<String, GroundedValue<?>> map = new HashMap<>(10);
340 map.put("comment", StringValue.makeStringValue(entry.getComment()));
341 map.put("compressed-size", new Int64Value(entry.getCompressedSize()));
342 map.put("crc", new Int64Value(entry.getCrc()));
343 byte[] extra = entry.getExtra();
344 if (extra != null) {
345 map.put("extra", new Base64BinaryValue(extra));
346 }
347 map.put("compression-method", new Int64Value(entry.getMethod()));
348 map.put("entry-name", StringValue.makeStringValue(entry.getName()));
349 map.put("size", new Int64Value(entry.getSize()));
350 try {
351 map.put("last-modified", DateTimeValue.fromJavaTime(entry.getTime()));
352 } catch (XPathException err) {
353 // ignore the failure
354 }
355 return map;
356 }
357
358
359 }