com.github.mustachejava.DefaultMustacheFactory Java Examples

The following examples show how to use com.github.mustachejava.DefaultMustacheFactory. 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: 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 #2
Source File: ModifiedDeathMessagesModule.java    From UHC with MIT License 6 votes vote down vote up
@Override
public void initialize() throws InvalidConfigurationException {
    if (!config.contains(FORMAT_KEY)) {
        config.set(FORMAT_KEY, "&c{{original}} at {{player.world}},{{player.blockCoords}}");
    }

    if (!config.contains(FORMAT_EXPLANATION_KEY)) {
        config.set(FORMAT_EXPLANATION_KEY, "<message> at <coords>");
    }

    final String format = config.getString(FORMAT_KEY);
    formatExplanation = config.getString(FORMAT_EXPLANATION_KEY);

    final MustacheFactory mf = new DefaultMustacheFactory();
    try {
        template = mf.compile(
                new StringReader(ChatColor.translateAlternateColorCodes('&', format)),
                "death-message"
        );
    } catch (Exception ex) {
        throw new InvalidConfigurationException("Error parsing death message template", ex);
    }

    super.initialize();
}
 
Example #3
Source File: ViewMustache.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
private void init()
{
  String templatePath = _config.get("view.mustache.templates",
                                    "classpath:/templates");

  MustacheResolver resolver;

  if (templatePath.startsWith("classpath:")) {
    String root = templatePath.substring("classpath:".length());

    resolver = new ClasspathResolver(root);

    //ClassLoader loader = Thread.currentThread().getContextClassLoader();
    //resolver = new MustacheResolverImpl(loader, root);
  }
  else {
    resolver = new DefaultResolver(templatePath);
  }

  MustacheFactory factory = new DefaultMustacheFactory(resolver);

  _factory = factory;
}
 
Example #4
Source File: AbstractHITCreator.java    From argument-reasoning-comprehension-task with Apache License 2.0 6 votes vote down vote up
public void initialize(String mustacheTemplate)
        throws IOException
{
    InputStream stream = this.getClass().getClassLoader().getResourceAsStream(mustacheTemplate);
    if (stream == null) {
        throw new FileNotFoundException("Resource not found: " + mustacheTemplate);
    }

    // compile template
    MustacheFactory mf = new DefaultMustacheFactory();
    Reader reader = new InputStreamReader(stream, "utf-8");
    mustache = mf.compile(reader, "template");

    // output path
    if (!outputPath.exists()) {
        outputPath.mkdirs();
    }
}
 
Example #5
Source File: MustacheScriptEngineService.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
 * 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 template
 *            a string representing the template to compile.
 * @return a compiled template object for later execution.
 * */
@Override
public Object compile(String template, Map<String, String> params) {
    String contentType = params.get(CONTENT_TYPE_PARAM);
    if (contentType == null) {
        contentType = JSON_CONTENT_TYPE;
    }

    final DefaultMustacheFactory mustacheFactory;
    switch (contentType){
        case PLAIN_TEXT_CONTENT_TYPE:
            mustacheFactory = new NoneEscapingMustacheFactory();
            break;
        case JSON_CONTENT_TYPE:
        default:
            // assume that the default is json encoding:
            mustacheFactory = new JsonEscapingMustacheFactory();
            break;
    }
    mustacheFactory.setObjectHandler(new CustomReflectionObjectHandler());
    Reader reader = new FastStringReader(template);
    return mustacheFactory.compile(reader, "query-template");
}
 
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: Mustache.java    From template-benchmark with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Setup
public void setup() {
    MustacheFactory mustacheFactory = new DefaultMustacheFactory() {

        @Override
        public void encode(String value, Writer writer) {
            // Disable HTML escaping
            try {
                writer.write(value);
            } catch (IOException e) {
                throw new MustacheException(e);
            }
        }
    };
    template = mustacheFactory.compile("templates/stocks.mustache.html");
}
 
Example #8
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 #9
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 #10
Source File: ArchetypeEngine.java    From helidon-build-tools with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new archetype engine instance.
 *
 * @param loader     jar file loader
 * @param properties user properties
 */
public ArchetypeEngine(ArchetypeLoader loader, Map<String, String> properties) {
    this.loader = loader;
    this.mf = new DefaultMustacheFactory();
    this.descriptor = loadDescriptor(loader);
    Objects.requireNonNull(properties, "properties is null");
    descriptor.properties().stream()
            .filter(p -> p.value().isPresent() && !properties.containsKey(p.id()))
            .forEach(p -> properties.put(p.id(), p.value().get()));
    this.properties = properties;
    List<SourcePath> paths = loadResourcesList(loader);
    this.templates = resolveFileSets(descriptor.templateSets().map(TemplateSets::templateSets).orElseGet(LinkedList::new),
            descriptor.templateSets().map(TemplateSets::transformations).orElseGet(Collections::emptyList), paths,
            properties);
    this.files = resolveFileSets(descriptor.fileSets().map(FileSets::fileSets).orElseGet(LinkedList::new),
            descriptor.fileSets().map(FileSets::transformations).orElseGet(Collections::emptyList), paths, properties);
}
 
