当前位置: 首页>>代码示例>>Java>>正文


Java Mustache类代码示例

本文整理汇总了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()
    );
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:18,代码来源:MustacheTests.java

示例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);
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:24,代码来源:CustomMustacheFactory.java

示例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;
}
 
开发者ID:quanticc,项目名称:ugc-bot-redux,代码行数:19,代码来源:NuclearService.java

示例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;
}
 
开发者ID:tokuhirom,项目名称:avans-mustache,代码行数:24,代码来源:MustacheView.java

示例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();
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:17,代码来源:MustacheScriptEngineService.java

示例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);
    }
}
 
开发者ID:syndesisio,项目名称:syndesis,代码行数:24,代码来源:DefaultProjectGenerator.java

示例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;
}
 
开发者ID:Stwissel,项目名称:vertx-sfdc-platformevents,代码行数:32,代码来源:RestConsumer.java

示例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();

}
 
开发者ID:Stwissel,项目名称:vertx-sfdc-platformevents,代码行数:17,代码来源:JsonExperiments.java

示例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();
    }
}
 
开发者ID:minijax,项目名称:minijax,代码行数:18,代码来源:MinijaxMustacheWriter.java

示例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();
    }
}
 
开发者ID:humio,项目名称:dcos2humio,代码行数:25,代码来源:ExecutorApplication.java

示例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();
}
 
开发者ID:willh,项目名称:lambda-helloworld-config,代码行数:23,代码来源:HelloWorldMicroservice.java

示例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;
}
 
开发者ID:baratine,项目名称:baratine,代码行数:27,代码来源:ViewMustache.java

示例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();

}
 
开发者ID:o19s,项目名称:elasticsearch-learning-to-rank,代码行数:20,代码来源:MustacheUtils.java

示例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);
    }
}
 
开发者ID:syndesisio,项目名称:syndesis-rest,代码行数:24,代码来源:DefaultProjectGenerator.java

示例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());
}
 
开发者ID:Nike-Inc,项目名称:cerberus-lifecycle-cli,代码行数:29,代码来源:ConsulConfigGenerator.java


注:本文中的com.github.mustachejava.Mustache类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。