views:

262

answers:

2

I've been using FreeMarker for a little while now, but there's one glaring piece of functionality that is either missing or I just can't figure out (I hope the latter!). If you pass cfg.getTemplate() an absolute path, it just doesn't work. I know you can specify a template directory, but I can't afford to do that, my use case could deal with files in any directory. Is there any way to set FreeMarker to render absolute paths the way any user would expect?

A: 
ChssPly76
Thanks for the answer. I ended up just changing the template directory every time, but creating a custom FileTemplateLoader would be the more correct way to deal with it.I certainly understand why this would be a security hole if using it to generate web pages, but if it's in a program normal users are running, it seems to me standard linux permissions should be a good enough preventative measure, no?
dimo414
As long as your permissions are set up adequately, yes, you should be fine. I still can't imagine why you would use an absolute path, though... it seems like you'd want to either keep template under some common (non-root) folder or, if they are customizable per user, somewhere relative to user's home. But I'm sure you have your reasons - good luck with your implementation.
ChssPly76
+1  A: 

I had to use the absolute path because the templating is happening in an Ant script and the templates are on the file system and discovered with an Ant fileset. I guess these are quite some unique requirements...

Anyway,for the posterity (as long as SO is up), here's a solution that works:

public class TemplateAbsolutePathLoader implements TemplateLoader {

    public Object findTemplateSource(String name) throws IOException {
        File source = new File(name);
        return source.isFile() ? source : null;
    }

    public long getLastModified(Object templateSource) {
        return ((File) templateSource).lastModified();
    }

    public Reader getReader(Object templateSource, String encoding)
            throws IOException {
        if (!(templateSource instanceof File)) {
            throw new IllegalArgumentException("templateSource is a: " + templateSource.getClass().getName());
        }
        return new InputStreamReader(new FileInputStream((File) templateSource), encoding);
    }

    public void closeTemplateSource(Object templateSource) throws IOException {
        // Do nothing.
    }

}

and the initialization is:

public String generate(File template) {

    Configuration cfg = new Configuration();
    cfg.setTemplateLoader(new TemplateAbsolutePathLoader());
    Template tpl = cfg.getTemplate(template.getAbsolutePath());

    // ...
}
Vladimir
Thank you very much. I'm no longer developing this project, so I can't test this, but I'm sure anyone else with my same question will appreciate this.
dimo414