[stringtemplate-interest] Suggestion for loadTemplateFromBeneathRootDirOrCLASSPATH
Dobes Vandermeer
dobesv at gmail.com
Fri Feb 22 00:31:39 PST 2008
I've made a subclass of StringTemplateGroup so that I can make it
behave in a way more consistent with the documentation. The docs say
that if you give an absolute path to the constructor, it'll only look
in that path, otherwise it looks on the classpath. In reality, if you
pass ANY non-null path and uses that as a filesystem path and ignores
the classpath.
What I really wanted was to path a relative path that was searched on
the classpath, so I subclassed it and made this version of
loadTemplateFromBeneathRootDirOrCLASSPATH.
The main difference is that it only treats a path as a filesystem path
if it's an absolute path, otherwise it searches the classpath. Giving
a path allows you to specify the root package in your classpath where
the files reside. This creates a bit of consistency with
CommonGroupLoader, which also searches paths in the classpath with a
path prefix.
protected StringTemplate
loadTemplateFromBeneathRootDirOrCLASSPATH(String fileName) {
StringTemplate template = null;
String name = getTemplateNameFromFileName(fileName);
// if no rootDir, try to load as a resource in CLASSPATH
if(rootDir != null) fileName = rootDir + "/" + fileName;
if ( rootDir==null || !(new File(rootDir).isAbsolute())) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
InputStream is = cl.getResourceAsStream(fileName);
if ( is==null ) {
cl = this.getClass().getClassLoader();
is = cl.getResourceAsStream(fileName);
}
if ( is==null ) {
return null;
}
BufferedReader br = null;
try {
br = new BufferedReader(getInputStreamReader(is));
template = loadTemplate(name, br);
}
catch (IOException ioe) {
error("Problem reading template file: "+fileName,ioe);
}
finally {
if ( br!=null ) {
try {
br.close();
}
catch (IOException ioe2) {
error("Cannot close template file: "+fileName, ioe2);
}
}
}
return template;
}
// load via rootDir
template = loadTemplate(name, fileName);
return template;
}
More information about the stringtemplate-interest
mailing list