Example #11
Source File: QuotaThresholdNotice.java    From james-project with Apache License 2.0 5 votes vote down vote up
private String renderTemplate(FileSystem fileSystem, String template) throws IOException {
    try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
         Writer writer = new OutputStreamWriter(byteArrayOutputStream)) {

        MustacheFactory mf = new DefaultMustacheFactory();
        Mustache mustache = mf.compile(getPatternReader(fileSystem, template), "example");
        mustache.execute(writer, computeScopes());
        writer.flush();
        return new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
    }
}
 
Example #12
Source File: MustacheProvider.java    From web-budget with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param template the template file name inside src/java/resources/mail
 */
public MustacheProvider(String template) {

    this.data = new HashMap<>();

    final MustacheFactory factory = new DefaultMustacheFactory();
    this.mustache = factory.compile("/mail/" + template);
}
 
Example #13
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 #14
Source File: ContentRenderer.java    From sputnik with Apache License 2.0 5 votes vote down vote up
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 #15
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 #16
Source File: MustacheProvider.java    From web-budget with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param template the template file name inside src/java/resources/mail
 */
public MustacheProvider(String template) {

    this.data = new HashMap<>();

    final MustacheFactory factory = new DefaultMustacheFactory();
    this.mustache = factory.compile("/mail/" + template);
}
 
Example #17
Source File: StackCommandBuilderTest.java    From gaia with Mozilla Public License 2.0 5 votes vote down vote up
@BeforeEach
void setup() {
    var mustache = new DefaultMustacheFactory().compile("mustache/terraform.mustache");

    var stateApiSecurityProperties = new StateApiSecurityConfig.StateApiSecurityProperties("gaia-backend", "password");

    stackCommandBuilder = new StackCommandBuilder(new Settings(), mustache, List.of(registryOAuth2Provider), stateApiSecurityProperties);
}
 
Example #18
Source File: TestMustache.java    From tools with Apache License 2.0 5 votes vote down vote up
@Test
public void testMustache() throws MustacheException, IOException {
	File root = new File("TestFiles");
	DefaultMustacheFactory builder = new DefaultMustacheFactory(root);
	Map<String, Object> context = Maps.newHashMap();
	context.put(TEST_FIELD1, TEST_RESULT1);
	Mustache m = builder.compile("testSimpleTemplate.txt");
	StringWriter writer = new StringWriter();
	m.execute(writer, context);
	assertEquals(TEST_RESULT1, writer.toString());
}
 
Example #19
Source File: TemplateUtils.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #20
Source File: HelloWebServer.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static HttpHandler fortunesHandler(DataSource db) {
  Objects.requireNonNull(db);

  var mustacheFactory = new DefaultMustacheFactory();

  return exchange -> {
    var fortunes = new ArrayList<Fortune>();

    try (var connection = db.getConnection();
         var statement = connection.prepareStatement("SELECT * FROM fortune");
         var resultSet = statement.executeQuery()) {

      while (resultSet.next()) {
        var id = resultSet.getInt("id");
        var message = resultSet.getString("message");
        fortunes.add(new Fortune(id, message));
      }
    }

    fortunes.add(new Fortune(0, "Additional fortune added at request time."));
    fortunes.sort(comparing(fortune -> fortune.message));

    var mustache = mustacheFactory.compile("hello/fortunes.mustache");
    var writer = new StringWriter();
    mustache.execute(writer, fortunes);
    var html = writer.toString();

    exchange.getResponseHeaders().put(CONTENT_TYPE, "text/html;charset=utf-8");
    exchange.getResponseSender().send(html);
  };
}
 
