-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
ClassLoaderResourceAccessor.java
291 lines (243 loc) · 11 KB
/
ClassLoaderResourceAccessor.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
package liquibase.resource;
import liquibase.Scope;
import liquibase.changelog.DatabaseChangeLog;
import liquibase.util.StreamUtil;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
/**
* An implementation of {@link FileSystemResourceAccessor} that builds up the file roots based on the passed {@link ClassLoader}.
* If you are using a ClassLoader that isn't based on local files, you will need to use a different {@link ResourceAccessor} implementation.
*
* @see OSGiResourceAccessor for OSGi-based classloaders
*/
public class ClassLoaderResourceAccessor extends AbstractResourceAccessor {
private ClassLoader classLoader;
protected List<FileSystem> rootPaths;
protected SortedSet<String> description;
public ClassLoaderResourceAccessor() {
this(Thread.currentThread().getContextClassLoader());
}
public ClassLoaderResourceAccessor(ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Performs the configuration of this resourceAccessor.
* Not done in the constructor for performance reasons, but can be called at the beginning of every public method.
*/
protected void init() {
if (rootPaths == null) {
this.rootPaths = new ArrayList<>();
this.description = new TreeSet<>();
loadRootPaths(classLoader);
}
}
/**
* The classloader search logic in {@link #list(String, String, boolean, boolean, boolean)} does not handle jar files well.
* This method is called by that method to populate {@link #rootPaths} with additional paths to search.
*/
protected void loadRootPaths(ClassLoader classLoader) {
if (classLoader instanceof URLClassLoader) {
final URL[] urls = ((URLClassLoader) classLoader).getURLs();
if (urls != null) {
for (URL url : urls) {
try {
addDescription(url);
this.rootPaths.add(FileSystems.newFileSystem(Paths.get(url.toURI()), this.getClass().getClassLoader()));
} catch (ProviderNotFoundException e) {
if (url.toExternalForm().startsWith("file:/")) {
//that is expected, the classloader itself will handle it
} else {
Scope.getCurrentScope().getLog(getClass()).info("No filesystem provider for URL " + url.toExternalForm() + ". Will rely on classloader logic for listing files.");
}
} catch (FileSystemNotFoundException fsnfe) {
Scope.getCurrentScope().getLog(getClass()).info("Configured classpath location " + url.toString() + " does not exist");
} catch (Throwable e) {
Scope.getCurrentScope().getLog(getClass()).warning("Cannot create filesystem for url " + url.toExternalForm() + ": " + e.getMessage(), e);
}
}
}
}
final ClassLoader parent = classLoader.getParent();
if (parent != null) {
loadRootPaths(parent);
}
}
private void addDescription(URL url) {
try {
this.description.add(Paths.get(url.toURI()).toString());
} catch (Throwable e) {
this.description.add(url.toExternalForm());
}
}
@Override
public InputStreamList openStreams(String relativeTo, String streamPath) throws IOException {
init();
InputStreamList returnList = new InputStreamList();
streamPath = getFinalPath(relativeTo, streamPath);
//sometimes the classloader returns duplicate copies of the same url
Set<String> seenUrls = new HashSet<>();
Enumeration<URL> resources = classLoader.getResources(streamPath);
while (resources.hasMoreElements()) {
URL url = resources.nextElement();
if (seenUrls.add(url.toExternalForm())) {
try {
returnList.add(url.toURI(), url.openStream());
} catch (URISyntaxException e) {
Scope.getCurrentScope().getLog(getClass()).severe(e.getMessage(), e);
}
}
}
return returnList;
}
protected String getFinalPath(String relativeTo, String streamPath) {
streamPath = streamPath.replace("\\", "/");
streamPath = streamPath.replaceFirst("^classpath:", "");
if (relativeTo != null) {
relativeTo = relativeTo.replace("\\", "/");
relativeTo = relativeTo.replaceFirst("^classpath:", "");
relativeTo = relativeTo.replaceAll("//+", "/");
if (!relativeTo.endsWith("/")) {
String lastPortion = relativeTo.replaceFirst(".+/", "");
if (lastPortion.contains(".")) {
relativeTo = relativeTo.replaceFirst("/[^/]+?$", "");
}
}
//
// If this is a simple file name then set the
// relativeTo value as if it is a root path
//
if (! relativeTo.contains("/") && relativeTo.contains(".")) {
relativeTo = "/";
}
streamPath = relativeTo + "/" + streamPath;
}
streamPath = streamPath.replaceAll("//+", "/");
streamPath = streamPath.replaceFirst("^/", "");
return DatabaseChangeLog.normalizePath(streamPath);
}
@Override
public SortedSet<String> list(String relativeTo, String path, boolean recursive, boolean includeFiles, boolean includeDirectories) throws IOException {
init();
String finalPath = getFinalPath(relativeTo, path);
final SortedSet<String> returnList = listFromClassLoader(finalPath, recursive, includeFiles, includeDirectories);
returnList.addAll(listFromRootPaths(finalPath, recursive, includeFiles, includeDirectories));
return returnList;
}
/**
* Called by {@link #list(String, String, boolean, boolean, boolean)} to find files in {@link #rootPaths}.
*/
protected SortedSet<String> listFromRootPaths(String path, boolean recursive, boolean includeFiles, boolean includeDirectories) {
SortedSet<String> returnSet = new TreeSet<>();
SimpleFileVisitor<Path> fileVisitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (includeFiles && attrs.isRegularFile()) {
addToReturnList(file);
}
if (includeDirectories && attrs.isDirectory()) {
addToReturnList(file);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (includeDirectories) {
addToReturnList(dir);
}
return FileVisitResult.CONTINUE;
}
protected void addToReturnList(Path file) {
if (!file.toString().equals(path)) {
returnSet.add(file.toString()
.replaceFirst("^/", "")
.replaceFirst("/$", "")
.replaceAll("//+", "/")
);
}
}
};
for (FileSystem fileSystem : rootPaths) {
int maxDepth = recursive ? Integer.MAX_VALUE : 1;
try {
Files.walkFileTree(fileSystem.getPath(path), Collections.singleton(FileVisitOption.FOLLOW_LINKS), maxDepth, fileVisitor);
} catch (NoSuchFileException e) {
//that is OK
} catch (IOException e) {
Scope.getCurrentScope().getLog(getClass()).warning("Cannot walk filesystem: " + e.getMessage(), e);
}
}
return returnSet;
}
/**
* Called by {@link #list(String, String, boolean, boolean, boolean)} to find files in {@link #classLoader}.
*/
protected SortedSet<String> listFromClassLoader(String path, boolean recursive, boolean includeFiles, boolean includeDirectories) {
final SortedSet<String> returnSet = new TreeSet<>();
final Enumeration<URL> resources;
try {
resources = classLoader.getResources(path);
} catch (IOException e) {
Scope.getCurrentScope().getLog(getClass()).severe("Cannot list resources in path " + path + ": " + e.getMessage(), e);
return returnSet;
}
while (resources.hasMoreElements()) {
final URL url = resources.nextElement();
try {
final InputStream inputStream = url.openStream();
final String fileList = StreamUtil.readStreamAsString(inputStream);
if (!fileList.isEmpty()) {
for (String childName : fileList.split("\n")) {
String childPath = (path + "/" + childName).replaceAll("//+", "/");
if (isDirectory(childPath)) {
if (includeDirectories) {
returnSet.add(childPath);
}
if (recursive) {
returnSet.addAll(listFromClassLoader(childPath, recursive, includeFiles, includeDirectories));
}
} else {
if (includeFiles) {
returnSet.add(childPath);
}
}
}
}
} catch (IOException e) {
Scope.getCurrentScope().getLog(getClass()).severe("Cannot list resources in " + url.toExternalForm() + ": " + e.getMessage(), e);
}
}
return returnSet;
}
/**
* Used by {@link #listFromClassLoader(String, boolean, boolean, boolean)} to determine if a path is a directory or not.
*/
protected boolean isDirectory(String path) {
try {
final Enumeration<URL> resources = classLoader.getResources(path);
while (resources.hasMoreElements()) {
final URL url = resources.nextElement();
final File file = new File(url.toURI());
if (file.exists() && file.isDirectory()) {
return true;
}
}
} catch (Exception e) {
//not a url we can handle
}
//fallback logic depends on files having an extension and directories not
String lastPortion = path.replaceFirst(".*/", "");
return !lastPortion.contains(".");
}
@Override
public SortedSet<String> describeLocations() {
init();
return description;
}
}