Java Code Examples for com.github.mustachejava.Mustache#execute()

The following examples show how to use com.github.mustachejava.Mustache#execute() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
Source File: DataSourceCodeGenerator.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public void generate(ExternalSource source, Server server, Map<String, String> props) throws MojoExecutionException {
    try {
        Mustache mustache = loadMustache(this.mf, source, this.classLoader);
        if (mustache != null) {
            Writer out = new FileWriter(new File(javaSrcDir, "DataSources" + server.getName() + ".java"));
            mustache.execute(out, props);
            out.close();
        } else {
            throw new MojoExecutionException("Failed to generate source for name :" + source.getTranslatorName() +
                    " make sure it is supported source, if this a custom source, it is developed with "
                    + "@ConnectionFactoryConfiguration annotation and Mustache file is provided");
        }
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}
 
Example 12
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 13
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 14
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 15
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 16
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 17
Source File: TEMPLATE.java    From warp10-platform with Apache License 2.0 4 votes vote down vote up
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
  Object o = stack.pop();
  
  if (!(o instanceof Map)) {
    throw new WarpScriptException(getName() + " expects a map on top of the stack.");
  }
  
  Map<String,Object> scope = (Map) o;
  
  o = stack.pop();
  
  if (!(o instanceof String)) {
    throw new WarpScriptException(getName() + " operates on a string.");
  }
  
  //
  // Check that 'scope' only contains strings, numbers, booleans or lists thereof
  //
  
  List<Object> elts = new ArrayList<Object>();
  elts.add(scope);
  
  while(!elts.isEmpty()) {         
    Object res = checkTypes(elts.get(0));
    elts.remove(0);
    
    if (null != res) {
      elts.addAll((Collection) res);
    }
  }
      
  try {
    Mustache mustache = mf.compile(new StringReader(o.toString()), "");
    
    StringWriter writer = new StringWriter();
    
    mustache.execute(writer, scope);
    
    stack.push(writer.toString());

    return stack;      
  } catch (Exception e) {
    throw new WarpScriptException(e);
  }
}
 
Example 18
Source File: VdbCodeGeneratorMojo.java    From teiid-spring-boot with Apache License 2.0 4 votes vote down vote up
private void createPomXml(Database database, Map<?, ?> spec, MustacheFactory mf, HashMap<String, String> props)
        throws Exception {
    StringBuilder sb = new StringBuilder();

    for(Server server : database.getServers()) {
        String translator = getBaseDataWrapper(database, server.getDataWrapper());
        sb.append("    <dependency>\n");
        sb.append("      <groupId>org.teiid</groupId>\n");
        sb.append("      <artifactId>spring-data-").append(translator).append("</artifactId>\n");
        sb.append("      <version>${teiid.springboot.version}</version>\n");
        sb.append("    </dependency>\n");
    }

    Map<?,?> build = (Map<?,?>)spec.get("build");
    Map<?,?> source = (Map<?,?>)build.get("source");
    List<String> dependencies = (List<String>)source.get("dependencies");
    if (dependencies != null) {
        for (String gav : dependencies) {
            int idx = gav.indexOf(':');
            int versionIdx = -1;
            if (idx != -1) {
                versionIdx = gav.indexOf(idx, ':');
            }
            if (idx == -1 || versionIdx == -1) {
                throw new MojoExecutionException("dependencies defined are not in correct GAV format. Must be in"
                        + "\"groupId:artifactId:version\" format.");
            }
            String groupId = gav.substring(0, idx);
            String artifactId = gav.substring(idx+1, versionIdx);
            String version = gav.substring(versionIdx+1);

            sb.append("    <dependency>\n");
            sb.append("      <groupId>").append(groupId).append("</groupId>\n");
            sb.append("      <artifactId>").append(artifactId).append("</artifactId>\n");
            sb.append("      <version>").append(version).append("</version>\n");
            sb.append("    </dependency>\n");
        }
    }

    props.put("vdbDependencies", sb.toString());

    getLog().info("Creating the pom.xml");
    Mustache mustache = mf.compile(
            new InputStreamReader(this.getClass().getResourceAsStream("/templates/pom.mustache")),
            "application");
    Writer out = new FileWriter(new File(getOutputDirectory(), "pom.xml"));
    mustache.execute(out, props);
    out.close();
}
 
Example 19
Source File: TwoFactorServlet.java    From passopolis-server with GNU General Public License v3.0 4 votes vote down vote up
public static void renderTemplate(String templateName, Object b, HttpServletResponse response)
    throws IOException {
  Mustache mustache = MUSTACHE_FACTORY.compilePackageRelative(
      TwoFactorServlet.class, templateName);
  mustache.execute(response.getWriter(), b);
}
 
Example 20
Source File: HttpDecoderExample.java    From datakernel with Apache License 2.0 4 votes vote down vote up
private static ByteBuf applyTemplate(Mustache mustache, Map<String, Object> scopes) {
	ByteBufWriter writer = new ByteBufWriter();
	mustache.execute(writer, scopes);
	return writer.getBuf();
}