Fagner Brack
Fagner Brack

Reputation: 2403

List files from inside a packaged war

I have an .ear, a .jar and a .war packages. I am reading my servlet classes dinamically by inspecting the file system and registering the mappings.

The thing is it works for development, I am able to read the directories and the proper file names do be able to create the mappings. The problem is that if I package my ear It does not work:

I have solved the directory checking issue by detecting an end path that does not end with an extension (for my purpose such verification is enough), but I am still not able to list the files from a given path.

Given this situation I have the question:

How can I list the file names at runtime from a package .war?

The current code:

private void addAllFiles( File dir, ArrayList<ConventionPath> list ) {
    for ( File file : dir.listFiles() ) { // dir.listFiles() comes null here =/
        String absolutePath = file.getAbsolutePath();

        boolean isActionDir = ConventionFiles.isActionDir( absolutePath, fileSeparator );
        boolean isActionFile = ConventionFiles.isActionFile( absolutePath );

        if ( isActionDir ) {
            addAllFiles( file, list );
        }

        if ( isActionDir || isActionFile ) {
            ConventionPath conventionPath =
                new ConventionPath( absolutePath, fileSeparator );
            list.add( conventionPath );
        }
    }
}

Upvotes: 1

Views: 2306

Answers (1)

Fagner Brack
Fagner Brack

Reputation: 2403

Now I made it work.

Instead of accessing the file via the file system I used the servlet context (I suppose this is the correct way to go):

URL root = context.getResource( "/WEB-INF/classes/com/package/" );

// /default-host/WEB-INF/classes/
String rootPath = root.getPath();

// /WEB-INF/classes/
rootPath = rootPath.substring( rootPath.indexOf( "/WEB-INF" ), rootPath.length() );

And then recursively I get the information I want from the resources:

Set<String> resourcesPath = context.getResourcePaths( rootPath );

Upvotes: 5

Related Questions