Skip to content

Instantly share code, notes, and snippets.

@christiangoudreau
Last active December 12, 2015 05:48
Show Gist options
  • Save christiangoudreau/4723948 to your computer and use it in GitHub Desktop.
Save christiangoudreau/4723948 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;
}
private 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 String build() {
return new VelocityWrapper(velocityEngine, templateLocation, velocityContext).generate();
}
}
}
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