use of com.github.mustachejava.Mustache in project elasticsearch by elastic.
the class MustacheTests method testBasics.
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());
}
use of com.github.mustachejava.Mustache in project elasticsearch by elastic.
the class CustomMustacheFactoryTests method testDefaultEncoder.
public void testDefaultEncoder() {
final ScriptEngineService engine = new MustacheScriptEngineService();
final Map<String, String> params = singletonMap(Script.CONTENT_TYPE_OPTION, PLAIN_TEXT_MIME_TYPE);
Mustache script = (Mustache) engine.compile(null, "{\"field\": \"{{value}}\"}", params);
CompiledScript compiled = new CompiledScript(INLINE, null, MustacheScriptEngineService.NAME, script);
ExecutableScript executable = engine.executable(compiled, singletonMap("value", "a \"value\""));
BytesReference result = (BytesReference) executable.run();
assertThat(result.utf8ToString(), equalTo("{\"field\": \"a \"value\"\"}"));
}
use of com.github.mustachejava.Mustache in project camel by apache.
the class MustacheEndpoint method onExchange.
@Override
protected void onExchange(Exchange exchange) throws Exception {
String newResourceUri = exchange.getIn().getHeader(MUSTACHE_RESOURCE_URI, String.class);
if (newResourceUri == null) {
// Get Mustache
String newTemplate = exchange.getIn().getHeader(MUSTACHE_TEMPLATE, String.class);
Mustache newMustache;
if (newTemplate == null) {
newMustache = getOrCreateMustache();
} else {
newMustache = createMustache(new StringReader(newTemplate), "mustache:temp#" + newTemplate.hashCode());
exchange.getIn().removeHeader(MUSTACHE_TEMPLATE);
}
// Execute Mustache
Map<String, Object> variableMap = ExchangeHelper.createVariableMap(exchange);
StringWriter writer = new StringWriter();
newMustache.execute(writer, variableMap);
writer.flush();
// Fill out message
Message out = exchange.getOut();
out.setBody(writer.toString());
out.setHeaders(exchange.getIn().getHeaders());
out.setAttachments(exchange.getIn().getAttachments());
} else {
exchange.getIn().removeHeader(MustacheConstants.MUSTACHE_RESOURCE_URI);
MustacheEndpoint newEndpoint = getCamelContext().getEndpoint(MUSTACHE_ENDPOINT_URI_PREFIX + newResourceUri, MustacheEndpoint.class);
newEndpoint.onExchange(exchange);
}
}
use of com.github.mustachejava.Mustache in project error-prone by google.
the class BugPatternFileGenerator method processLine.
@Override
public boolean processLine(String line) throws IOException {
BugPatternInstance pattern = new Gson().fromJson(line, BugPatternInstance.class);
result.add(pattern);
// replace spaces in filename with underscores
Path checkPath = Paths.get(pattern.name.replace(' ', '_') + ".md");
try (Writer writer = Files.newBufferedWriter(outputDir.resolve(checkPath), UTF_8)) {
// load side-car explanation file, if it exists
Path sidecarExplanation = explanationDir.resolve(checkPath);
if (Files.exists(sidecarExplanation)) {
if (!pattern.explanation.isEmpty()) {
throw new AssertionError(String.format("%s specifies an explanation via @BugPattern and side-car", pattern.name));
}
pattern.explanation = new String(Files.readAllBytes(sidecarExplanation), UTF_8).trim();
}
// Construct an appropriate page for this {@code BugPattern}. Include altNames if
// there are any, and explain the correct way to suppress.
ImmutableMap.Builder<String, Object> templateData = ImmutableMap.<String, Object>builder().put("category", pattern.category).put("severity", pattern.severity).put("name", pattern.name).put("summary", pattern.summary.trim()).put("altNames", Joiner.on(", ").join(pattern.altNames)).put("explanation", pattern.explanation.trim());
if (baseUrl != null) {
templateData.put("baseUrl", baseUrl);
}
if (generateFrontMatter) {
Map<String, String> frontmatterData = ImmutableMap.<String, String>builder().put("title", pattern.name).put("summary", pattern.summary).put("layout", "bugpattern").put("category", pattern.category.toString()).put("severity", pattern.severity.toString()).build();
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
Writer yamlWriter = new StringWriter();
yamlWriter.write("---\n");
yaml.dump(frontmatterData, yamlWriter);
yamlWriter.write("---\n");
templateData.put("frontmatter", yamlWriter.toString());
}
if (pattern.documentSuppression) {
String suppression;
switch(pattern.suppressibility) {
case SUPPRESS_WARNINGS:
suppression = String.format("Suppress false positives by adding an `@SuppressWarnings(\"%s\")` " + "annotation to the enclosing element.", pattern.name);
break;
case CUSTOM_ANNOTATION:
if (pattern.customSuppressionAnnotations.length == 1) {
suppression = String.format("Suppress false positives by adding the custom suppression annotation " + "`@%s` to the enclosing element.", pattern.customSuppressionAnnotations[0]);
} else {
suppression = String.format("Suppress false positives by adding one of these custom suppression " + "annotations to the enclosing element: %s", COMMA_JOINER.join(Lists.transform(Arrays.asList(pattern.customSuppressionAnnotations), ANNOTATE_AND_CODIFY)));
}
break;
case UNSUPPRESSIBLE:
suppression = "This check may not be suppressed.";
break;
default:
throw new AssertionError(pattern.suppressibility);
}
templateData.put("suppression", suppression);
}
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile("com/google/errorprone/resources/bugpattern.mustache");
mustache.execute(writer, templateData.build());
if (pattern.generateExamplesFromTestCases) {
// Example filename must match example pattern.
List<Path> examplePaths = new ArrayList<>();
Filter<Path> filter = new ExampleFilter(pattern.className.substring(pattern.className.lastIndexOf('.') + 1));
findExamples(examplePaths, exampleDirBase, filter);
List<ExampleInfo> exampleInfos = FluentIterable.from(examplePaths).transform(new PathToExampleInfo(pattern.className)).toSortedList(new Comparator<ExampleInfo>() {
@Override
public int compare(ExampleInfo first, ExampleInfo second) {
return first.name().compareTo(second.name());
}
});
Collection<ExampleInfo> positiveExamples = Collections2.filter(exampleInfos, IS_POSITIVE);
Collection<ExampleInfo> negativeExamples = Collections2.filter(exampleInfos, not(IS_POSITIVE));
if (!exampleInfos.isEmpty()) {
writer.write("\n----------\n\n");
if (!positiveExamples.isEmpty()) {
writer.write("### Positive examples\n");
for (ExampleInfo positiveExample : positiveExamples) {
writeExample(positiveExample, writer);
}
}
if (!negativeExamples.isEmpty()) {
writer.write("### Negative examples\n");
for (ExampleInfo negativeExample : negativeExamples) {
writeExample(negativeExample, writer);
}
}
}
}
}
return true;
}
use of com.github.mustachejava.Mustache in project Anserini by castorini.
the class TweetServlet method doGet.
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getRequestURI().equals("/search")) {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/html");
request.setCharacterEncoding("UTF-8");
Query q;
try {
q = new QueryParser(StatusField.TEXT.name, TweetSearcher.ANALYZER).parse(request.getParameter("query"));
try {
reader = DirectoryReader.open(TweetSearcher.indexWriter, true, true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
IndexReader newReader = DirectoryReader.openIfChanged((DirectoryReader) reader, TweetSearcher.indexWriter, true);
if (newReader != null) {
reader.close();
reader = newReader;
}
IndexSearcher searcher = new IndexSearcher(reader);
int topN;
if (request.getParameter("top") != null) {
topN = Integer.parseInt(request.getParameter("top"));
} else {
// TODO configurable, default(parameter unspecified in url) topN = 20
topN = 20;
}
TopScoreDocCollector collector = TopScoreDocCollector.create(topN);
searcher.search(q, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
TweetHits tweetHits = new TweetHits(request.getParameter("query"), hits.length);
for (int i = 0; i < hits.length; ++i) {
int docId = hits[i].doc;
Document d = searcher.doc(docId);
tweetHits.addHit(i, String.valueOf(d.get(StatusField.ID.name)));
}
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile(MustacheTemplatePath);
mustache.execute(response.getWriter(), tweetHits).flush();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
Aggregations