-
Notifications
You must be signed in to change notification settings - Fork 915
/
URLResource.java
386 lines (332 loc) · 12.4 KB
/
URLResource.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package org.jruby.util;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.channels.Channel;
import java.nio.channels.Channels;
import java.nio.file.attribute.FileTime;
import java.util.*;
import jnr.constants.platform.Errno;
import jnr.posix.FileStat;
import org.jruby.Ruby;
import org.jruby.RubyInstanceConfig;
public class URLResource implements FileResource, DummyResourceStat.FileResourceExt {
public static final String URI = "uri:";
public static final String CLASSLOADER = "classloader:";
public static final String URI_CLASSLOADER = URI + CLASSLOADER;
private final String uri;
private final String[] list;
private final URL url;
private final String pathname;
private final ClassLoader cl;
URLResource(String uri, URL url, String[] files) {
this(uri, url, null, null, files);
}
URLResource(String uri, ClassLoader cl, String pathname, String[] files) {
this(uri, null, cl, pathname, files);
}
private URLResource(String uri, URL url, ClassLoader cl, String pathname, String[] files) {
this.uri = uri;
this.list = files;
this.url = url;
this.cl = cl;
this.pathname = pathname;
}
@Override
public String absolutePath() {
return uri;
}
@Override
public String canonicalPath() {
return uri;
}
@Override
public String path() {
return uri;
}
@Override
public boolean exists() {
return url != null || pathname != null || list != null;
}
@Override
public boolean isDirectory() {
return list != null;
}
@Override
public boolean isFile() {
return list == null && (url != null || pathname != null);
}
@Override
public long length() {
long totalRead = 0;
InputStream is = null;
try {
is = openInputStream();
byte[] buf = new byte[8096];
int amountRead;
while ((amountRead = is.read(buf)) != -1) {
totalRead += amountRead;
}
is.close();
}
catch (IOException e) { close(is); }
return totalRead;
}
@Override
public boolean canRead() { return exists(); }
@Override
public boolean canWrite() { return false; }
@Override
public boolean canExecute() { return false; }
@Override
public String[] list() { return list; }
@Override
public boolean isSymLink() { return false; }
@Override
public long lastModified() {
return 0L; // not implemented - problematic for a classpath resource
}
public FileTime lastModifiedTime() {
return null; // not implemented - problematic for a classpath resource
}
public FileTime lastAccessTime() {
return null; // not implemented - problematic for a classpath resource
}
public FileTime creationTime() {
return null; // not implemented - problematic for a classpath resource
}
@Override
public int errno() {
return Errno.ENOENT.intValue();
}
@Override
public FileStat stat() {
return new DummyResourceStat(this);
}
@Override
public FileStat lstat() {
return stat(); // URLs don't have symbolic links, so lstat == stat
}
@Override
public <T> T unwrap(Class<T> type) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public InputStream openInputStream() throws IOException {
if (pathname != null) {
return cl.getResourceAsStream(pathname);
}
if (url == null) {
throw new ResourceException.NotFound(absolutePath());
}
return url.openStream();
}
@Override
public Channel openChannel( int flags, int perm ) throws IOException {
return Channels.newChannel(openInputStream());
}
@Override
public boolean equals(Object obj) {
if (obj instanceof URLResource) {
return uri.equals(((URLResource) obj).uri);
}
return false;
}
@Override
public int hashCode() {
return 17 * uri.hashCode();
}
@Override
public String toString() {
return getClass().getName() + '{' + absolutePath() + '}';
}
public static FileResource createClassloaderURI(Ruby runtime, String pathname, boolean asFile) {
ClassLoader cl = runtime != null ? runtime.getJRubyClassLoader() : RubyInstanceConfig.defaultClassLoader();
try {
pathname = new URI(pathname.replaceFirst("^/*", "/"))
.normalize().getPath().replaceAll("^/([.][.]/)*", "");
}
catch (URISyntaxException e) {
pathname = pathname.replaceAll("^[.]?/*", "");
}
final URL url = cl.getResource(pathname);
String[] files = null;
if (!asFile) {
files = listClassLoaderFiles(cl, pathname);
if (files == null) { // no .jrubydir found
boolean isDirectory = false;
// we do not want double entries
Set<String> list = new LinkedHashSet<>();
list.add("."); list.add("..");
try {
// first look at the enum from the classloader
// may or may not contain directory entries
Enumeration<URL> urls = cl.getResources(pathname);
while (urls.hasMoreElements()){
isDirectory = addDirectoryEntries(list, urls.nextElement(), isDirectory);
}
if (runtime != null) {
// we have a runtime, so look at the JRubyClassLoader
// and its parent classloader
isDirectory = addDirectoriesFromClassloader(cl, list, pathname, isDirectory);
isDirectory = addDirectoriesFromClassloader(cl.getParent(), list, pathname, isDirectory);
}
else {
// just look at what we have
isDirectory = addDirectoriesFromClassloader(cl, list, pathname, isDirectory);
}
if (isDirectory) files = list.toArray(new String[list.size()]);
}
catch (IOException e) { /* we tried */ }
}
}
return new URLResource(URI_CLASSLOADER + '/' + pathname, cl, url == null ? null : pathname, files);
}
private static boolean addDirectoriesFromClassloader(ClassLoader cl, Set<String> list, String pathname, boolean isDirectory) throws IOException {
if (cl instanceof URLClassLoader ) {
for (URL u : ((URLClassLoader) cl).getURLs()) {
if (u.getFile().endsWith(".jar") && u.getProtocol().equals("file")) {
u = new URL("jar:" + u + "!/" + pathname);
isDirectory = addDirectoryEntries(list, u, isDirectory);
}
}
}
return isDirectory;
}
private static boolean addDirectoryEntries(Set<String> entries, URL url, boolean isDirectory) {
switch (url.getProtocol()) {
case "jar":
// maybe the jar itself contains directory entries (which are actually optional)
FileResource jar = JarResource.create(url.toString());
if (jar != null && jar.isDirectory()) {
if (!isDirectory) isDirectory = true;
entries.addAll(Arrays.asList(jar.list()));
}
break;
case "file":
// let's look on the filesystem
File file = new File(url.getPath());
if (file.isDirectory()) {
if (!isDirectory) isDirectory = true;
entries.addAll(Arrays.asList(file.list()));
}
break;
default:
}
return isDirectory;
}
public static FileResource create(Ruby runtime, String pathname, boolean asFile) {
if (!pathname.startsWith(URI)) {
return null;
}
// GH-2005 needs the replace
pathname = pathname.substring(URI.length()).replace('\\', '/');
if (pathname.startsWith(CLASSLOADER)) {
return createClassloaderURI(runtime, pathname.substring(CLASSLOADER.length()), asFile);
}
return createRegularURI(pathname, asFile);
}
private static FileResource createRegularURI(String pathname, boolean asFile) {
URL url;
try {
// TODO NormalizedFile does too much - should leave uri: files as they are
// and make file:/a protocol to be file:///a so the second replace does not apply
pathname = pathname.replaceFirst( "file:/([^/])", "file:///$1" );
pathname = pathname.replaceFirst( ":/([^/])", "://$1" );
url = new URL(pathname);
// we do not want to deal with those url here like this though they are valid url/uri
if (url.getProtocol().startsWith("http")) return null;
}
catch (MalformedURLException e) { // file does not exists
return new URLResource(URI + pathname, null, null);
}
String[] files = asFile ? null : listFiles(pathname);
if (files != null) {
return new URLResource(URI + pathname, null, files);
}
try {
InputStream is = url.openStream();
// no inputstream happens with knoplerfish OSGI and osgi tests from /maven/jruby-complete
if (is != null) {
is.close();
}
else {
// there is no input-stream from this url
url = null;
}
return new URLResource(URI + pathname, url, null);
}
catch (IOException e) { // can not open stream - treat it as not existing file
return new URLResource(URI + pathname, null, null);
}
}
private static String[] listFilesFromInputStream(InputStream is) {
BufferedReader reader = null;
try {
List<String> files = new ArrayList<>();
reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
while (line != null) {
files.add(line);
line = reader.readLine();
}
return files.toArray(new String[files.size()]);
}
catch (IOException e) {
return null;
}
finally {
close(reader);
}
}
private static String[] listClassLoaderFiles(ClassLoader classloader, String pathname) {
try {
String path = pathname + (pathname.isEmpty() || pathname.endsWith("/") ? ".jrubydir" : "/.jrubydir");
Enumeration<URL> urls = classloader.getResources(path);
if (!urls.hasMoreElements()) return null;
Set<String> result = new LinkedHashSet<>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
for (String entry: listFilesFromInputStream(url.openStream())) {
if (!result.contains(entry)) result.add(entry);
}
}
return result.toArray(new String[result.size()]);
}
catch (IOException e) {
return null;
}
}
private static String[] listFiles(String pathname) {
try {
InputStream is = new URL(pathname + "/.jrubydir").openStream();
// no inputstream happens with knoplerfish OSGI and osgi tests from /maven/jruby-complete
if (is != null) {
return listFilesFromInputStream(is);
}
return null;
}
catch (IOException e) {
return null;
}
}
private static void close(final Closeable resource) {
if (resource != null) {
try { resource.close(); } catch (IOException ex) {}
}
}
public static URL getResourceURL(Ruby runtime, String location) {
if (location.startsWith(URI_CLASSLOADER)) {
return runtime.getJRubyClassLoader().getResource(location.substring(URI_CLASSLOADER.length() + 1));
}
try {
return new URL(location.replaceFirst("^" + URI, ""));
}
catch (MalformedURLException e) {
throw new AssertionError("BUG in " + URLResource.class, e);
}
}
}