views:

265

answers:

1

I have a very simple Velocity application that works on Linux and MacOS and fails on Windows. The problem is with the resource locations. I just give it "/" to allow it to recognize file system paths, but on Windows that fails to work for "c:/....." pathnames. I suspect that there is a simpler solution to this, but what?

 velocityEngine = new VelocityEngine();
    // we want to use absolute paths.
    velocityEngine.setProperty("file.resource.loader.path", "/");
    try {
      velocityEngine.init();
    } catch (Exception e) {
      throw new MojoExecutionException("Unable to initialize velocity", e);
    }
A: 

I put velocity templates in the classpath and read them in with Class.getResourceAsStream.

It should go something like this:

// stuff.velocity is a file that lives directly under WEB-INF/classes 
// that contains the velocity template
InputStream inputStream = Class.getResourceAsStream("/stuff.velocity"); 
String template = readTemplateFromFile(inputStream);
VelocityContext context = new VelocityContext( );
// insert any parameters into context now
Writer writer = new StringWriter();
Velocity.evaluate( context, writer, "LOG", template );

and now writer should hold the result of applying the parameters to the template.

Will Glass' comment below looks like a good thing to check out. When I was using velocity it was to generate notification emails, there were not a lot of them and I had the work farmed out to a separate thread so performance was not a big deal at the time.

Nathan Hughes
How do you configure the engine to do that, or, perhaps, I should ask, what is the pathname syntax that causes it to do that?
bmargulies
hope my edits clarify that.
Nathan Hughes
Using Velocity.evaluate() is a bug performance hit as it doesn't support Velocity's template caching mechanism. If you put the templates in the classpath, use ClasspathResourceLoader. For arbitrary file locations, use a FileResourceLoader.
Will Glass
If you add an answer to this question with an example of this then I'll vote for it.
Nathan Hughes