com.github.mustachejava.MustacheFactory Java Examples

The following examples show how to use com.github.mustachejava.MustacheFactory. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #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: VdbCodeGeneratorMojo.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
private void createApplication(MustacheFactory mf, Database database, HashMap<String, String> props)
        throws Exception {
    getLog().info("Creating the Application.java class");
    Mustache mustache = mf.compile(
            new InputStreamReader(this.getClass().getResourceAsStream("/templates/Application.mustache")),
            "application");
    Writer out = new FileWriter(new File(getJavaSrcDirectory(), "Application.java"));
    mustache.execute(out, props);
    out.close();
}
 
Example #10
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 #11
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 #12
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 #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: 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 #15
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);
    }
}
 
Example #16
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 #17
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 #18
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 #19
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 #20
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 #21
Source File: Generator.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Executes a mustache template against a generatorContext object to generate an output string.
 * @param resourcePath Embedded resource template to use.
 * @param generatorContext Context object to bind the template to.
 * @return The string that results.
 */
protected String applyTemplate(@Nonnull String resourcePath, @Nonnull Object generatorContext) {
    Preconditions.checkNotNull(resourcePath, "resourcePath");
    Preconditions.checkNotNull(generatorContext, "generatorContext");

    InputStream resource = MustacheFactory.class.getClassLoader().getResourceAsStream(resourcePath);
    if (resource == null) {
        throw new RuntimeException("Could not find resource " + resourcePath);
    }

    InputStreamReader resourceReader = new InputStreamReader(resource, Charsets.UTF_8);
    Mustache template = mustacheFactory.compile(resourceReader, resourcePath);
    return template.execute(new StringWriter(), generatorContext).toString();
}
 
Example #22
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 #23
Source File: WebsiteBuilderMojo.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private void generateDefault(final Object context, final Supplier<Writer> writerSupplier,
        final MustacheFactory mustacheFactory, final String name) {
    try (final Reader tpl = new InputStreamReader(requireNonNull(findTemplate(name)), StandardCharsets.UTF_8);
            final Writer writer = writerSupplier.get()) {
        mustacheFactory.compile(tpl, name).execute(writer, context);
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #24
Source File: ApiGenerator.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
protected void generate(MustacheFactory mf, File javaSrcDir, Database database, HashMap<String, String> parentMap)
        throws Exception {
    log.info("Starting to Generate the Java classes for OpenAPI document: " + this.openApiFile.getCanonicalPath());
    String packageName = parentMap.get("packageName");
    String outputDir = this.outputDirectory.getAbsolutePath();

    CodegenConfigurator configurator = new CodegenConfigurator();
    configurator.setPackageName(packageName);
    configurator.setApiPackage(packageName);
    configurator.addDynamicProperty("configPackage", packageName);
    configurator.addDynamicProperty("basePackage", packageName);
    configurator.setModelPackage(packageName);

    //configurator.addSystemProperty("models", "");
    //configurator.addSystemProperty("modelDocs", "false");
    //configurator.addSystemProperty("modelTests", "false");

    configurator.setInputSpec(this.openApiFile.getAbsolutePath());

    configurator.setGeneratorName("org.teiid.maven.TeiidCodegen");
    configurator.setOutputDir(outputDir);
    configurator.setLibrary("spring-boot");
    configurator.addDynamicProperty("delegatePattern", "true");
    configurator.setIgnoreFileOverride(null);

    final ClientOptInput input = configurator.toClientOptInput();
    new DefaultGenerator().opts(input).generate();

    log.info("Generated the Java classes for OpenAPI document: " + this.openApiFile.getCanonicalPath());
}
 
Example #25
Source File: DataSourceCodeGenerator.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
static Mustache loadMustache(MustacheFactory mf, ExternalSource source, ClassLoader classLoader) {
    Mustache mustache = null;
    InputStream is = classLoader.getResourceAsStream(source.getName() + ".mustache");
    if (is != null) {
        mustache = mf.compile(new InputStreamReader(is),source.getName().toLowerCase());
    } else {
        mustache = mf.compile(
                new InputStreamReader(VdbCodeGeneratorMojo.class.getResourceAsStream("/templates/Jdbc.mustache")),
                source.getName().toLowerCase());
    }
    return mustache;
}
 
Example #26
Source File: VdbCodeGeneratorMojo.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
private void createApplicationProperties(Database database, Map<?, ?> spec, MustacheFactory mf,
        HashMap<String, String> props, ExternalSources externalSources) throws Exception {
    StringBuilder sb = new StringBuilder();

    List<?> dataSources = (List<?>)spec.get("datasources");
    for (Object ds : dataSources) {
        Map<?,?> datasource = (Map<?,?>)ds;
        String name = (String) datasource.get("name");
        String type = (String) datasource.get("type");
        List<?> properties = (List<?>)datasource.get("properties");
        for (Object p : properties) {
            Map<?,?> prop = (Map<?,?>)p;
            sb.append("spring.teiid.data.").append(type).append(".")
            .append(name).append(".").append((String) prop.get("name")).append("=")
            .append((String) prop.get("value")).append("\n");
        }
    }

    props.put("dsProperties", sb.toString());
    getLog().info("Creating the application.properties");
    Mustache mustache = mf.compile(
            new InputStreamReader(this.getClass().getResourceAsStream("/templates/application_properties.mustache")),
            "application");
    Writer out = new FileWriter(new File(getResourceDirectory(), "application.properties"));
    mustache.execute(out, props);
    out.close();
}
 
Example #27
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 #28
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 #29
Source File: Main.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static Mustache getTemplate() {
    MustacheFactory mf = new DefaultMustacheFactory();
    return mf.compile("fortunes.mustache");
}
 
Example #30
Source File: DefaultMustacheFactoryProducer.java    From ozark with Apache License 2.0 4 votes vote down vote up
@Produces
@ViewEngineConfig
public MustacheFactory getMustacheFactory() {
    return new OzarkMustacheFactory();
}