com.github.mustachejava.Mustache Java Examples

The following examples show how to use com.github.mustachejava.Mustache. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TemplateService.java    From sawmill with Apache License 2.0 6 votes vote down vote up
public Template createTemplate(String template) {
    if (template == null) {
        throw new SawmillException("template cannot be with null value");
    }

    boolean containsMustache = template.contains("{{") && template.contains("}}");
    if (!containsMustache) {
        return new StringTemplate(template);
    }

    Mustache mustache = template.contains(JSON_STRING_SUFFIX) ?
                jsonStringMustacheFactory.compile(new StringReader(template.replaceAll(JSON_STRING_SUFFIX, "")), "") :
                mustacheFactory.compile(new StringReader(template), "");

    return new MustacheTemplate(mustache);
}
 
Example #2
Source File: CustomMustacheFactory.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
/**
 * At compile time, this function extracts the name of the variable:
 * {{#toJson}}variable_name{{/toJson}}
 */
protected static String extractVariableName(String fn, Mustache mustache, TemplateContext tc) {
    Code[] codes = mustache.getCodes();
    if (codes == null || codes.length != 1) {
        throw new MustacheException("Mustache function [" + fn + "] must contain one and only one identifier");
    }

    try (StringWriter capture = new StringWriter()) {
        // Variable name is in plain text and has type WriteCode
        if (codes[0] instanceof WriteCode) {
            codes[0].execute(capture, Collections.emptyList());
            return capture.toString();
        } else {
            codes[0].identity(capture);
            return capture.toString();
        }
    } catch (IOException e) {
        throw new MustacheException("Exception while parsing mustache function [" + fn + "] at line " + tc.line(), e);
    }
}
 
Example #3
Source File: MustacheUtils.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
public static String execute(Mustache template, Map<String, Object> params) {
    final StringWriter writer = new StringWriter();
    try {
        // crazy reflection here
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(SPECIAL_PERMS);
        }
        AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
            template.execute(writer, params);
            return null;
        });
    } catch (Exception e) {
        logger.error((Supplier<?>) () -> new ParameterizedMessage("Error running {}", template), e);
        throw new IllegalArgumentException("Error running " + template, e);
    }
    return writer.toString();

}
 
Example #4
Source File: TodoMustacheServiceUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTodoList_whenGetHtml_thenSuccess() throws IOException {
    Mustache m = MustacheUtil.getMustacheFactory().compile("todos.mustache");

    List<Todo> todos = Arrays.asList(
      new Todo("Todo 1", "Todo description"),
      new Todo("Todo 2", "Todo description another"),
      new Todo("Todo 3", "Todo description another")
    );
    Map<String, Object> context = new HashMap<>();
    context.put("todos", todos);

    assertThat(executeTemplate(m, context))
      .contains("<h2>Todo 1</h2>")
      .contains("<h2>Todo 2</h2>")
      .contains("<h2>Todo 3</h2>");
}
 
Example #5
Source File: BaseMessageTemplates.java    From UHC with MIT License 6 votes vote down vote up
@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 #6
Source File: HttpDecoderExample.java    From datakernel with Apache License 2.0 6 votes vote down vote up
@Provides
AsyncServlet mainServlet(ContactDAO contactDAO) {
	Mustache contactListView = new DefaultMustacheFactory().compile("static/contactList.html");
	return RoutingServlet.create()
			.map("/", request ->
					HttpResponse.ok200()
							.withBody(applyTemplate(contactListView, map("contacts", contactDAO.list()))))
			.map(POST, "/add", AsyncServletDecorator.loadBody()
					.serve(request -> {
						//[START REGION_3]
						Either<Contact, DecodeErrors> decodedUser = CONTACT_DECODER.decode(request);
						//[END REGION_3]
						if (decodedUser.isLeft()) {
							contactDAO.add(decodedUser.getLeft());
						}
						Map<String, Object> scopes = map("contacts", contactDAO.list());
						if (decodedUser.isRight()) {
							scopes.put("errors", decodedUser.getRight().toMap(SEPARATOR));
						}
						return HttpResponse.ok200()
								.withBody(applyTemplate(contactListView, scopes));
					}));
}
 