Example #21
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 #22
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 #23
Source File: SnakeYAMLMojo.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
private void generateHelperClass(Map<String, Type> types, Set<Import> imports) throws IOException {
    List<String> pathElementsToGeneratedClass = new ArrayList<>();
    String outputPackage = outputClass.substring(0, outputClass.lastIndexOf('.'));
    for (String segment : outputPackage.split("\\.")) {
        pathElementsToGeneratedClass.add(segment);
    }
    Path outputDir = Paths.get(outputDirectory.getAbsolutePath(), pathElementsToGeneratedClass.toArray(new String[0]));
    Files.createDirectories(outputDir);

    String simpleClassName = outputClass.substring(outputClass.lastIndexOf('.') + 1);
    Path outputPath = outputDir.resolve(simpleClassName + ".java");

    Writer writer = new OutputStreamWriter(new FileOutputStream(outputPath.toFile()));
    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache m = mf.compile("typeClassTemplate.mustache");
    CodeGenModel model = new CodeGenModel(outputPackage, simpleClassName, types.values(), imports, interfacePrefix,
            implementationPrefix);
    m.execute(writer, model);
    writer.close();
}
 
Example #24
Source File: GenerateMustache.java    From heimdall with Apache License 2.0 5 votes vote down vote up
/**
* Generates a Mustache file.
* 
* @param template		The template for generation
* @param parameters	The Map<String, Object> with the parameters for creation
* @return				The content of the file created
*/
  public static String generateTemplate(String template, Map<String, Object> parameters) {
       
       StringWriter writer = new StringWriter();
       MustacheFactory mf = new DefaultMustacheFactory();
       Mustache mustache = mf.compile(new StringReader(template), "example");
       mustache.execute(writer, parameters);
       
       return writer.toString();
  }
 
Example #25
Source File: MustacheProvider.java    From library with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param template the template file name inside src/java/resources/mail
 */
public MustacheProvider(String template) {

    this.data = new HashMap<>();

    final MustacheFactory factory = new DefaultMustacheFactory();
    this.mustache = factory.compile("/mail/" + template);
}
 
Example #26
Source File: MustacheTemplateRenderer.java    From testgrid with Apache License 2.0 5 votes vote down vote up
@Override
public String render(String view, Map<String, Object> model) throws ReportingException {
    Mustache mustache = new DefaultMustacheFactory(TEMPLATE_DIR).compile(view);
    StringWriter stringWriter = new StringWriter();
    try {
        mustache.execute(stringWriter, model).close();
    } catch (IOException e) {
        throw new ReportingException(e);
    }
    return stringWriter.toString();
}
 
Example #27
Source File: CamelKProjectBuilder.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public CamelKProjectBuilder(String name, String syndesisVersion) {
    super(name, syndesisVersion);

    MustacheFactory mustacheFactory = new DefaultMustacheFactory();
    try (InputStream stream = CamelKProjectBuilder.class.getResource("template/pom.xml.mustache").openStream()) {
        this.pomMustache = mustacheFactory.compile(new InputStreamReader(stream, StandardCharsets.UTF_8), name);
    } catch (IOException e) {
        throw new IllegalStateException("Failed to read Camel-K pom template file", e);
    }
}
 
Example #28
Source File: ProjectGenerator.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public ProjectGenerator(ProjectGeneratorConfiguration configuration, IntegrationResourceManager resourceManager, MavenProperties mavenProperties) throws IOException {
    this.configuration = configuration;
    this.resourceManager = resourceManager;
    this.mavenProperties = mavenProperties;

    MustacheFactory mf = new DefaultMustacheFactory();

    this.applicationJavaMustache = compile(mf, configuration, "Application.java.mustache", "Application.java");
    this.applicationPropertiesMustache = compile(mf, configuration, "application.properties.mustache", "application.properties");
    this.restRoutesMustache = compile(mf, configuration, "RestRouteConfiguration.java.mustache", "RestRouteConfiguration.java");
    this.pomMustache = compile(mf, configuration, "pom.xml.mustache", "pom.xml");
}
 
Example #29
Source File: KubernetesInstanceFactory.java    From kubernetes-elastic-agents with Apache License 2.0 5 votes vote down vote up
public static String getTemplatizedPodSpec(String podSpec) {
    StringWriter writer = new StringWriter();
    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache mustache = mf.compile(new StringReader(podSpec), "templatePod");
    mustache.execute(writer, KubernetesInstanceFactory.getJinJavaContext());
    return writer.toString();
}
 
Example #30
Source File: MustacheContentResolver.java    From swagger-brake with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves a mustache template into a String based on the parameter map.
 * @param mustacheFile the path of the mustache template.
 * @param paramMap the parameter map for the mustache template.
 * @return the resolved content.
 */
public String resolve(String mustacheFile, Map<String, ?> paramMap) {
    try {
        MustacheFactory mf = new DefaultMustacheFactory();
        Mustache m = mf.compile(mustacheFile);
        StringWriter sw = new StringWriter();
        m.execute(sw, paramMap).flush();
        return sw.toString();
    } catch (IOException e) {
        throw new RuntimeException("Error while resolving mustache content", e);
    }
}