本文整理汇总了Java中com.github.mustachejava.Mustache类的典型用法代码示例。如果您正苦于以下问题:Java Mustache类的具体用法?Java Mustache怎么用?Java Mustache使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Mustache类属于com.github.mustachejava包,在下文中一共展示了Mustache类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testBasics
import com.github.mustachejava.Mustache; //导入依赖的package包/类
public void testBasics() {
String template = "GET _search {\"query\": " + "{\"boosting\": {"
+ "\"positive\": {\"match\": {\"body\": \"gift\"}},"
+ "\"negative\": {\"term\": {\"body\": {\"value\": \"solr\"}"
+ "}}, \"negative_boost\": {{boost_val}} } }}";
Map<String, Object> params = Collections.singletonMap("boost_val", "0.2");
Mustache mustache = (Mustache) engine.compile(null, template, Collections.emptyMap());
CompiledScript compiledScript = new CompiledScript(INLINE, "my-name", "mustache", mustache);
ExecutableScript result = engine.executable(compiledScript, params);
assertEquals(
"Mustache templating broken",
"GET _search {\"query\": {\"boosting\": {\"positive\": {\"match\": {\"body\": \"gift\"}},"
+ "\"negative\": {\"term\": {\"body\": {\"value\": \"solr\"}}}, \"negative_boost\": 0.2 } }}",
((BytesReference) result.run()).utf8ToString()
);
}
示例2: extractVariableName
import com.github.mustachejava.Mustache; //导入依赖的package包/类
/**
* At compile time, this function extracts the name of the variable:
* {{#toJson}}variable_name{{/toJson}}
*/
protected static String extractVariableName(String fn, Mustache mustache, TemplateContext tc) {
Code[] codes = mustache.getCodes();
if (codes == null || codes.length != 1) {
throw new MustacheException("Mustache function [" + fn + "] must contain one and only one identifier");
}
try (StringWriter capture = new StringWriter()) {
// Variable name is in plain text and has type WriteCode
if (codes[0] instanceof WriteCode) {
codes[0].execute(capture, Collections.emptyList());
return capture.toString();
} else {
codes[0].identity(capture);
return capture.toString();
}
} catch (IOException e) {
throw new MustacheException("Exception while parsing mustache function [" + fn + "] at line " + tc.line(), e);
}
}
示例3: announce
import com.github.mustachejava.Mustache; //导入依赖的package包/类
private String announce(NuclearStream stream, List<String> responseList, Map<String, String> context) {
String response = responseList.get(RandomUtils.nextInt(0, responseList.size()));
if (context == null) {
announcePresenter.announce(stream.getPublisher().getId(), response, true, false);
} else {
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile(new StringReader(response), "response");
try {
StringWriter writer = new StringWriter();
mustache.execute(writer, context).flush();
response = writer.toString();
announcePresenter.announce(stream.getPublisher().getId(), response, true, false);
} catch (IOException e) {
log.warn("Could not create response", e);
}
}
return response;
}
示例4: render
import com.github.mustachejava.Mustache; //导入依赖的package包/类
/**
* Create a response object by mustache template engine.
*
* @param template
* @param context
* @return
*/
public WebResponse render(@NonNull HTMLFilterProvider controller,
@NonNull String template,
Object context) {
final Mustache mustache = mustacheFactory.compile(template);
final StringWriter writer = new StringWriter();
mustache.execute(writer, context);
String bodyString = writer.toString();
bodyString = controller.filterHTML(bodyString);
final byte[] body = bodyString.getBytes(StandardCharsets.UTF_8);
final ByteArrayResponse res = new ByteArrayResponse(200, body);
res.setContentType("text/html; charset=utf-8");
res.setContentLength(body.length);
return res;
}
示例5: run
import com.github.mustachejava.Mustache; //导入依赖的package包/类
@Override
public Object run() {
final BytesStreamOutput result = new BytesStreamOutput();
try (UTF8StreamWriter writer = utf8StreamWriter().setOutput(result)) {
// crazy reflection here
SpecialPermission.check();
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
((Mustache) template.compiled()).execute(writer, vars);
return null;
});
} catch (Exception e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Error running {}", template), e);
throw new GeneralScriptException("Error running " + template, e);
}
return result.bytes();
}
示例6: compile
import com.github.mustachejava.Mustache; //导入依赖的package包/类
private Mustache compile(ProjectGeneratorProperties generatorProperties, String template, String name) throws IOException {
String overridePath = generatorProperties.getTemplates().getOverridePath();
URL resource = null;
if (!Strings.isEmpty(overridePath)) {
resource = getClass().getResource("templates/" + overridePath + "/" + template);
}
if (resource == null) {
resource = getClass().getResource("templates/" + template);
}
if (resource == null) {
throw new IllegalArgumentException(
String.format("Unable to find te required template (overridePath=%s, template=%s)"
, overridePath
, template
)
);
}
try (InputStream stream = resource.openStream()) {
return mf.compile(new InputStreamReader(stream, StandardCharsets.UTF_8), name);
}
}
示例7: transformBody
import com.github.mustachejava.Mustache; //导入依赖的package包/类
/**
* Turns the JsonObject that came over the wire into a buffer object to be
* used in the HTTP Post. Special twist: if configured the JSONObject is run
* through a {{Mustache}} transformation, so the result can be anything
* JSON, HTML, XML, PlainText, WebForm etc. Allows ultimate flexibility when
* one knows Mustache
*
* @param Json
* Object with incoming payload
* @return a Buffer object to be pasted
*/
private Buffer transformBody(final JsonObject body) {
Buffer result = null;
if (this.needsTransformation()) {
final Mustache mustache = this.getMustache();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final PrintWriter pw = new PrintWriter(out);
try {
mustache.execute(pw, Utils.mappifyJsonObject(body)).flush();
pw.close();
result = Buffer.buffer(out.toByteArray());
} catch (final IOException e) {
this.logger.error(e);
// Get back the unchanged body
result = body.toBuffer();
}
} else {
result = body.toBuffer();
}
return result;
}
示例8: test1
import com.github.mustachejava.Mustache; //导入依赖的package包/类
private void test1() throws IOException {
// final JsonObject scope = this.getScope();
final JsonObject x = this.getScope();
// Map<String, Object> scope = x.getMap();
final Map<String, Object> scope = this.mappifyJsonObject(x);
// Map<String, Object> scope = new HashMap<>();
// scope.put("YesNo", true);
// scope.put("answer", 42);
final Mustache m = this.getTemplate();
final Writer w = this.getWriter();
w.append(x.encodePrettily());
m.execute(w, scope);
w.close();
}
示例9: writeTo
import com.github.mustachejava.Mustache; //导入依赖的package包/类
@Override
public void writeTo(
final View page,
final Class<?> type,
final Type genericType,
final Annotation[] annotations,
final MediaType mediaType,
final MultivaluedMap<String, Object> httpHeaders,
final OutputStream entityStream)
throws IOException {
final Mustache mustache = mf.compile("templates/" + page.getTemplateName() + ".mustache");
try (final OutputStreamWriter writer = new OutputStreamWriter(entityStream)) {
mustache.execute(writer, page.getModel()).flush();
}
}
示例10: main
import com.github.mustachejava.Mustache; //导入依赖的package包/类
public static void main(String[] args) {
System.out.println("Starting executor");
if (new File("config").mkdir()) {
System.out.println("Created config directory");
}
MustacheFactory mustacheFactory = new DefaultMustacheFactory();
final Mustache filebeatMustache = mustacheFactory.compile("filebeat.yaml.mustache");
final Mustache metricbeatMustache = mustacheFactory.compile("metricbeat.yaml.mustache");
try {
MesosExecutorDriver driver = new MesosExecutorDriver(new HumioExecutor(filebeatMustache, metricbeatMustache));
final Protos.Status status = driver.run();
System.out.println("status = " + status);
if (status.equals(Protos.Status.DRIVER_STOPPED)) {
System.exit(0);
} else {
System.err.println("Error: " + status);
}
} catch (Exception e) {
e.printStackTrace();
}
}
示例11: handleRequest
import com.github.mustachejava.Mustache; //导入依赖的package包/类
public String handleRequest(String name, Context context) {
String responseLanguage = Optional.ofNullable(System.getenv("language")).orElse(DEFAULT_LANGUAGE);
Mustache mustache = new DefaultMustacheFactory().compile("hellopage.mustache");
String envVersion = Optional.ofNullable(context.getFunctionVersion()).orElse("no-alias");
String functionName = Optional.ofNullable(context.getFunctionName()).orElse("default-name");
String arnName = Optional.ofNullable(context.getInvokedFunctionArn()).orElse("default-arn");
String response = "Hello " + name + " from version: " + envVersion + " of " + functionName + " with arn: " + arnName;
HelloResponse responseData = new HelloResponse(responseLanguage, response);
StringWriter stringWriter = new StringWriter();
try {
mustache.execute(stringWriter, responseData).flush();
} catch (IOException e) {
stringWriter.append("Failed to execute mustache template and flush output");
}
return stringWriter.toString();
}
示例12: render
import com.github.mustachejava.Mustache; //导入依赖的package包/类
@Override
public boolean render(RequestWeb req, View view)
{
String viewName = view.name();
if (! viewName.endsWith(".mustache")) {
return false;
}
try {
Mustache mustache = _factory.compile(viewName);
req.type("text/html; charset=utf-8");
Writer writer = req.writer();
mustache.execute(writer, view.map()).flush();
req.ok();
}
catch (Exception e) {
req.fail(e);
}
return true;
}
示例13: execute
import com.github.mustachejava.Mustache; //导入依赖的package包/类
public static String execute(Mustache template, Map<String, Object> params) {
final StringWriter writer = new StringWriter();
try {
// crazy reflection here
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(SPECIAL_PERMS);
}
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
template.execute(writer, params);
return null;
});
} catch (Exception e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Error running {}", template), e);
throw new IllegalArgumentException("Error running " + template, e);
}
return writer.toString();
}
示例14: compile
import com.github.mustachejava.Mustache; //导入依赖的package包/类
private Mustache compile(ProjectGeneratorProperties generatorProperties, String template, String name) throws IOException {
String overridePath = generatorProperties.getTemplates().getOverridePath();
URL resource = null;
if (!Strings.isEmpty(overridePath)) {
resource = getClass().getResource("templates/" + overridePath + "/" + template);
}
if (resource == null) {
resource = getClass().getResource("templates/" + template);
}
if (resource == null) {
throw new IllegalArgumentException(
String.format("Unable to find te required template (overridePath=%s, template=%s)"
, overridePath
, template
)
);
}
try (InputStream stream = resource.openStream()) {
return mf.compile(new InputStreamReader(stream, UTF_8), name);
}
}
示例15: generate
import com.github.mustachejava.Mustache; //导入依赖的package包/类
/**
* Generates a configuration object that contains the supplied gossip encryption token,
* acl master token, and string representations of the full JSON configuration for Consul.
*/
public ConsulConfiguration generate(final String datacenter,
final String aclMasterToken,
final String gossipEncryptionToken) {
final ConsulConfigurationInput input = new ConsulConfigurationInput()
.setAclMasterToken(aclMasterToken)
.setGossipEncryptionToken(gossipEncryptionToken)
.setDatacenter(datacenter);
final Mustache serverTemplateCompiler = mustacheFactory.compile(serverTemplatePath);
final Mustache clientTemplateCompiler = mustacheFactory.compile(clientTemplatePath);
final StringWriter serverConfigWriter = new StringWriter();
final StringWriter clientConfigWriter = new StringWriter();
try {
serverTemplateCompiler.execute(serverConfigWriter, input).flush();
clientTemplateCompiler.execute(clientConfigWriter, input).flush();
} catch (IOException ioe) {
throw new ConfigGenerationException("Failed to generate Consul configuration!", ioe);
}
return new ConsulConfiguration()
.setInput(input)
.setServerConfiguration(serverConfigWriter.toString())
.setClientConfiguration(clientConfigWriter.toString());
}