Christoph Wolf
Christoph Wolf

Reputation: 115

Loading properties file in GWT on Tomcat

I know there are lots of similar questions out there, but none of which that helped. We have a GWT application running on a tomcat server, which is loading a properties file for database connections.

The code to load the properties file looks like following:

private static final String DB_CONF = "com/x/monitorui/server/configuration.properties";
Properties properties = new Properties();
properties.load(DatabaseConnection.class.getClass().getResourceAsStream(DB_CONF));

This works fine whilst developing locally on the Jetty, but not when deployed on the Tomcat. It can't seem to find the resource. The file itself is located in war/WEB-INF/classes/com/x/monitorui/server, the class trying to load it is located in the same package.

Upvotes: 1

Views: 2969

Answers (2)

Renato
Renato

Reputation: 13690

If you properties file is in the same directory as the class you use to call "getResourceAsStream(..)", then you just need the name of the file, without the absolute path to it. For example, supposing you have:

// notice that your build should copy this from the source directory to your /WEB-INF/classes/.... directory automatically so you can do a clean build
com/x/monitorui/server/configuration.properties

and a class located at the same directory, ie. in package:

com.x.monitorui.server.DatabaseConnection

then you can simply call

Properties properties = new Properties();
properties.load(DatabaseConnection.class.getResourceAsStream("configuration.properties"));

Upvotes: 1

Andreas
Andreas

Reputation: 2301

Wo do nearly the same here with "Packager.class" as a class in the same directory; The idea here is to find the path via the class path, which works on tomcat:

final ClassPool pool = ClassPool.getDefault( );
final Class<?> baseClass = Packager.class;
pool.insertClassPath( new ClassClassPath( baseClass ) );

final URL url = pool.find( baseClass.getName( ) );

String pathToBaseClass = url.toURI( ).getPath( );
String baseDir = pathToBaseClass.substring( 0, pathToBaseClass.indexOf( "com" ) - 1 );

Upvotes: 1

Related Questions