Example #7
Source File: GitChangelogApi.java    From git-changelog-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Get the changelog.
 *
 * @throws GitChangelogRepositoryException
 */
public void render(final Writer writer) throws GitChangelogRepositoryException {
  final MustacheFactory mf = new DefaultMustacheFactory();
  final String templateContent = checkNotNull(getTemplateContent(), "No template!");
  final StringReader reader = new StringReader(templateContent);
  final Mustache mustache = mf.compile(reader, this.settings.getTemplatePath());
  try {
    final boolean useIntegrationIfConfigured = shouldUseIntegrationIfConfigured(templateContent);
    final Changelog changelog = this.getChangelog(useIntegrationIfConfigured);
    mustache
        .execute(
            writer, //
            new Object[] {changelog, this.settings.getExtendedVariables()} //
            )
        .flush();
  } catch (final IOException e) {
    // Should be impossible!
    throw new GitChangelogRepositoryException("", e);
  }
}
 
Example #8
Source File: ProjectGeneratorHelper.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public static Mustache compile(MustacheFactory mustacheFactory, ProjectGeneratorConfiguration generatorProperties, String template, String name) throws IOException {
    String overridePath = generatorProperties.getTemplates().getOverridePath();
    URL resource = null;

    if (!StringUtils.isEmpty(overridePath)) {
        resource = ProjectGeneratorHelper.class.getResource("templates/" + overridePath + "/" + template);
    }
    if (resource == null) {
        resource = ProjectGeneratorHelper.class.getResource("templates/" + template);
    }
    if (resource == null) {
        throw new IllegalArgumentException(
            String.format("Unable to find te required template (overridePath=%s, template=%s)"
                , overridePath
                , template
            )
        );
    }

    try (InputStream stream = resource.openStream()) {
        return mustacheFactory.compile(new InputStreamReader(stream, StandardCharsets.UTF_8), name);
    }
}
 
Example #9
Source File: SmtpConfiguration.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Override
public String serializeAsXml() throws IOException {
    HashMap<String, Object> scopes = new HashMap<>();
    scopes.put("hasAuthorizedAddresses", authorizedAddresses.isPresent());
    authorizedAddresses.ifPresent(value -> scopes.put("authorizedAddresses", value));
    scopes.put("authRequired", authRequired);
    scopes.put("verifyIdentity", verifyIndentity);
    scopes.put("maxmessagesize", maxMessageSizeInKb);
    scopes.put("bracketEnforcement", bracketEnforcement);
    scopes.put("hooks", addittionalHooks);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    Writer writer = new OutputStreamWriter(byteArrayOutputStream);
    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache mustache = mf.compile(getPatternReader(), "example");
    mustache.execute(writer, scopes);
    writer.flush();
    return new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
}
 
Example #10
Source File: FortunesPostgresqlGetHandler.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    List<Fortune> fortunes = new ArrayList<>();
    try (Connection connection = ds.getConnection();
         PreparedStatement statement = connection.prepareStatement(
                 "SELECT * FROM Fortune",
                 ResultSet.TYPE_FORWARD_ONLY,
                 ResultSet.CONCUR_READ_ONLY);
         ResultSet resultSet = statement.executeQuery()) {
        while (resultSet.next()) {
            fortunes.add(new Fortune(
                    resultSet.getInt("id"),
                    resultSet.getString("message")));
        }
    }
    fortunes.add(new Fortune(0, "Additional fortune added at request time."));
    Collections.sort(fortunes);
    Mustache mustache = mustacheFactory.compile("fortunes.mustache");
    StringWriter writer = new StringWriter();
    mustache.execute(writer, fortunes);
    exchange.getResponseHeaders().put(
            Headers.CONTENT_TYPE, "text/html;charset=utf-8");
    exchange.getResponseSender().send(writer.toString());
}
 
