Friday, April 22, 2011

Properties file troubles

I stumbled over a stupid properties file gotcha the other day trying to get a Spring META-INF/spring.schemas file working. Spring uses this file to translate an XML Schema schemaLocation into the name of a classpath resource. This allows Spring to load the schema directly from the classpath instead of downloading it from a remote server which might not be reachable from your deployment environment (e.g. because of firewalls). So for instance, suppose you have the following in your XML:
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:demo="http://www.ervacon.com/schema/demo"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.ervacon.com/schema/demo http://www.ervacon.com/schema/demo/demo.xsd">
If you combine this with the following META-INF/spring.schemas file, Spring will load demo.xsd directly from the classpath without even trying to access http://www.ervacon.com/schema/demo/demo.xsd:
http\://www.ervacon.com/schema/demo/demo.xsd=demo.xsd
The key thing to notice in the properties file is the escaping backslash before the colon! This is necessary because a colon is a valid delimiter in a Java properties file:
public static void main(String[] args) throws IOException {
 StringReader propsIn = new StringReader("http://my.server.com/foo.xsd=foo.xsd");
 
 Properties props = new Properties();
 props.load(propsIn);

 for (String propName : props.stringPropertyNames()) {
  System.out.println(propName + " --> " + props.getProperty(propName));
  // prints: http --> //my.server.com/foo.xsd=foo.xsd
 }
}
Keep in mind that all colons need to be escaped! So don't forget the colon in front of the port number:
http\://my.server.com\:8080/foo.xsd=foo.xsd
Doh!

No comments:

Post a Comment