-
-
Save spg/4723979 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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