Example #11
Source File: InstanceTemplatingTest.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@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 #12
Source File: StackCommandBuilder.java    From gaia with Mozilla Public License 2.0 5 votes vote down vote up
@Autowired
StackCommandBuilder(Settings settings, Mustache terraformMustache, List<RegistryOAuth2Provider> registryOAuth2Providers, StateApiSecurityConfig.StateApiSecurityProperties stateApiSecurityProperties) {
    this.settings = settings;
    this.terraformMustache = terraformMustache;
    this.registryOAuth2Providers = registryOAuth2Providers;
    this.stateApiSecurityProperties = stateApiSecurityProperties;
}
 
Example #13
Source File: MustacheTemplateEngine.java    From spark-template-engines with Apache License 2.0 5 votes vote down vote up
@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 #14
Source File: MicraServlet.java    From micra with MIT License 5 votes vote down vote up
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 #15
Source File: MicraServlet.java    From micra with MIT License 5 votes vote down vote up
protected String Mustache (String template, Map scopes)
{
    StringWriter writer = new StringWriter();
    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache mustache = mf.compile(new StringReader(template), template);
    mustache.execute(writer, scopes);
    writer.flush();

    return writer.toString();
}
 
Example #16
Source File: MustacheTemplater.java    From dropwizard-debpkg-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(final Reader input, final Writer output, final String name, final Object parameters) {
    try {
        final Mustache template = MUSTACHE.compile(input, name);
        template.execute(output, parameters);
    }
    catch (MustacheException e) {
        final Throwable cause = Throwables.getRootCause(e);
        Throwables.propagateIfInstanceOf(cause, MissingParameterException.class);
        throw e;
    }
}
 
Example #17
Source File: TodoMustacheServiceUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenEmptyList_whenGetHtml_thenEmptyHtml() throws IOException {
    Mustache m = MustacheUtil.getMustacheFactory().compile("todos.mustache");

    Map<String, Object> context = new HashMap<>();
    assertThat(executeTemplate(m, context)).isEmpty();
    ;
}
 
Example #18
Source File: TodoMustacheServiceUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenTodoList_whenGetHtmlUsingLamdba_thenHtml() throws IOException {
    Mustache m = MustacheUtil.getMustacheFactory().compile("todos-lambda.mustache");
    List<Todo> todos = Arrays.asList(
      new Todo("Todo 1", "Todo description"),
      new Todo("Todo 2", "Todo description another"),
      new Todo("Todo 3", "Todo description another")
    );
    todos.get(2).setDone(true);
    todos.get(2).setCompletedOn(Date.from(Instant.now().plusSeconds(300)));

    Map<String, Object> context = new HashMap<>();
    context.put("todos", todos);
    assertThat(executeTemplate(m, context).trim()).contains("Done 5 minutes ago");
}
 
Example #19
Source File: StatsGenerator.java    From passopolis-server with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Renders template with scope to a file located at outDir + suffix.
 *
 * @param outDir must not end with /
 * @param suffix must start with /
 * @param template
 * @param scope
 */
private static void renderIfOutputEnabled(
    String outDir, String suffix, Mustache template, Object scope) throws IOException {
  assert suffix.charAt(0) == '/';
  if (outDir != null) {
    assert !outDir.endsWith("/");
    String path = outDir + suffix;
    try (BufferedWriter writer = Files.newWriter(new File(path), Charsets.UTF_8)) {
      template.execute(writer, scope);
    }
  }
}
 
Example #20
Source File: TemplatesTest.java    From passopolis-server with GNU General Public License v3.0 5 votes vote down vote up
@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 #21
Source File: BaseMessageTemplates.java    From UHC with MIT License 5 votes vote down vote up
@Override
public List<String> evalTemplates(String path, final Object... context) {
    final List<Mustache> temps = getTemplates(path);

    return Lists.transform(temps, new Function<Mustache, String>() {
        @Override
        public String apply(Mustache input) {
            final StringWriter writer = new StringWriter();
            input.execute(writer, context);

            return writer.getBuffer().toString();
        }
    });
}
 
