blob: f0ba62726794453d0fc2e2c3b5f476e8c0830134 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.file;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.runtime.RuntimeConstants;
import org.slf4j.helpers.NOPLogger;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import static com.yahoo.yolean.Exceptions.uncheck;
/**
* Uses the Velocity engine to render a template, to and from both String and Path objects.
*
* @author hakonhall
* @author jonmv
*/
public class Template {
static {
Velocity.addProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, NOPLogger.NOP_LOGGER);
Velocity.init();
}
private final VelocityContext velocityContext = new VelocityContext();
private final String template;
private Template(String template) {
this.template = template;
}
public static Template at(Path templatePath) {
return of(uncheck(() -> new String(Files.readAllBytes(templatePath))));
}
public static Template of(String template) {
return new Template(template);
}
public Template set(String name, Object value) {
velocityContext.put(name, value);
return this;
}
public FileWriter getFileWriterTo(Path destinationPath) {
return new FileWriter(destinationPath, this::render);
}
public String render() {
StringWriter writer = new StringWriter();
Velocity.evaluate(velocityContext, writer, "Template", template);
return writer.toString();
}
}
|