-
Notifications
You must be signed in to change notification settings - Fork 62
/
Resource.scala
421 lines (378 loc) · 12.1 KB
/
Resource.scala
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package wvlet.log.io
//--------------------------------------
//
// Resource.scala
// Since: 2012/07/17 9:12
//
//--------------------------------------
import java.io.{BufferedInputStream, File}
import java.lang.reflect.Modifier
import java.net.{URL, URLClassLoader}
import java.util.jar.JarFile
import scala.annotation.tailrec
/**
* Extend this trait to add support your class for reading resources
*/
trait ResourceReader {
def open[U](resourceFileName: String)(f: BufferedInputStream => U): U = {
Resource.open(this.asInstanceOf[AnyRef].getClass, resourceFileName)(f)
}
}
/**
* Resource file manager.
*
* @author
* leo
*/
object Resource {
/**
* Open a resource as a stream, then execute the code block using the stream
*
* @param referenceClass
* context class to specify the package containing the resource file
* @param resourceFileName
* file name
* @param body
* code block
* @tparam U
*/
def open[U](referenceClass: Class[_], resourceFileName: String)(body: BufferedInputStream => U): U = {
val u = find(referenceClass, resourceFileName)
if (u.isEmpty) {
sys.error("Resource %s (in %s) not found".format(resourceFileName, referenceClass.getSimpleName))
}
val s = new BufferedInputStream(u.get.openStream())
try body(s)
finally s.close
}
private def packagePath(referenceClass: Class[_]): String = {
return packagePath(referenceClass.getPackage)
}
private def packagePath(basePackage: Package): String = {
return packagePath(basePackage.getName)
}
private def packagePath(packageName: String): String = {
val packageAsPath: String = packageName.replaceAll("\\.", "/")
if (packageAsPath.endsWith("/")) packageAsPath else packageAsPath + "/"
}
private def currentClassLoader = Thread.currentThread().getContextClassLoader
/**
* Return a URLClassLoader if the given ClassLoader or its parent has the URLClassLoader
*/
private def findNextURLClassLoader(cl: ClassLoader): Option[URLClassLoader] = {
cl match {
case u: URLClassLoader => Some(u)
case null => None
case other => findNextURLClassLoader(other.getParent)
}
}
private def resolveResourcePath(packageName: String, resourceFileName: String) = {
val path: String = packagePath(packageName)
prependSlash(path + resourceFileName)
}
private def prependSlash(name: String): String = {
if (name.startsWith("/")) {
name
} else {
"/" + name
}
}
def find(referenceClass: Class[_], resourceFileName: String): Option[URL] = {
find(packagePath(referenceClass), resourceFileName)
}
/**
* Find a resource from the give absolute path
*
* @param absoluteResourcePath
* @return
*/
def find(absoluteResourcePath: String): Option[URL] =
find(
"",
if (absoluteResourcePath.startsWith("/"))
absoluteResourcePath.substring(1)
else absoluteResourcePath
)
/**
* Finds the java.net.URL of the resource
*
* @param packageName
* the base package name to find the resource
* @param resourceFileName
* the resource file name relative to the package folder
* @return
* the URL of the specified resource
*/
def find(packageName: String, resourceFileName: String): Option[URL] = {
val resourcePath = resolveResourcePath(packageName, resourceFileName)
@tailrec
def loop(cl: ClassLoader): Option[URL] = {
findNextURLClassLoader(cl) match {
case Some(urlClassLoader) =>
urlClassLoader.getResource(resourcePath) match {
case path: URL =>
Some(path)
case null =>
loop(urlClassLoader.getParent)
}
case None => None
}
}
loop(currentClassLoader) orElse Option(this.getClass.getResource(resourcePath))
}
/**
* VirtualFile is a common interface to handle system files and file resources in JAR.
*
* System file resources have an URL prefixed with "file:". e.g., "file:/C:/Program
* Files/Software/classes/org/xerial/util/FileResource.java" JAR file contents have an URL prefixed with "jar:file:
* e.g., "jar:file:/C:/Program Files/Software/something.jar!/org/xerial/util/FileResource.java"
*
* @author
* leo
*/
abstract trait VirtualFile {
/**
* Gets the logical path of the file. For example, if this VirtualFile' URL is
* "file:/somewhere/org/xerial/util/FileResource.java", its logical name is org/xerial/util/FileResource.java,
* beginning from the root package.
*
* @return
*/
def logicalPath: String
/**
* is directory?
*
* @return
* true when the file is a directory, otherwise false
*/
def isDirectory: Boolean
/**
* Gets the URL of this file
*
* @return
*/
def url: URL
}
/**
* A virtual file implementation for usual files
*
* @author
* leo
*/
case class SystemFile(file: java.io.File, logicalPath: String) extends VirtualFile {
def url: URL = file.toURI.toURL
def isDirectory: Boolean = file.isDirectory
}
/**
* A virtual file implementation for file resources contained in a JAR file
*
* @author
* leo
*/
case class FileInJar(resourceURL: URL, logicalPath: String, isDirectory: Boolean) extends VirtualFile {
if (resourceURL == null) {
sys.error("resource URL cannot be null: " + logicalPath)
}
def url = resourceURL
}
private def extractLogicalName(packagePath: String, resourcePath: String): String = {
val p = if (!packagePath.endsWith("/")) packagePath + "/" else packagePath
val pos: Int = resourcePath.indexOf(p)
if (pos < 0) return null
val logicalName: String = resourcePath.substring(pos + p.length)
logicalName
}
private def collectFileResources(
resourceURLString: String,
packagePath: String,
resourceFilter: String => Boolean
): Seq[VirtualFile] = {
val logicalName = extractLogicalName(packagePath, resourceURLString)
if (logicalName == null) {
throw new IllegalArgumentException("packagePath=" + packagePath + ", resourceURL=" + resourceURLString)
}
val b = Seq.newBuilder[VirtualFile]
val file: File = new File(new URL(resourceURLString).toURI)
if (resourceFilter(file.getPath)) {
b += SystemFile(file, logicalName)
}
if (file.isDirectory) {
for (childFile <- file.listFiles) {
val childResourceURL =
resourceURLString + (if (resourceURLString.endsWith("/")) "" else "/") + childFile.getName
b ++= collectFileResources(childResourceURL, packagePath, resourceFilter)
}
}
b.result()
}
/**
* Create a list of all resources under the given resourceURL recursively. If the resourceURL is a file, this method
* searches directories under the path. If the resource is contained in a Jar file, it searches contents of the Jar
* file.
*
* @param resourceURL
* @param packageName
* package name under consideration
* @param resourceFilter
* @return
* the list of resources matching the given resource filter
*/
private def listResources(
resourceURL: URL,
packageName: String,
resourceFilter: String => Boolean
): Seq[VirtualFile] = {
val pkgPath = packagePath(packageName)
val fileList = Seq.newBuilder[VirtualFile]
if (resourceURL == null) {
return Seq.empty
}
val protocol = resourceURL.getProtocol
if (protocol == "file") {
val resourceURLString = resourceURL.toString
fileList ++= collectFileResources(resourceURLString, pkgPath, resourceFilter)
} else if (protocol == "jar") {
val path: String = resourceURL.getPath
val pos: Int = path.indexOf("!")
if (pos < 0) {
throw new IllegalArgumentException("invalid resource URL: " + resourceURL)
}
val jarPath = path.substring(0, pos).replaceAll("%20", " ")
val filePath =
path
.substring(0, pos)
.replaceAll("%20", " ")
.replaceAll("%25", "%") // %25 => %
.replace("file:", "")
val jarURLString = "jar:" + jarPath
val jf: JarFile = new JarFile(filePath)
val entryEnum = jf.entries
while (entryEnum.hasMoreElements) {
val jarEntry = entryEnum.nextElement
val physicalURL = jarURLString + "!/" + jarEntry.getName
val jarFileURL = new URL(physicalURL)
val logicalName = extractLogicalName(pkgPath, jarEntry.getName)
if (logicalName != null && resourceFilter(logicalName)) {
fileList += FileInJar(jarFileURL, logicalName, jarEntry.isDirectory)
}
}
} else {
throw new UnsupportedOperationException("resources other than file or jar are not supported: " + resourceURL)
}
fileList.result()
}
/**
* Collect resources under the given package
*
* @param packageName
* @return
*/
def listResources(packageName: String): Seq[VirtualFile] =
listResources(
packageName,
{ (f: String) =>
true
}
)
/**
* Collect resources under the given package
*
* @param classLoader
* @param packageName
* @param resourceFilter
* @return
*/
def listResources(
packageName: String,
resourceFilter: String => Boolean,
classLoader: ClassLoader = Thread.currentThread.getContextClassLoader
): Seq[VirtualFile] = {
val b = Seq.newBuilder[VirtualFile]
for (u <- findResourceURLs(classLoader, packageName)) {
b ++= listResources(u, packageName, resourceFilter)
}
b.result()
}
/**
* Find resource URLs that can be found from a given class loader and its ancestors
*
* @param cl
* class loader
* @param name
* resource name
* @return
*/
def findResourceURLs(cl: ClassLoader, name: String): Seq[URL] = {
val path = packagePath(name)
val b = Seq.newBuilder[URL]
@tailrec
def loop(cl: ClassLoader): Unit = {
findNextURLClassLoader(cl) match {
case Some(urlClassLoader) =>
val e = urlClassLoader.findResources(path)
while (e.hasMoreElements) {
val elem = e.nextElement()
b += elem
}
loop(urlClassLoader.getParent)
case None =>
// Do nothing
}
}
loop(currentClassLoader)
b.result()
}
def findClasses[A](
packageName: String,
toSearch: Class[A],
classLoader: ClassLoader = Thread.currentThread.getContextClassLoader
): Seq[Class[A]] = {
val classFileList = listResources(
packageName,
{ (f: String) =>
f.endsWith(".class")
},
classLoader
)
def componentName(path: String): Option[String] = {
val dot: Int = path.lastIndexOf(".")
if (dot <= 0) {
None
} else {
Some(path.substring(0, dot).replaceAll("/", "."))
}
}
def findClass(name: String): Option[Class[_]] = {
try Some(Class.forName(name, false, classLoader))
catch {
case e: ClassNotFoundException => None
}
}
val b = Seq.newBuilder[Class[A]]
for (vf <- classFileList; cn <- componentName(vf.logicalPath)) {
val className: String = packageName + "." + cn
for (cl <- findClass(className)) {
if (!Modifier.isAbstract(cl.getModifiers) && toSearch.isAssignableFrom(cl)) {
b += cl.asInstanceOf[Class[A]]
}
}
}
b.result()
}
def findClasses[A](searchPath: Package, toSearch: Class[A], classLoader: ClassLoader): Seq[Class[A]] = {
findClasses(searchPath.getName, toSearch, classLoader)
}
}