Example #22
Source File: BaseMessageTemplates.java    From UHC with MIT License 5 votes vote down vote up
@Override
public String evalTemplate(String key, Object... context) {
    final Mustache template = getTemplate(key);

    final StringWriter writer = new StringWriter();
    template.execute(writer, context);

    return writer.getBuffer().toString();
}
 
Example #23
Source File: MustacheJavaViewResolver.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
protected View view(final Mustache mustache) {
	return (model, out) -> {
		PrintWriter writer = new PrintWriter(out);
		mustache.execute(writer, model);
		writer.flush();
	};
}
 
Example #24
Source File: BaseMessageTemplates.java    From UHC with MIT License 5 votes vote down vote up
@Override
public Mustache getTemplate(String key) {
    // compile the tempalte from the config value and store it in our map
    if (!templates.containsKey(key)) {
        templates.put(key, templating.compile(new StringReader(getRaw(key)), key));
    }

    return Iterables.getFirst(templates.get(key), null);
}
 
Example #25
Source File: PostgresFortunesService.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private byte[] buildMustacheTemplate(List<Fortune> fortunes) {
  Mustache mustache = mustacheFactory.compile("fortunes.mustache");
  ByteArrayOutputStream bytes = new ByteArrayOutputStream();

  try (Writer writer = new OutputStreamWriter(bytes, StandardCharsets.UTF_8)) {
    mustache.execute(writer, fortunes);
  } catch (IOException e) {
    throw new UncheckedIOException(e);
  }

  return bytes.toByteArray();
}
 
Example #26
Source File: TodoMustacheServiceUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenEmptyList_whenGetHtmlUsingInvertedSection_thenHtml() throws IOException {
    Mustache m = MustacheUtil.getMustacheFactory().compile("todos-inverted-section.mustache");

    Map<String, Object> context = new HashMap<>();
    assertThat(executeTemplate(m, context).trim()).isEqualTo("<p>No todos!</p>");
}
 
Example #27
Source File: PropertyValuationBuilder.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Remplace les propriétés entre moustaches par leur valorisation
 * à l'aide du framework Mustache.
 */
public static String replaceMustachePropertiesWithValues(String input, Map<String, Object> scopes) {
    Mustache mustache = AbstractProperty.getMustacheInstanceFromStringContent(input);
    StringWriter stringWriter = new StringWriter();
    mustache.execute(stringWriter, scopes);
    stringWriter.flush();
    return stringWriter.toString();
}
 
Example #28
Source File: BaseHTMLReporter.java    From at.info-knowledge-base with MIT License 5 votes vote down vote up
@Override
public void generateReport(final List<XmlSuite> xmlSuites, final List<ISuite> suites, final String outputDirectory) {
    try {
        final Mustache mustache = new DefaultMustacheFactory().compile(REPORT_TEMPLATE);
        final File reportsFolder = new File(outputDirectory + "/html");

        reportsFolder.mkdir();

        if (reportsFolder.exists()) {
            mustache.execute(new FileWriter(outputDirectory + "/" + REPORT_OUTPUT), getScope(suites)).flush();
        }
    } catch (Exception e) {
        LOGGER.severe("Can't create template: " + e.getMessage());
    }
}
 
Example #29
Source File: MustacheTransformer.java    From tutorials with MIT License 5 votes vote down vote up
public String html() throws IOException {
    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache mustache = mf.compile(templateFile);
    try (Writer output = new StringWriter()) {
        mustache.execute(output, staxTransformer.getMap());
        output.flush();
        return output.toString();
    }
}
 
Example #30
Source File: MustacheTemplateEngine.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * Render a given model from a given template.
 *
 * @param view  name of the template file in resources/templates directory
 * @param model model to be rendered from the template
 * @return rendered template
 */
@Override
public String render(String view, Object model) {
    Mustache mustache = mustacheFactory.compile(view);
    StringWriter stringWriter = new StringWriter();
    try {
        mustache.execute(stringWriter, model).close();
    } catch (IOException e) {
        throw new RuntimeTemplateException(e);
    }
    return stringWriter.toString();
}