Friday, February 4, 2011

Equinox: Reading External File

I was looking for a way to read a file from the current directory. The business scenario is: We are opening a socket connection from an equinox bundle.
Currently the port for the socket communication is hard coded. In a rare scenario it’s possible that the port will be already in use. We should be able to provide the port from outside the execution environment. 

One way is to pass it through the launch arguments. But sometimes getting hold of config.ini or starting the application from console may not be possible. (In case of custom launchers)

Second option is to read the port from an external file. We can use following to pick the file:

this.getClass().getProtectionDomain().getCodeSource().getLocation() - Gets the current location of the bundle.

If we have kept the file with port at the same location then read the file using:
URL url = new URL(this.getClass().getProtectionDomain().getCodeSource().getLocation()
+ "/../messages.properties");
InputStream inputStream = url.openStream();
Properties properties = new Properties();
try {
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace(); 
}
socketport=properties.getProperty("SocketPort"));

Not sure if that's the best way. But surprisingly I didn't find any other way to read a file from the current path kept outside the bundle; and even this is specific to Equinox and not available in other OSGi implementations. If anyone is aware of any other way then do let me know

No comments:

Post a Comment