Java Examples for com.github.mustachejava.Mustache

The following java examples will help you to understand the usage of com.github.mustachejava.Mustache. These source code samples are taken from different open source projects.

Example 1
Project: mustache.java-master  File: Handlebar.java View source code
private void processTemplate(HttpServletRequest req, HttpServletResponse res, String filename, Object... scopes) throws UnsupportedEncodingException, FileNotFoundException, IOException, JsonParseException, JsonProcessingException {
    if (!new File(rootDir, filename).exists()) {
        System.out.println("template not found, skipping: " + filename);
        return;
    }
    MustacheFactory mc = new DefaultMustacheFactory(rootDir);
    Mustache mustache = mc.compile(filename);
    String base = filename.substring(0, filename.lastIndexOf("."));
    File file = new File(mocks, base + ".json");
    Map parameters = new HashMap<Object, Object>(req.getParameterMap()) {

        @Override
        public Object get(Object o) {
            // To change body of overridden methods use File |
            Object result = super.get(o);
            // Settings | File Templates.
            if (result instanceof String[]) {
                String[] strings = (String[]) result;
                if (strings.length == 1) {
                    return strings[0];
                }
            }
            return result;
        }
    };
    List<Object> scs = new ArrayList<Object>();
    if (null != scopes)
        scs.addAll(Arrays.<Object>asList(scopes));
    scs.add(parameters);
    scs.add(new Object() {

        Function slots = new TemplateFunction() {

            @Override
            public String apply(String input) {
                return "{{>" + input.trim() + "}}";
            }
        };
    });
    if (file.exists()) {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
        JsonParser parser = JSON_FACTORY.createParser(br);
        JsonNode json = parser.readValueAsTree();
        br.close();
        scs.add(0, toObject(json));
    }
    mustache.execute(res.getWriter(), scs.toArray());
}
Example 2
Project: fork-master  File: HtmlGenerator.java View source code
public void generateHtml(String htmlTemplateResource, File output, String filename, Object... htmlModels) {
    FileWriter writer = null;
    try {
        Mustache mustache = mustacheFactory.compile(htmlTemplateResource);
        File indexFile = new File(output, filename);
        writer = new FileWriter(indexFile);
        mustache.execute(writer, htmlModels);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        closeQuietly(writer);
    }
}
Example 3
Project: Hesperid-master  File: Files.java View source code
/**
     * Helper method to evaluate the filename and location.
     * That implementation uses mustache to parse thoose simple fields,
     * we might consider to be more efficient by string replacement,
     * or guessing if we nedd replacement in the first place....
     *
     * @param template
     * @param mustacheScope
     * @return
     */
