Skip to content

Commit

Permalink
Make ClassLoaderResourceAccessor implement Closable (#2308)
Browse files Browse the repository at this point in the history
* Update ClassLoaderResourceAccessor.java
* Log when there are issues closing a ResourceAccessor
* Added test for ClassLoaderResourceAccessor.close()

Co-authored-by: Nathan Voxland <nathan@voxland.net>
  • Loading branch information
Delir4um and nvoxland committed Jan 26, 2022
1 parent c038b28 commit 6fcabdc
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
Expand Up @@ -24,7 +24,7 @@
*
* @see OSGiResourceAccessor for OSGi-based classloaders
*/
public class ClassLoaderResourceAccessor extends AbstractResourceAccessor {
public class ClassLoaderResourceAccessor extends AbstractResourceAccessor implements AutoCloseable {

private ClassLoader classLoader;
protected List<FileSystem> rootPaths;
Expand Down Expand Up @@ -270,7 +270,7 @@ protected SortedSet<String> listFromClassLoader(String path, boolean recursive,
try (JarFile jar = new JarFile(URLDecoder.decode(jarPath, StandardCharsets.UTF_8.name()))) {
String comparePath = path;
if (comparePath.startsWith("/")) {
comparePath = "/"+comparePath;
comparePath = "/" + comparePath;
}
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
Expand Down Expand Up @@ -355,4 +355,17 @@ public SortedSet<String> describeLocations() {

return description;
}

@Override
public void close() throws Exception {
if (rootPaths != null) {
for (final FileSystem rootPath : rootPaths) {
try {
rootPath.close();
} catch (final Exception e) {
Scope.getCurrentScope().getLog(getClass()).fine("Cannot close path " + e.getMessage(), e);
}
}
}
}
}
Expand Up @@ -5,6 +5,8 @@ import liquibase.util.StreamUtil
import spock.lang.Specification
import spock.lang.Unroll

import java.nio.file.FileSystem

class ClassLoaderResourceAccessorTest extends Specification {

def testResourceAccessor = new ClassLoaderResourceAccessor(new URLClassLoader(
Expand Down Expand Up @@ -153,4 +155,23 @@ class ClassLoaderResourceAccessorTest extends Specification {
],
]
}

def close() {
setup:
FileSystem path1 = Mock()
FileSystem path2 = Mock()

when:
def testAccessor = new ClassLoaderResourceAccessor(this.getClass().getClassLoader())

testAccessor.rootPaths = null;
testAccessor.close() //no errors thrown from close() when rootPaths is null

testAccessor.rootPaths = [path1, path2]
testAccessor.close()

then:
2 * path1.close()
1 * path2.close()
}
}

0 comments on commit 6fcabdc

Please sign in to comment.