Skip to content

Instantly share code, notes, and snippets.

@spg
Forked from christiangoudreau/gist:4723948
Created February 6, 2013 16:55
Show Gist options
  • Save spg/4723979 to your computer and use it in GitHub Desktop.
Save spg/4723979 to your computer and use it in GitHub Desktop.
public class VelocityWrapper {
private final Template template;
private final VelocityContext velocityContext;
private VelocityWrapper(
VelocityEngine velocityEngine,
String templateLocation,
VelocityContext velocityContext) {
this.template = velocityEngine.getTemplate(templateLocation);
this.velocityContext = velocityContext;
generate();
}
public String generate() {
StringWriter writer = new StringWriter();
template.merge(velocityContext, writer);
return writer.toString();
}
public static class Builder {
private final VelocityEngine velocityEngine;
private final String templateLocation;
private final VelocityContext velocityContext = new VelocityContext();
@Inject
public Builder(VelocityEngine velocityEngine, @Assisted String templateLocation) {
this.velocityEngine = velocityEngine;
this.templateLocation = templateLocation;
}
public put(String key, String value) {
velocityContext.put(key, value);
return this;
}
public VelocityWrapper build() {
return new VelocityWrapper(velocityEngine, templateLocation, velocityContext);
}
}
}
Then:
Builder builder = velocityWrapperBuilderFactory.create("path/to/my/velocity/file.vm");
builder.put("X", "Y");
builder.build(); // This will build and executed the velocity wrapper.
// Builder is consumed, a builder by definition shouldn't be reused and another one should be created through the factory.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment