use of com.github.mustachejava.MustacheFactory in project elasticsearch by elastic.
the class MustacheScriptEngineService method compile.
/**
* Compile a template string to (in this case) a Mustache object than can
* later be re-used for execution to fill in missing parameter values.
*
* @param templateSource a string representing the template to compile.
* @return a compiled template object for later execution.
* */
@Override
public Object compile(String templateName, String templateSource, Map<String, String> params) {
final MustacheFactory factory = createMustacheFactory(params);
Reader reader = new FastStringReader(templateSource);
return factory.compile(reader, "query-template");
}
use of com.github.mustachejava.MustacheFactory 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.MustacheFactory 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);
}
}
use of com.github.mustachejava.MustacheFactory in project dropwizard by dropwizard.
the class MustacheViewRenderer method render.
@Override
public void render(View view, Locale locale, OutputStream output) throws IOException {
try {
final MustacheFactory mustacheFactory = useCache ? factories.get(view.getClass()) : createNewMustacheFactory(view.getClass());
final Mustache template = mustacheFactory.compile(view.getTemplateName());
final Charset charset = view.getCharset().orElse(StandardCharsets.UTF_8);
try (OutputStreamWriter writer = new OutputStreamWriter(output, charset)) {
template.execute(writer, view);
}
} catch (Throwable e) {
throw new ViewRenderException("Mustache template error: " + view.getTemplateName(), e);
}
}
use of com.github.mustachejava.MustacheFactory in project error-prone by google.
the class BugPatternIndexWriter method dump.
void dump(Collection<BugPatternInstance> patterns, Writer w, Target target, Set<String> enabledChecks) throws IOException {
// (Default, Severity) -> [Pattern...]
SortedSetMultimap<IndexEntry, MiniDescription> sorted = TreeMultimap.create(Comparator.comparing(IndexEntry::onByDefault).reversed().thenComparing(IndexEntry::severity), Comparator.comparing(MiniDescription::name));
for (BugPatternInstance pattern : patterns) {
sorted.put(IndexEntry.create(enabledChecks.contains(pattern.name), pattern.severity), MiniDescription.create(pattern));
}
Map<String, Object> templateData = new HashMap<>();
List<Map<String, Object>> bugpatternData = Multimaps.asMap(sorted).entrySet().stream().map(e -> ImmutableMap.of("category", e.getKey().asCategoryHeader(), "checks", e.getValue())).collect(Collectors.toCollection(ArrayList::new));
templateData.put("bugpatterns", bugpatternData);
if (target == Target.EXTERNAL) {
Map<String, String> frontmatterData = ImmutableMap.<String, String>builder().put("title", "Bug Patterns").put("layout", "bugpatterns").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());
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile("com/google/errorprone/resources/bugpatterns_external.mustache");
mustache.execute(w, templateData);
} else {
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile("com/google/errorprone/resources/bugpatterns_internal.mustache");
mustache.execute(w, templateData);
}
}
Aggregations