use of com.github.mustachejava.DefaultMustacheFactory 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.DefaultMustacheFactory 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("tags", Joiner.on(", ").join(pattern.tags)).put("severity", pattern.severity).put("providesFix", pattern.providesFix.displayInfo()).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("tags", Joiner.on(", ").join(pattern.tags)).put("severity", pattern.severity.toString()).put("providesFix", pattern.providesFix.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 suppressionString;
if (pattern.suppressionAnnotations.length == 0) {
suppressionString = "This check may not be suppressed.";
} else {
suppressionString = pattern.suppressionAnnotations.length == 1 ? "Suppress false positives by adding the suppression annotation %s to the " + "enclosing element." : "Suppress false positives by adding one of these suppression annotations to " + "the enclosing element: %s";
suppressionString = String.format(suppressionString, Arrays.stream(pattern.suppressionAnnotations).map((String anno) -> standardizeAnnotation(anno, pattern.name)).collect(Collectors.joining(", ")));
}
templateData.put("suppression", suppressionString);
}
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.DefaultMustacheFactory in project minijax by minijax.
the class MustacheFeature method configure.
@Override
public boolean configure(final FeatureContext context) {
context.register(new DefaultMustacheFactory(), MustacheFactory.class);
context.register(MinijaxMustacheWriter.class);
context.register(MinijaxMustacheExceptionMapper.class);
return true;
}
use of com.github.mustachejava.DefaultMustacheFactory in project mesosFramework by zhizuqiu.
the class Tools method initMustache.
/**
* 读取模板并使用Map填充
*/
public static String initMustache(Map<String, String> scopes, String path) {
try {
Writer writer = new StringWriter();
MustacheFactory mf = new DefaultMustacheFactory();
File file = new File(path);
if (!file.exists()) {
logger.error("file [" + path + "] not exist");
return null;
}
byte[] data = Files.readAllBytes(Paths.get(path));
String fileData = new String(data, "UTF-8");
Mustache mustache = mf.compile(new StringReader(fileData), "test");
mustache.execute(writer, scopes);
return writer.toString();
} catch (Exception e) {
logger.error("initMustache exception->" + getErrorInfoFromException(e));
}
return null;
}
use of com.github.mustachejava.DefaultMustacheFactory in project dcos-commons by mesosphere.
the class TemplateUtils method renderMustache.
/**
* Renders a given Mustache template using the provided value map, returning any template parameters which weren't
* present in the map.
*
* @param templateName descriptive name of template to show in logs
* @param templateContent String representation of template
* @param values Map of values to be inserted into the template
* @param missingValues List where missing value entries will be added for any template params in
* {@code templateContent} which are not found in {@code values}
* @return Rendered Mustache template String
*/
public static String renderMustache(String templateName, String templateContent, Map<String, String> values, final List<MissingValue> missingValues) {
StringWriter writer = new StringWriter();
DefaultMustacheFactory mustacheFactory = new DefaultMustacheFactory();
mustacheFactory.setObjectHandler(new ReflectionObjectHandler() {
@Override
public Binding createBinding(String name, final TemplateContext tc, Code code) {
return new MissingValueBinding(this, name, tc, code, missingValues);
}
});
Map<String, Object> objEnv = new HashMap<>();
for (Map.Entry<String, String> entry : values.entrySet()) {
if (StringUtils.equalsIgnoreCase(entry.getValue(), "false") || StringUtils.equalsIgnoreCase(entry.getValue(), "true")) {
objEnv.put(entry.getKey(), Boolean.valueOf(entry.getValue()));
} else {
objEnv.put(entry.getKey(), entry.getValue());
}
}
mustacheFactory.compile(new StringReader(templateContent), templateName).execute(writer, objEnv);
return writer.toString();
}
Aggregations