private HesperidesFile getLocationFromMustacheScopeEvaluation(Template template, MustacheScope mustacheScope) {
    /* NOT EFFICIENT */
    Mustache mustacheFilename = mustacheFactory.compile(new StringReader(template.getFilename()), "something");
    String filename = TemplateContentGenerator.from(mustacheFilename).withScope(mustacheScope).generate();
    /* NOT EFFICIENT */
    Mustache mustacheLocation = mustacheFactory.compile(new StringReader(template.getLocation()), "something");
    String location = TemplateContentGenerator.from(mustacheLocation).withScope(mustacheScope).generate();
    return new HesperidesFile(template.getNamespace(), template.getName(), location, filename, convertRights(template.getRights()));
}
Example 4
Project: passopolis-server-master  File: TemplatesTest.java View source code
@Test
public void compileSuccess() {
    Mustache mustache = Templates.compile("correct.mustache");
    HashMap<String, String> variables = new HashMap<>();
    variables.put("outer_variable", "1");
    variables.put("partial_variable", "2");
    StringWriter writer = new StringWriter();
    mustache.execute(writer, variables);
    assertEquals("outer: 1\npartial: 2\n\n", writer.getBuffer().toString());
}
Example 5
Project: POL-POM-5-master  File: HtmlTemplate.java View source code
public String render(Object userScope) throws IOException {
    final Reader reader = new InputStreamReader(inputStream);
    final Mustache mustache = mf.compile(reader, null);
    OutputStream stream = new ByteArrayOutputStream();
    Object[] scopes = new Object[2];
    scopes[0] = userScope;
    scopes[1] = globalScope();
    mustache.execute(new PrintWriter(stream), scopes).flush();
    return stream.toString();
}
Example 6
Project: spark-template-engines-master  File: MustacheTemplateEngine.java View source code
@Override
public String render(ModelAndView modelAndView) {
    String viewName = modelAndView.getViewName();
    Mustache mustache = mustacheFactory.compile(viewName);
    StringWriter stringWriter = new StringWriter();
    try {
        mustache.execute(stringWriter, modelAndView.getModel()).close();
    } catch (IOException e) {
        throw new RuntimeIOException(e);
    }
    return stringWriter.toString();
}
Example 7
Project: torrenttunes-client-master  File: WriteMultilingualHTMLFiles.java View source code
private static void writeForLanguageMap(Strings language, String outputFile) {
    try {
        /*
			 * There are unfortunately two layers of mustache. The first is the strings,
			 * {{strings.blah}}, and the second is within the scripts, like {{artist.mbid}}
			 * 
			 * Your main.template file changed all the {{artist.mbid}} to @@artist.mbid~~ , 
			 * because otherwise this first language pass will fuck up all the others too,
			 * so after this first pass, you change the back to {{artist.mbid}}
			 * 
			 * { to @
			 * } to ~
			 */
        Reader reader = new FileReader(new File(DataSources.HTML_TEMPLATE_LOCATION()));
        File file = new File(outputFile);
        if (!file.exists())
            file.createNewFile();
        Writer writer = new FileWriter(file);
        MustacheFactory mf = new DefaultMustacheFactory();
        Mustache mustache = mf.compile(reader, "example");
        mustache.execute(writer, language.map);
        writer.flush();
        // Now replace all leftover mustache back to correct {{artist.mbid}}
        String text = Tools.readFile(outputFile);
        text = text.replaceAll("@", "{").replaceAll("~", "}");
        Tools.writeFile(text, outputFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 8
Project: undertow.js-master  File: MustacheTemplateProvider.java View source code
@Override
public Template getTemplate(String templateName) {
    try {
        MustacheFactory mf = new DefaultMustacheFactory();
        final Mustache mustache = mf.compile(new StringReader(Templates.loadTemplate(templateName, resourceManager)), templateName);
        return new Template() {

            @Override
            public String apply(Object data) {
                final StringWriter stringWriter = new StringWriter();
                mustache.execute(stringWriter, data);
                return stringWriter.getBuffer().toString();
            }
        };
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 9
Project: buckaroo-master  File: BuckFile.java View source code
public static Either<IOException, String> generate(final Identifier project) {
    Preconditions.checkNotNull(project);
    final URL url = Resources.getResource("com.loopperfect.buckaroo/ProjectTemplate.mustache");
    final String templateString;
    try {
        templateString = Resources.toString(url, Charsets.UTF_8);
    } catch (final IOException e) {
        return Either.left(e);
    }
    final Map<String, Object> scopes = ImmutableMap.of("name", project.name);
    final Writer writer = new StringWriter();
    final MustacheFactory mustacheFactory = new DefaultMustacheFactory();
    final Mustache mustache = mustacheFactory.compile(new StringReader(templateString), "Project");
    mustache.execute(writer, scopes);
    try {
        writer.flush();
    } catch (final IOException e) {
        return Either.left(e);
    }
    return Either.right(writer.toString());
}
Example 10
Project: dropwizard-master  File: MustacheViewRenderer.java View source code
@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);
    }
}
Example 11
Project: jenkins-csvexporter-master  File: OutputCSVJobObjProcessor.java View source code
@Override
public boolean process(Set<? extends TypeElement> annotationsElement, RoundEnvironment roundEnv) {
    try {
        for (TypeElement typeAnnotation : annotationsElement) {
            for (Element element : roundEnv.getElementsAnnotatedWith(typeAnnotation)) {
                System.out.println("OutputCSVObj Processing ....");
                String className = element.getAnnotation(ExportElementType.class).value();
                InputStream inputStream = this.getClass().getResourceAsStream("mustache/subClassTemplate.mustache");
                StringBuilder sb = new StringBuilder();
                int c;
                while ((c = inputStream.read()) != -1) {
                    sb.append((char) c);
                }
                StringReader stringReader = new StringReader(sb.toString());
                MustacheFactory mf = new JavaDefaultMustacheFactory();
                Mustache mustache = mf.compile(stringReader, "mustacheResult");
                JavaFileObject fileObject = processingEnv.getFiler().createSourceFile("com.boissinot.jenkins.csvexporter.domain.generated.OutputCSVJobObj_", element);
                ExportBeanListRetriever exportBeanListRetriever = new ExportBeanListRetriever();
                SortedSet<ExportBean> beans = exportBeanListRetriever.buildExportBeanList(roundEnv.getElementsAnnotatedWith(ExportElement.class));
                Writer writer = fileObject.openWriter();
                HeaderLabelRetriever headerLabelRetriever = new HeaderLabelRetriever();
                BeanFieldRetriever beanFieldRetriever = new BeanFieldRetriever();
                mustache.execute(writer, new OutputCSVJobTemplateContent(className, className + "_", beanFieldRetriever.getNames(beans), headerLabelRetriever.getNameLabels(beans)));
                writer.flush();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage());
        return false;
    }
    return true;
}
Example 12
Project: rapidoid-master  File: MustacheJavaViewResolver.java View source code
protected MustacheResolver mustacheResolver(final ResourceLoader templateLoader) {
    return new MustacheResolver() {

        @Override
        public Reader getReader(String name) {
            try {
                byte[] bytes = templateLoader.load(name);
                U.must(bytes != null, "The Mustache.java template '%s' doesn't exist!", name);
                return new StringReader(new String(bytes));
            } catch (Exception e) {
                throw U.rte(e);
            }
        }
    };
}
Example 13
Project: semiot-platform-master  File: RDFTemplate.java View source code
public String resolveToString(Map<String, Object>... maps) {
    Map<String, Object> scope = new FailOnMissingMapWrapper(mergeMaps(maps));
    String tmp = new String(template);
    for (int i = 0; PATTERN_VARIABLE.matcher(tmp).matches(); i++) {
        StringWriter writer = new StringWriter();
        Mustache mustache = MUSTACHE_FACTORY.compile(new StringReader(tmp), name + i);
        mustache.execute(writer, scope);
        tmp = writer.toString();
    }
    return tmp;
}
Example 14
Project: tech-gallery-master  File: EmailConfig.java View source code
/**
   * Must be called if email is a template email. Resource and dynamic data must not be null.
   */
public void processTemplate(Object mustacheTo) {
    if (template != null) {
        MustacheFactory mf = new DefaultMustacheFactory();
        Mustache mustache = mf.compile(Constants.TEMPLATES_FOLDER + File.separator + this.template);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Writer writer = new OutputStreamWriter(baos, StandardCharsets.UTF_8);
        try {
            mustache.execute(writer, mustacheTo).flush();
        } catch (IOException e) {
            throw new RuntimeException("Could not mount template file");
        }
        try {
            this.body = new String(baos.toByteArray(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Could not encode template file");
        }
    }
}
Example 15
Project: vnluser-master  File: MustacheTemplateUtil.java View source code
public static Mustache getCompiledTemplate(String tplPath) {
    if (isUsedCache.get()) {
        Mustache tpl = mustacheMap.get(tplPath);
        if (tpl == null) {
            String fullpath = StringUtil.toString(BASE_TEMPLATE_PATH, tplPath, TEMPLATE_SUFFIX);
            tpl = getMustacheFactory().compile(fullpath);
            mustacheMap.put(tplPath, tpl);
        }
        return tpl;
    } else {
        String fullpath = StringUtil.toString(BASE_TEMPLATE_PATH, tplPath, TEMPLATE_SUFFIX);
        return new DefaultMustacheFactory().compile(fullpath);
    }
}
Example 16
Project: web-framework-master  File: MustacheViewRenderer.java View source code
@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);
    }
}
Example 17
Project: elassandra-master  File: MustacheTests.java View source code
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.<String, Object>singletonMap("boost_val", "0.2");
    Mustache mustache = (Mustache) engine.compile(template, Collections.<String, String>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()).toUtf8());
}
Example 18
Project: error-prone-master  File: BugPatternFileGenerator.java View source code
@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(// sort by name
            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;
}
Example 19
Project: lambdamatic-project-master  File: BaseAnnotationProcessor.java View source code
/**
   * Generates the source code for the given {@code targetClassName} using the given
   * {@link Mustache} template.
   * 
   * @param templateContext the template context to use when running the engine to generate the
   *        source code.
   * @throws IOException if the file cannot be created
   */
