當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。