Search in sources :

Example 1 with MustacheFactory

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");
}
Also used : FastStringReader(org.elasticsearch.common.io.FastStringReader) FastStringReader(org.elasticsearch.common.io.FastStringReader) Reader(java.io.Reader) MustacheFactory(com.github.mustachejava.MustacheFactory)

Example 2 with MustacheFactory

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;
}
Also used : DefaultMustacheFactory(com.github.mustachejava.DefaultMustacheFactory) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) Mustache(com.github.mustachejava.Mustache) StringWriter(java.io.StringWriter) DumperOptions(org.yaml.snakeyaml.DumperOptions) Path(java.nio.file.Path) ImmutableMap(com.google.common.collect.ImmutableMap) Yaml(org.yaml.snakeyaml.Yaml) MustacheFactory(com.github.mustachejava.MustacheFactory) DefaultMustacheFactory(com.github.mustachejava.DefaultMustacheFactory) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 3 with MustacheFactory

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);
    }
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) Query(org.apache.lucene.search.Query) TopScoreDocCollector(org.apache.lucene.search.TopScoreDocCollector) DefaultMustacheFactory(com.github.mustachejava.DefaultMustacheFactory) Mustache(com.github.mustachejava.Mustache) IOException(java.io.IOException) Document(org.apache.lucene.document.Document) ScoreDoc(org.apache.lucene.search.ScoreDoc) DefaultMustacheFactory(com.github.mustachejava.DefaultMustacheFactory) MustacheFactory(com.github.mustachejava.MustacheFactory) QueryParser(org.apache.lucene.queryparser.classic.QueryParser) IndexReader(org.apache.lucene.index.IndexReader) ParseException(org.apache.lucene.queryparser.classic.ParseException)

Example 4 with MustacheFactory

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);
    }
}
Also used : ViewRenderException(io.dropwizard.views.ViewRenderException) Mustache(com.github.mustachejava.Mustache) Charset(java.nio.charset.Charset) OutputStreamWriter(java.io.OutputStreamWriter) DefaultMustacheFactory(com.github.mustachejava.DefaultMustacheFactory) MustacheFactory(com.github.mustachejava.MustacheFactory)

Example 5 with MustacheFactory

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);
    }
}
Also used : DefaultMustacheFactory(com.github.mustachejava.DefaultMustacheFactory) SortedSetMultimap(com.google.common.collect.SortedSetMultimap) ImmutableMap(com.google.common.collect.ImmutableMap) StringWriter(java.io.StringWriter) Collection(java.util.Collection) Mustache(com.github.mustachejava.Mustache) Set(java.util.Set) IOException(java.io.IOException) HashMap(java.util.HashMap) Collectors(java.util.stream.Collectors) Multimaps(com.google.common.collect.Multimaps) ArrayList(java.util.ArrayList) Yaml(org.yaml.snakeyaml.Yaml) DumperOptions(org.yaml.snakeyaml.DumperOptions) List(java.util.List) TreeMultimap(com.google.common.collect.TreeMultimap) Map(java.util.Map) MustacheFactory(com.github.mustachejava.MustacheFactory) AutoValue(com.google.auto.value.AutoValue) Writer(java.io.Writer) Comparator(java.util.Comparator) SeverityLevel(com.google.errorprone.BugPattern.SeverityLevel) Target(com.google.errorprone.DocGenTool.Target) HashMap(java.util.HashMap) DefaultMustacheFactory(com.github.mustachejava.DefaultMustacheFactory) Mustache(com.github.mustachejava.Mustache) Yaml(org.yaml.snakeyaml.Yaml) DefaultMustacheFactory(com.github.mustachejava.DefaultMustacheFactory) MustacheFactory(com.github.mustachejava.MustacheFactory) StringWriter(java.io.StringWriter) DumperOptions(org.yaml.snakeyaml.DumperOptions) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap) Map(java.util.Map) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Aggregations

MustacheFactory (com.github.mustachejava.MustacheFactory)5 DefaultMustacheFactory (com.github.mustachejava.DefaultMustacheFactory)4 Mustache (com.github.mustachejava.Mustache)4 ImmutableMap (com.google.common.collect.ImmutableMap)2 IOException (java.io.IOException)2 StringWriter (java.io.StringWriter)2 Writer (java.io.Writer)2 ArrayList (java.util.ArrayList)2 DumperOptions (org.yaml.snakeyaml.DumperOptions)2 Yaml (org.yaml.snakeyaml.Yaml)2 AutoValue (com.google.auto.value.AutoValue)1 Multimaps (com.google.common.collect.Multimaps)1 SortedSetMultimap (com.google.common.collect.SortedSetMultimap)1 TreeMultimap (com.google.common.collect.TreeMultimap)1 SeverityLevel (com.google.errorprone.BugPattern.SeverityLevel)1 Target (com.google.errorprone.DocGenTool.Target)1 Gson (com.google.gson.Gson)1 ViewRenderException (io.dropwizard.views.ViewRenderException)1 OutputStreamWriter (java.io.OutputStreamWriter)1 Reader (java.io.Reader)1