protected void generateSourceCode(final BaseTemplateContext templateContext) throws IOException {
    final Mustache template = getTemplate(templateContext.getTemplateFileName());
    if (template == null) {
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "Could not create the QueryMetadata class for the given '" + templateContext.getFullyQualifiedClassName() + "' class: no queryMetadataTemplate available.");
        return;
    }
    final JavaFileObject jfo = this.processingEnv.getFiler().createSourceFile(templateContext.getFullyQualifiedClassName());
    this.processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "creating source file: " + jfo.toUri());
    try (final Writer writer = jfo.openWriter()) {
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "applying template: " + template.getName());
        template.execute(writer, templateContext).flush();
    }
}
Example 20
Project: struts2.mustache.java-master  File: MustacheResult.java View source code
/* (non-Javadoc)
	 * @see org.apache.struts2.dispatcher.PlainTextResult#doExecute(java.lang.String, com.opensymphony.xwork2.ActionInvocation)
	 */
@SuppressWarnings("unused")
@Override
protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(HTTP_RESPONSE);
    ServletContext servletContext = (ServletContext) invocation.getInvocationContext().get(SERVLET_CONTEXT);
    PrintWriter writer = response.getWriter();
    // Open a stream to read the template passed to the action
    InputStreamReader reader = new FileReader(servletContext.getRealPath(finalLocation));
    // create the resource root
    String resourceRoot = null;
    if (rootMustachePath != null) {
        resourceRoot = rootMustachePath;
    } else {
        resourceRoot = servletContext.getRealPath("/");
    }
    if (reader == null) {
        log.warn("resource at location [" + finalLocation.toString() + "] cannot be obtained (return null) from ServletContext !!! ");
    } else {
        response.setContentType("text/html");
        // We need to pass the real path of the templates to the Mustache compiler, in order to support nested templates
        MustacheFactory mf = new DefaultMustacheFactory(new File(resourceRoot));
        Mustache mustache = mf.compile(reader, "mustacheResult");
        mustache.execute(writer, invocation.getAction());
        reader.close();
    }
    writer.flush();
    writer.close();
}
Example 21
Project: tailor-master  File: FormatTest.java View source code
@Test
public void testHTMLFormat() throws IOException {
    Format format = Format.HTML;
    final String[] command = new String[] { "--format", format.getName(), "--no-color", "--only=upper-camel-case", inputFile.getPath() };
    Map<String, Object> expectedOutput = getHTMLMessages();
    Tailor.main(command);
    List<String> expected = new ArrayList<>();
    List<String> actual = new ArrayList<>();
    Mustache mustache = new DefaultMustacheFactory().compile(new InputStreamReader(HTMLFormatter.class.getResourceAsStream("index.html"), Charset.defaultCharset()), "index.html");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mustache.execute(new OutputStreamWriter(baos, Charset.defaultCharset()), expectedOutput).flush();
    expectedMessages.addAll(Arrays.asList(baos.toString(Charset.defaultCharset().name()).split(NEWLINE_REGEX)));
    for (String msg : expectedMessages) {
        String strippedMsg = msg.replaceAll(inputFile.getCanonicalPath(), "");
        expected.add(strippedMsg);
    }
    String[] msgs = outContent.toString(Charset.defaultCharset().name()).split(NEWLINE_REGEX);
    for (String msg : msgs) {
        String strippedMsg = msg.replaceAll(inputFile.getCanonicalPath(), "");
        actual.add(strippedMsg);
    }
    assertArrayEquals(outContent.toString(Charset.defaultCharset().name()), expected.toArray(), actual.toArray());
}
Example 22
Project: watertemplate-engine-master  File: Internationalization.java View source code
private void compileFile(Locale locale, File file) throws IOException {
    LOGGER.debug("Parsing {} at {}", locale, file);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Before: {} ", FileUtils.readFileToString(file).trim());
    }
    final Properties p = new Properties();
    p.load(new FileReader(locales.get(locale)));
    Map<String, Object> func = new HashMap<>();
    func.put("i18n", (TemplateFunction)  s -> p.getProperty(s, s));
    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache mustache = mf.compile(file.getAbsolutePath());
    mustache.execute(new FileWriter(file), func).flush();
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("After: {} ", FileUtils.readFileToString(file));
    }
}
Example 23
Project: elasticsearch-master  File: MustacheTests.java View source code
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());
}
Example 24
Project: Foodoo-backend-master  File: Templates.java View source code
public static String getTestTemplate(String name, String status, String date) {
    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache template = mf.compile("test.mustache");
    StringWriter writer = new StringWriter();
    HashMap<String, String> scopes = new HashMap<>();
    scopes.put("catname", name);
    scopes.put("status", status);
    scopes.put("date", date);
    template.execute(writer, scopes);
    return writer.toString();
}
Example 25
Project: keywhiz-master  File: SecretTemplateCompiler.java View source code
public String compile(final String template) {
    StringWriter sw = new StringWriter();
    try {
        MustacheFactory mf = new DefaultMustacheFactory();
        Mustache mustache = mf.compile(new StringReader(template), null);
        mustache.execute(sw, functions).flush();
    } catch (NumberFormatExceptionIOException | MustacheException |  e) {
        throw new IllegalArgumentException(e);
    }
    // This means that no randomness was generated. This is not acceptable
    if (!hasCompiledRandomness) {
        throw new IllegalArgumentException();
    }
    return sw.toString();
}
Example 26
Project: micra-master  File: MicraServlet.java View source code
protected String MustacheView(String templateName, Map scopes) {
    ServletContext context = getServletContext();
    String fullTemplatePath = context.getRealPath("/WEB-INF/" + templateName);
    StringWriter writer = new StringWriter();
    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache mustache = mf.compile(fullTemplatePath);
    mustache.execute(writer, scopes);
    writer.flush();
    return writer.toString();
}
Example 27
Project: MIFOSX-master  File: TemplateMergeService.java View source code
public String compile(final Template template, final Map<String, Object> scopes) throws MalformedURLException, IOException {
    this.scopes = scopes;
    this.scopes.put("static", new TemplateFunctions());
    final MustacheFactory mf = new DefaultMustacheFactory();
    final Mustache mustache = mf.compile(new StringReader(template.getText()), template.getName());
    final Map<String, Object> mappers = getCompiledMapFromMappers(template.getMappersAsMap());
    this.scopes.putAll(mappers);
    expandMapArrays(scopes);
    final StringWriter stringWriter = new StringWriter();
    mustache.execute(stringWriter, this.scopes);
    return stringWriter.toString();
}
Example 28
Project: roboconf-platform-master  File: InstanceTemplatingTest.java View source code
@Test
public void testImportTemplate() throws Exception {
    Map<String, String> vars = new HashMap<>();
    vars.put("name1", "val1");
    vars.put("name2", "val2");
    vars.put("name3", "val3");
    Import impt = new Import("/", "component1", vars);
    MustacheFactory mf = new DefaultMustacheFactory();
    File templateFile = TestUtils.findTestFile("/importTemplate.mustache");
    Mustache mustache = mf.compile(templateFile.getAbsolutePath());
    StringWriter writer = new StringWriter();
    mustache.execute(writer, new ImportBean(impt)).flush();
    String writtenString = writer.toString();
    for (Map.Entry<String, String> entry : vars.entrySet()) {
        Assert.assertTrue("Var was not displayed correctly", writtenString.contains(entry.getKey() + " : " + entry.getValue()));
    }
}
Example 29
Project: UHC-master  File: BaseMessageTemplates.java View source code
@Override
public List<Mustache> getTemplates(final String path) {
    // compile the template from the config value and store it in our map
    if (!templates.containsKey(path)) {
        final List<Mustache> temps = Lists.transform(getRawStrings(path), new Function<String, Mustache>() {

            protected int index;

            @Override
            public Mustache apply(String input) {
                return templating.compile(new StringReader(input), path + ".[" + (index++) + "]");
            }
        });
        templates.putAll(path, temps);
    }
    return templates.get(path);
}
Example 30
Project: camel-master  File: MustacheEndpoint.java View source code
@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);
    }
}
Example 31
Project: mustache-maven-plugin-master  File: MustacheMojo.java View source code
private void runTemplateConfiguration(Object globalContext, TemplateRunConfiguration configuration, Charset charset) throws MojoFailureException, MojoExecutionException {
    Object templateContext = createContext(configuration.getContext(), charset);
    if (templateContext == null) {
        if (globalContext == null) {
            throw new MojoFailureException("Template has no defined context and plugin context is also empty");
        }
        templateContext = globalContext;
    }
    Mustache mustache = createTemplate(configuration.getTemplateFile(), charset);
    File outputFile = new File(configuration.getOutputPath());
    File parent = outputFile.getParentFile();
    if (!parent.exists() || parent.mkdirs()) {
        throw new MojoFailureException("Output directory cannot be created.");
    }
    try (Writer writer = new OutputStreamWriter(new FileOutputStream(outputFile), charset)) {
        mustache.execute(writer, templateContext);
    } catch (IOException e) {
        throw new MojoFailureException(e, "Cannot open output file", "Cannot open output file: " + e.getMessage());
    } catch (MustacheException e) {
        throw new MojoFailureException(e, "Cannot process template", "Cannot process template: " + e.getMessage());
    }
}
Example 32
Project: ninja-mustache-master  File: TemplateEngineMustacheTest.java View source code
public Writer answer(InvocationOnMock invocation) throws Throwable {
    Map<String, Object> parameters = (Map<String, Object>) invocation.getArguments()[1];
    assertNotNull(parameters.get("flash"));
    assertNotNull(parameters.get("i18n"));
    assertEquals("en", parameters.get("lang"));
    assertEquals("/", parameters.get("contextPath"));
    Writer writer = (Writer) invocation.getArguments()[0];
    writer.write("Hellow world from Mustache");
    return writer;
}
Example 33
Project: redis-protocol-master  File: Main.java View source code
@SuppressWarnings("ResultOfMethodCallIgnored")
public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException, MustacheException {
    try {
        Args.parse(Main.class, args);
    } catch (IllegalArgumentException e) {
        Args.usage(Main.class);
        System.exit(1);
    }
    MustacheFactory mb = new DefaultMustacheFactory("templates/" + language) {

        @Override
        public void encode(String value, Writer writer) {
            try {
                writer.write(value);
            } catch (IOException e) {
                throw new MustacheException();
            }
        }
    };
    Mustache mustache = mb.compile(template + ".txt");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    XPathFactory xpf = XPathFactory.newInstance();
    final DocumentBuilder db = dbf.newDocumentBuilder();
    final XPathExpression replyX = xpf.newXPath().compile("//a");
    final Properties cache = new Properties();
    File cacheFile = new File("cache");
    if (cacheFile.exists()) {
        cache.load(new FileInputStream(cacheFile));
    }
    Set<String> ungenerated = new HashSet<String>(Arrays.asList(// Transactions
    "MULTI", // Transactions
    "EXEC", // Transactions
    "DISCARD", // subscriptions
    "PSUBSCRIBE", // subscriptions
    "SUBSCRIBE", // subscriptions
    "UNSUBSCRIBE", // subscriptions
    "PUNSUBSCRIBE", // authentication
    "AUTH"));
    final Set<String> genericReply = new HashSet<String>(Arrays.asList(// Can return an integer reply
    "SORT", // Two different return values
    "ZRANK", // Two different return values
    "ZREVRANK", // Can return a bulk or multibulk reply depending on count
    "SRANDMEMBER", // If the timeout occurs it returns a Nil multi-bulk reply instead of a bulk reply
    "BRPOPLPUSH"));
    final Set<String> multiples = new HashSet<String>(Arrays.asList("ZADD"));
    JsonFactory jf = new MappingJsonFactory();
    JsonParser jsonParser = jf.createJsonParser(new URL("https://raw.github.com/antirez/redis-doc/master/commands.json"));
    final JsonNode commandNodes = jsonParser.readValueAsTree();
    Iterator<String> fieldNames = commandNodes.getFieldNames();
    ImmutableListMultimap<String, String> group = Multimaps.index(fieldNames, new Function<String, String>() {

        @Override
        public String apply(String s) {
            return commandNodes.get(s).get("group").asText();
        }
    });
    List<Object> commands = new ArrayList<Object>();
    for (Map.Entry<String, String> entry : group.entries()) {
        String key = entry.getKey();
        final String groupName = key.substring(0, 1).toUpperCase() + key.substring(1);
        final String command = entry.getValue();
        if (ungenerated.contains(command))
            continue;
        final boolean splitCommand = command.contains(" ");
        final String safeCommand = command.replace(" ", "_");
        String cacheReply = cache.getProperty(command.toLowerCase());
        if (cacheReply == null) {
            final Document detail = db.parse("http://query.yahooapis.com/v1/public/yql/javarants/redisreply?url=" + URLEncoder.encode("http://redis.io/commands/" + safeCommand.toLowerCase(), "utf-8"));
            cacheReply = replyX.evaluate(detail).replaceAll("[- ]", "").replaceAll("reply", "Reply").replaceAll("bulk", "Bulk").replaceAll("Statuscode", "Status");
            cache.setProperty(safeCommand.toLowerCase(), cacheReply);
            cache.store(new FileWriter(cacheFile), "# Updated " + new Date());
        }
        final String finalReply = cacheReply;
        final JsonNode commandNode = commandNodes.get(command);
        commands.add(new Object() {

            String group = groupName;

            boolean split_command = splitCommand;

            String name = safeCommand;

            String name1 = splitCommand ? name.substring(0, name.indexOf("_")) : name;

            String name2 = splitCommand ? name.substring(name.indexOf("_") + 1) : "";

            String comment = commandNode.get("summary").getTextValue();

            boolean generic = finalReply.equals("") || genericReply.contains(name);

            String reply = generic ? "Reply" : finalReply;

            String version = commandNode.get("since").getTextValue();

            boolean hasOptional = false;

            boolean hasMultiple = false;

            List<String> skipped = new ArrayList<String>();

            boolean varargs() {
                return (hasMultiple || hasOptional);
            }

            boolean usearray = false;

            List<Object> arguments = new ArrayList<Object>();

            int base_length() {
                return arguments.size() - (hasMultiple ? 1 : 0);
            }

            {
                JsonNode argumentArray = commandNode.get("arguments");
                if (argumentArray != null) {
                    if (argumentArray.size() > 3) {
                        usearray = true;
                    }
                    boolean first = true;
                    int argNum = 0;
                    if (multiples.contains(name)) {
                        arguments.add(new Object() {

                            boolean first = true;

                            boolean multiple = true;

                            String typename = "Object";

                            String name = "args";
                        });
                    } else {
                        for (final JsonNode argumentNode : argumentArray) {
                            JsonNode nameNodes = argumentNode.get("name");
                            final String argName;
                            if (nameNodes.isArray()) {
                                boolean f = true;
                                StringBuilder sb = new StringBuilder();
                                for (JsonNode nameNode : nameNodes) {
                                    if (!f) {
                                        sb.append("_or_");
                                    }
                                    f = false;
                                    String textValue = nameNode.getTextValue();
                                    sb.append(textValue);
                                }
                                argName = sb.toString();
                            } else {
                                argName = nameNodes.getTextValue();
                            }
                            final boolean finalFirst = first;
                            final int finalArgNum = argNum;
                            final boolean isMultiple = argumentNode.get("multiple") != null || argumentNode.get("command") != null;
                            final boolean isOptional = argumentNode.get("optional") != null;
                            if (isOptional)
                                hasOptional = true;
                            if (isMultiple)
                                hasMultiple = true;
                            final int finalArgNum1 = argNum;
                            arguments.add(new Object() {

                                int arg_num = finalArgNum1;

                                boolean first = finalFirst;

                                boolean multiple = isMultiple;

                                String typename = "Object";

                                String name() {
                                    String name = (argName + finalArgNum).replaceAll("[- :]", "_");
                                    for (String s : skipped) {
                                        name = s + "_" + name;
                                    }
                                    return name;
                                }

                                Boolean optional = isOptional;

                                boolean skip() {
                                    boolean skip = hasMultiple && isOptional && !isMultiple;
                                    if (skip) {
                                        skipped.add(argName);
                                    }
                                    return skip;
                                }
                            });
                            if (isMultiple) {
                                usearray = true;
                            }
                            first = false;
                            argNum++;
                            if (isMultiple)
                                break;
                        }
                    }
                }
            }

            String methodname = safeCommand.toLowerCase();

            String quote = keywords.contains(methodname) ? "`" : "";
        });
    }
    Map<String, Object> ctx = new HashMap<String, Object>();
    ctx.put("commands", commands);
    File base = new File(dest, pkg.replace(".", "/"));
    base.mkdirs();
    mustache.execute(new FileWriter(new File(base, className + "." + language)), ctx).close();
}
Example 34
Project: autopsy-master  File: SnapShotReportWriter.java View source code
/**
     * Fill in the mustache template at the given location using the values from
     * the given context object and save it to the given outPutFile.
     *
     * @param templateLocation The location of the template. suitible for use
     *                         with Class.getResourceAsStream
     * @param templateName     The name of the tempalte. (Used by mustache to
     *                         cache templates?)
     * @param context          The contect to use to fill in the template
     *                         values.
     * @param outPutFile       The filled in tempalte will be saced at this
     *                         Path.
     *
     * @throws IOException If there is a problem saving the filled in template
     *                     to disk.
     */
