3

Inside my WEB application there is a classpath or resource directory with JSON and text files.

/classes/mydir/a.json  
/classes/mydir/b.json
/classes/mydir/b.txt
/classes/mydir/xyz.json

I need a InputStream (to give to Jackson JSON ObjectMapper) to all JSON files in this directory.

I do a

URL dirUrl = getClass().getResource("/mydir");

which gives me

vfs:/content/mywar.war/WEB-INF/classes/mydir/

Which is the correct directory but any next step using toUri, File or nio classes complains that 'vfs' is not supported.

Are there any (JBoss/EAP) utility classes to read resources from the classpath inside a JBoss EAP or can someone give an example to do a JSON file listing of a classpath directory? Hopefully not using yet another dependency.

Runtime: JBoss EAP 7.1.4.GA (WildFly Core 3.0.17.Final-redhat-1)
Java: 1.8.0_191-b12

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
JStefan
  • 149
  • 1
  • 2
  • 11

2 Answers2

1

You can use Reflections library to scan the package on the classpath:

Reflections reflections = new Reflections("mydir", new ResourcesScanner());
Set<String> resources = reflections.getResources(Pattern.compile(".*"));
System.out.println(resources); // [mydir/a.json, ...
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • The fragment didn't immediately worked but it led me to the `jboss-vfs' framework I was looking for. I rather not include yet another framework. Including yet another jboss framework feels cleaner. And is also easy to use. – JStefan Apr 17 '19 at 11:43
1

The answer from @Karol finally led me to the RedHat jboss-vfs framework I was looking for. So I included the following maven artefact in my pom:

    <dependency>
        <groupId>org.jboss</groupId>
        <artifactId>jboss-vfs</artifactId>
    </dependency>

Then I do the following:

URL dirUrl = getClass().getResource("/mydir");
VirtualFile vfDir = VFS.getChild(dirUrl.toURI());
List<VirtualFile> jsonVFs = vfDir.getChildren(new VirtualFileFilter() {
    @Override
    public boolean accepts(VirtualFile file) {
        return file.getName().toLowerCase().endsWith(".json");
    }
});
for (int i = 0; i < jsonVFs.size(); i++) {
    VirtualFile vf = jsonVFs.get(i);
    File f = vf.getPhysicalFile();
    MyClass fromJson = objectMapper.readValue(f, MyClass.class); 
    // Do something with it..
}

Exactly what I needed.

JStefan
  • 149
  • 1
  • 2
  • 11