private void fillTemplateAndWrite(final String templateLocation, final String templateName, Object context, final Path outPutFile) throws IOException {
    Mustache summaryMustache = mf.compile(new InputStreamReader(SnapShotReportWriter.class.getResourceAsStream(templateLocation)), templateName);
    try (Writer writer = Files.newBufferedWriter(outPutFile, Charset.forName("UTF-8"))) {
        //NON-NLS
        summaryMustache.execute(writer, context);
    }
}
Example 35
Project: rakam-master  File: WebUserService.java View source code
private CompletableFuture sendMail(Mustache titleCompiler, Mustache contentCompiler, Mustache htmlCompiler, String email, Map<String, Object> data) {
    StringWriter writer;
    writer = new StringWriter();
    contentCompiler.execute(writer, data);
    String txtContent = writer.toString();
    writer = new StringWriter();
    htmlCompiler.execute(writer, data);
    String htmlContent = writer.toString();
    writer = new StringWriter();
    titleCompiler.execute(writer, data);
    String title = writer.toString();
    MailSender mailSender = mailConfig.getMailSender();
    return CompletableFuture.runAsync(() -> {
        try {
            mailSender.sendMail(email, title, txtContent, Optional.of(htmlContent), Stream.empty());
        } catch (MessagingException e) {
            LOGGER.error(e, "Unable to send mail");
        }
    });
}
Example 36
Project: sputnik-master  File: ContentRenderer.java View source code
public String render(Review review) throws IOException {
    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache mustache = mf.compile(TEMPLATE_MUSTACHE);
    Writer sink = new StringWriter();
    mustache.execute(sink, review).flush();
    return sink.toString();
}
Example 37
Project: springyRecords-master  File: ABTableClassWriter.java View source code
public Mustache createTemplate() {
    MustacheFactory mf = new DefaultMustacheFactory();
    return mf.compile("abtable.mustache");
}
Example 38
Project: FireFly-master  File: MustacheTemplateHandlerSPIImpl.java View source code
@Override
public void renderTemplate(RoutingContext routingContext, String resourceName, Object scope) {
    Mustache mustache = mustacheFactory.compile(resourceName);
    try (PrintWriter writer = routingContext.getResponse().getPrintWriter()) {
        mustache.execute(writer, scope);
    }
}
Example 39
Project: obridge-master  File: MustacheRunner.java View source code
public static String build(String templateName, Object backingObject) {
    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache mustache = mf.compile(templateName);
    Writer execute = mustache.execute(new StringWriter(), backingObject);
    return execute.toString();
}
Example 40
Project: osgi-jax-rs-connector-master  File: MustacheTemplateProcessor.java View source code
@Override
public Mustache resolve(String name, MediaType mediaType) {
    InputStream stream = MustacheTemplateProcessor.class.getResourceAsStream(name);
    return mustacheFactory.compile(new InputStreamReader(stream), name);
}
Example 41
Project: springmvc-mustache-master  File: MustacheJavaTemplateTest.java View source code
@Before
public void setUp() {
    mustache = mock(Mustache.class);
    mustacheJavaTemplate = new MustacheJavaTemplate(mustache);
}
Example 42
Project: titanite-master  File: MustacheViewRenderer.java View source code
private BodyWriter render(Mustache mustache, Object model) throws IOException {
    return ( out) -> {
        try (OutputStreamWriter writer = new OutputStreamWriter(out)) {
            mustache.execute(writer, model instanceof String ? EMPTY_MODEL : new Object[] { model });
        }
    };
}
Example 43
Project: maven-build-utils-master  File: Exporter.java View source code
private Mustache compileTemplate(ClassLoader ccl, MustacheFactory mf, String template) {
    return mf.compile(new InputStreamReader(ccl.getResourceAsStream(template)), template);
}
Example 44
Project: tweet-gateway-server-master  File: MustacheToolbox.java View source code
public Mustache compileOptimized(String fileName) {
    MustacheFactory mf = new DefaultMustacheFactory();
    try {
        Reader reader = createTrimmingReader(fileName);
        return mf.compile(reader, fileName);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }
}
Example 45
Project: jersey-master  File: MustacheTemplateProcessor.java View source code
@Override
protected Mustache resolve(final String templatePath, final Reader reader) {
    return factory.compile(reader, templatePath);
}
Example 46
Project: takari-lifecycle-master  File: FilterResourcesProcessor.java View source code
public void filter(Reader reader, Writer writer, Map<Object, Object> properties) throws IOException {
    Mustache mustache = mustacheFactory.compile(reader, "maven", "${", "}");
    mustache.execute(writer, properties).close();
}
Example 47
Project: plato-master  File: T2FlowExecutablePlanGenerator.java View source code
/**
     * Generates the executable plan from this description and writes it to the
     * provided writer.
     * 
     * @param writer
     *            the writer where the plan is written to
     * @throws IOException
     *             if an error occurred during write
     */
public void generate(Writer writer) throws IOException {
    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache mustache = mf.compile("data/t2flow/workflow.mustache");
    mustache.execute(writer, workflow).flush();
}