com.samskivert.mustache.Mustache Java Examples
The following examples show how to use
com.samskivert.mustache.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: PackageTemplateTests.java From spring-cloud-skipper with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings("unchecked") public void testMustasche() throws IOException { Yaml yaml = new Yaml(); Map model = (Map) yaml.load(valuesResource.getInputStream()); String templateAsString = StreamUtils.copyToString(nestedMapResource.getInputStream(), Charset.defaultCharset()); Template mustacheTemplate = Mustache.compiler().compile(templateAsString); String resolvedYml = mustacheTemplate.execute(model); Map map = (Map) yaml.load(resolvedYml); logger.info("Resolved yml = " + resolvedYml); assertThat(map).containsKeys("apiVersion", "deployment"); Map deploymentMap = (Map) map.get("deployment"); assertThat(deploymentMap).contains(entry("name", "time")) .contains(entry("count", 10)); Map applicationProperties = (Map) deploymentMap.get("applicationProperties"); assertThat(applicationProperties).contains(entry("log.level", "DEBUG"), entry("server.port", 8089)); Map deploymentProperties = (Map) deploymentMap.get("deploymentProperties"); assertThat(deploymentProperties).contains(entry("app.time.producer.partitionKeyExpression", "payload"), entry("app.log.spring.cloud.stream.bindings.input.consumer.maxAttempts", 5)); }
Example #2
Source File: AbstractScalaCodegen.java From openapi-generator with Apache License 2.0 | 6 votes |
@Override public Mustache.Compiler processCompiler(Mustache.Compiler compiler) { Mustache.Escaper SCALA = new Mustache.Escaper() { @Override public String escape(String text) { // Fix included as suggested by akkie in #6393 // The given text is a reserved word which is escaped by enclosing it with grave accents. If we would // escape that with the default Mustache `HTML` escaper, then the escaper would also escape our grave // accents. So we remove the grave accents before the escaping and add it back after the escaping. if (text.startsWith("`") && text.endsWith("`")) { String unescaped = text.substring(1, text.length() - 1); return "`" + Escapers.HTML.escape(unescaped) + "`"; } // All none reserved words will be escaped with the default Mustache `HTML` escaper return Escapers.HTML.escape(text); } }; return compiler.withEscaper(SCALA); }
Example #3
Source File: TemplateManager.java From alf.io with GNU General Public License v3.0 | 6 votes |
public TemplateManager(MessageSourceManager messageSourceManager, UploadedResourceManager uploadedResourceManager, ConfigurationManager configurationManager) { this.messageSourceManager = messageSourceManager; this.uploadedResourceManager = uploadedResourceManager; this.configurationManager = configurationManager; this.compilers = new EnumMap<>(TemplateOutput.class); this.compilers.put(TemplateOutput.TEXT, Mustache.compiler() .escapeHTML(false) .standardsMode(false) .defaultValue("") .nullValue("") .withFormatter(TemplateManager::dateFormatter)); this.compilers.put(TemplateOutput.HTML, Mustache.compiler() .escapeHTML(true) .standardsMode(false) .defaultValue("") .nullValue("") .withFormatter(TemplateManager::dateFormatter)); }
Example #4
Source File: AbstractScalaCodegen.java From TypeScript-Microservices with MIT License | 6 votes |
@Override public Mustache.Compiler processCompiler(Mustache.Compiler compiler) { Mustache.Escaper SCALA = new Mustache.Escaper() { @Override public String escape (String text) { // Fix included as suggested by akkie in #6393 // The given text is a reserved word which is escaped by enclosing it with grave accents. If we would // escape that with the default Mustache `HTML` escaper, then the escaper would also escape our grave // accents. So we remove the grave accents before the escaping and add it back after the escaping. if (text.startsWith("`") && text.endsWith("`")) { String unescaped = text.substring(1, text.length() - 1); return "`" + Escapers.HTML.escape(unescaped) + "`"; } // All none reserved words will be escaped with the default Mustache `HTML` escaper return Escapers.HTML.escape(text); } }; return compiler.withEscaper(SCALA); }
Example #5
Source File: KotlinServerCodegen.java From TypeScript-Microservices with MIT License | 6 votes |
private void addMustacheLambdas(Map<String, Object> objs) { Map<String, Mustache.Lambda> lambdas = new ImmutableMap.Builder<String, Mustache.Lambda>() .put("lowercase", new LowercaseLambda().generator(this)) .put("uppercase", new UppercaseLambda()) .put("titlecase", new TitlecaseLambda()) .put("camelcase", new CamelCaseLambda().generator(this)) .put("indented", new IndentedLambda()) .put("indented_8", new IndentedLambda(8, " ")) .put("indented_12", new IndentedLambda(12, " ")) .put("indented_16", new IndentedLambda(16, " ")) .build(); if (objs.containsKey("lambda")) { LOGGER.warn("An property named 'lambda' already exists. Mustache lambdas renamed from 'lambda' to '_lambda'. " + "You'll likely need to use a custom template, " + "see https://github.com/swagger-api/swagger-codegen#modifying-the-client-library-format. "); objs.put("_lambda", lambdas); } else { objs.put("lambda", lambdas); } }
Example #6
Source File: AbstractCSharpCodegen.java From TypeScript-Microservices with MIT License | 6 votes |
private void addMustacheLambdas(Map<String, Object> objs) { Map<String, Mustache.Lambda> lambdas = new ImmutableMap.Builder<String, Mustache.Lambda>() .put("lowercase", new LowercaseLambda().generator(this)) .put("uppercase", new UppercaseLambda()) .put("titlecase", new TitlecaseLambda()) .put("camelcase", new CamelCaseLambda().generator(this)) .put("camelcase_param", new CamelCaseLambda().generator(this).escapeAsParamName(true)) .put("indented", new IndentedLambda()) .put("indented_8", new IndentedLambda(8, " ")) .put("indented_12", new IndentedLambda(12, " ")) .put("indented_16", new IndentedLambda(16, " ")) .build(); if (objs.containsKey("lambda")) { LOGGER.warn("An property named 'lambda' already exists. Mustache lambdas renamed from 'lambda' to '_lambda'. " + "You'll likely need to use a custom template, " + "see https://github.com/swagger-api/swagger-codegen#modifying-the-client-library-format. "); objs.put("_lambda", lambdas); } else { objs.put("lambda", lambdas); } }
Example #7
Source File: Utils.java From para with Apache License 2.0 | 6 votes |
/** * Compiles a mustache template with a given scope (map of fields and values). * @param context a map of fields and values * @param template a Mustache template * @return the compiled template string */ public static String compileMustache(Map<String, Object> context, String template) { if (context == null || StringUtils.isBlank(template)) { return ""; } Writer writer = new StringWriter(); try { Mustache.compiler().escapeHTML(false).emptyStringIsFalse(true).compile(template).execute(context, writer); } finally { try { writer.close(); } catch (IOException e) { logger.error(null, e); } } return writer.toString(); }
Example #8
Source File: TemplateFieldJoiningAnnotator.java From baleen with Apache License 2.0 | 6 votes |
/** * Gather fields that are referenced in the mustache template. * * @return the collection */ private Collection<String> gatherReferencedFields() { Collection<String> fields = new ArrayList<>(); Collector collector = new DefaultCollector() { @Override public VariableFetcher createFetcher(Object ctx, String name) { fields.add(name); return super.createFetcher(ctx, name); } }; Compiler compiler = Mustache.compiler().defaultValue("").withCollector(collector); Template mockTemplate = compiler.compile(mustacheTemplate); mockTemplate.execute(new HashMap<>()); return fields; }
Example #9
Source File: DefaultGenerator.java From TypeScript-Microservices with MIT License | 6 votes |
private File processTemplateToFile(Map<String, Object> templateData, String templateName, String outputFilename) throws IOException { String adjustedOutputFilename = outputFilename.replaceAll("//", "/").replace('/', File.separatorChar); if (ignoreProcessor.allowsFile(new File(adjustedOutputFilename))) { String templateFile = getFullTemplateFile(config, templateName); String template = readTemplate(templateFile); Mustache.Compiler compiler = Mustache.compiler(); compiler = config.processCompiler(compiler); Template tmpl = compiler .withLoader(new Mustache.TemplateLoader() { @Override public Reader getTemplate(String name) { return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); } }) .defaultValue("") .compile(template); writeToFile(adjustedOutputFilename, tmpl.execute(templateData)); return new File(adjustedOutputFilename); } LOGGER.info("Skipped generation of " + adjustedOutputFilename + " due to rule in .swagger-codegen-ignore"); return null; }
Example #10
Source File: SpringMustacheApplication.java From tutorials with MIT License | 5 votes |
@Bean public Mustache.Compiler mustacheCompiler(Mustache.TemplateLoader templateLoader, Environment environment) { MustacheEnvironmentCollector collector = new MustacheEnvironmentCollector(); collector.setEnvironment(environment); return Mustache.compiler() .defaultValue("Some Default Value") .withLoader(templateLoader) .withCollector(collector); }
Example #11
Source File: Meta.java From openapi-generator with Apache License 2.0 | 5 votes |
/** * Converter method to process supporting files: execute with mustache, or simply copy to * destination directory * * @param targetDir - destination directory * @param data - map with additional params needed to process templates * @return converter object to pass to lambdaj */ private static Converter<SupportingFile, File> processFiles(final File targetDir, final Map<String, Object> data) { return support -> { try { File destinationFolder = new File(new File(targetDir.getAbsolutePath()), support.folder); File outputFile = new File(destinationFolder, support.destinationFilename); TemplateManager templateProcessor = new TemplateManager( new TemplateManagerOptions(false, false), new MustacheEngineAdapter(), new TemplatePathLocator[]{ new CommonTemplateContentLocator("codegen") } ); String template = templateProcessor.readTemplate(new File(TEMPLATE_DIR_CLASSPATH, support.templateFile).getPath()); String formatted = template; Mustache.TemplateLoader loader = name -> templateProcessor.getTemplateReader(name.concat(MUSTACHE_EXTENSION)); if (support.templateFile.endsWith(MUSTACHE_EXTENSION)) { LOGGER.info("writing file to {}", outputFile.getAbsolutePath()); formatted = Mustache.compiler().withLoader(loader).defaultValue("") .compile(template).execute(data); } else { LOGGER.info("copying file to {}", outputFile.getAbsolutePath()); } FileUtils.writeStringToFile(outputFile, formatted, StandardCharsets.UTF_8); return outputFile; } catch (IOException e) { throw new RuntimeException("Can't generate project", e); } }; }
Example #12
Source File: ManifestUtils.java From spring-cloud-skipper with Apache License 2.0 | 5 votes |
private static String applyManifestTemplate(Package packageToDeploy, Map<String, ?> model) { // Aggregate all valid manifests into one big doc. StringBuilder sb = new StringBuilder(); // Top level templates. List<Template> templates = packageToDeploy.getTemplates(); if (templates != null) { for (Template template : templates) { String templateAsString = new String(template.getData()); com.samskivert.mustache.Template mustacheTemplate = Mustache.compiler().compile(templateAsString); sb.append("\n---\n# Source: " + template.getName() + "\n"); sb.append(mustacheTemplate.execute(model)); } } for (Package pkg : packageToDeploy.getDependencies()) { String packageName = pkg.getMetadata().getName(); Map<String, Object> modelForDependency; if (model.containsKey(packageName)) { modelForDependency = (Map<String, Object>) model.get(pkg.getMetadata().getName()); } else { modelForDependency = new TreeMap<>(); } sb.append(applyManifestTemplate(pkg, modelForDependency)); } return sb.toString(); }
Example #13
Source File: TypeScriptFetchClientCodegen.java From openapi-generator with Apache License 2.0 | 5 votes |
@Override protected ImmutableMap.Builder<String, Mustache.Lambda> addMustacheLambdas() { ImmutableMap.Builder<String, Mustache.Lambda> lambdas = super.addMustacheLambdas(); lambdas.put("indented_star_1", new IndentedLambda(1, " ", "* ")); lambdas.put("indented_star_4", new IndentedLambda(5, " ", "* ")); return lambdas; }
Example #14
Source File: MailService.java From eds-starter6-jpa with Apache License 2.0 | 5 votes |
public MailService(JavaMailSender mailSender, MessageSource messageSource, AppProperties appProperties, Mustache.Compiler mustacheCompiler, @Value("${info.app.name}") String appName) { this.mailSender = mailSender; this.defaultSender = appProperties.getDefaultEmailSender(); this.messageSource = messageSource; this.appUrl = appProperties.getUrl(); this.appName = appName; this.mustacheCompiler = mustacheCompiler; }
Example #15
Source File: Meta.java From TypeScript-Microservices with MIT License | 5 votes |
/** * Converter method to process supporting files: execute with mustache, or simply copy to * destination directory * * @param targetDir - destination directory * @param data - map with additional params needed to process templates * @return converter object to pass to lambdaj */ private static Converter<SupportingFile, File> processFiles(final File targetDir, final Map<String, Object> data) { return new Converter<SupportingFile, File>() { private DefaultGenerator generator = new DefaultGenerator(); @Override public File convert(SupportingFile support) { try { File destinationFolder = new File(new File(targetDir.getAbsolutePath()), support.folder); File outputFile = new File(destinationFolder, support.destinationFilename); String template = generator.readTemplate(new File(TEMPLATE_DIR_CLASSPATH, support.templateFile).getPath()); String formatted = template; if (support.templateFile.endsWith(MUSTACHE_EXTENSION)) { LOGGER.info("writing file to {}", outputFile.getAbsolutePath()); formatted = Mustache.compiler().withLoader(loader(generator)).defaultValue("") .compile(template).execute(data); } else { LOGGER.info("copying file to {}", outputFile.getAbsolutePath()); } FileUtils.writeStringToFile(outputFile, formatted); return outputFile; } catch (IOException e) { throw new RuntimeException("Can't generate project", e); } } }; }
Example #16
Source File: MustCache.java From something.apk with MIT License | 5 votes |
private synchronized static void generatePostTemplates(Context context){ try { InputStreamReader postMustReader = new InputStreamReader(context.getResources().getAssets().open("mustache/post.mustache"), Charsets.UTF_8); postTemplate = Mustache.compiler().compile(postMustReader); InputStreamReader pmMustReader = new InputStreamReader(context.getResources().getAssets().open("mustache/pm.mustache"), Charsets.UTF_8); pmTemplate = Mustache.compiler().compile(pmMustReader); InputStreamReader previewMustReader = new InputStreamReader(context.getResources().getAssets().open("mustache/preview.mustache"), Charsets.UTF_8); previewTemplate = Mustache.compiler().compile(previewMustReader); InputStreamReader headerInput = new InputStreamReader(context.getResources().getAssets().open("mustache/header.mustache"), Charsets.UTF_8); headerTemplate = Mustache.compiler().compile(headerInput); InputStreamReader footerInput = new InputStreamReader(context.getResources().getAssets().open("mustache/footer.mustache"), Charsets.UTF_8); footerTemplate = Mustache.compiler().compile(footerInput); Closeables.close(previewMustReader, true); Closeables.close(pmMustReader, true); Closeables.close(headerInput, true); Closeables.close(footerInput, true); Closeables.close(postMustReader, true); } catch (IOException e) { e.printStackTrace(); //should never happen, log via bugsense just in case BugSenseHandler.sendException(e); } }
Example #17
Source File: TemplateManager.java From alf.io with GNU General Public License v3.0 | 5 votes |
protected Mustache.Lambda createTranslator() { return (frag, out) -> { String template = frag.execute(); final String key = extractKey(template); final List<String> args = extractParameters(template); final String text = messageSource.getMessage(key, args.toArray(), locale); out.write(text); }; }
Example #18
Source File: JMustacheViewResolver.java From rapidoid with Apache License 2.0 | 5 votes |
protected Mustache.TemplateLoader loader(final ResourceLoader templateLoader) { return name -> { String filename = filename(name); byte[] bytes = templateLoader.load(filename); U.must(bytes != null, "The JMustache template '%s' doesn't exist!", filename); return new StringReader(new String(bytes)); }; }
Example #19
Source File: Meta.java From TypeScript-Microservices with MIT License | 5 votes |
/** * Creates mustache loader for template using classpath loader * * @param generator - class with reader getter * @return loader for template */ private static Mustache.TemplateLoader loader(final DefaultGenerator generator) { return new Mustache.TemplateLoader() { @Override public Reader getTemplate(String name) { return generator.getTemplateReader(TEMPLATE_DIR_CLASSPATH + File.separator + name.concat(MUSTACHE_EXTENSION)); } }; }
Example #20
Source File: JMustacheViewResolver.java From rapidoid with Apache License 2.0 | 4 votes |
@Override public View getView(String viewName, final ResourceLoader resourceLoader) throws Exception { String filename = filename(viewName); byte[] bytes = resourceLoader.load(filename); if (bytes == null) return null; Mustache.TemplateLoader loader = loader(resourceLoader); String template = new String(bytes); Mustache.Compiler compiler = getViewFactory(resourceLoader); Template mustache = compiler.withLoader(loader).compile(template); return view(mustache); }
Example #21
Source File: LambdaTest.java From openapi-generator with Apache License 2.0 | 4 votes |
protected String execute(Mustache.Compiler compiler, String template, Object ctx) { return compiler.compile(template).execute(ctx); }
Example #22
Source File: TemplateRenderer.java From intellij-idea-plugin with Apache License 2.0 | 4 votes |
public TemplateRenderer(Mustache.Compiler mustache) { this.mustache = mustache; }
Example #23
Source File: TemplateRenderer.java From intellij-idea-plugin with Apache License 2.0 | 4 votes |
private static Mustache.Compiler mustacheCompiler() { return Mustache.compiler().withLoader(mustacheTemplateLoader()); }
Example #24
Source File: JMustacheViewResolver.java From rapidoid with Apache License 2.0 | 4 votes |
@Override protected Mustache.Compiler createViewFactory(ResourceLoader templateLoader) { return Mustache.compiler().withLoader(loader(templateLoader)); }
Example #25
Source File: MustacheViewResolver.java From spring-reactive-sample with GNU General Public License v3.0 | 4 votes |
/** * Create a {@code MustacheViewResolver} backed by a default instance of a * {@link Compiler}. */ public MustacheViewResolver() { this.compiler = Mustache.compiler(); setViewClass(requiredViewClass()); }
Example #26
Source File: CardGenerator.java From hccd with GNU General Public License v3.0 | 4 votes |
public static void generateCards(WatchedFiles projectFiles, UserConfiguration config) throws IOException { Hccd.log("Generating card sheet file..."); if (!projectFiles.getCsvFile().isFile()) { Hccd.log("CSV file does not exist. Generation aborted."); } else { String root = FilenameUtils.getBaseName(projectFiles.getHtmlFile().getName()); File target = new File(projectFiles.getParentDir(), root + GENERATED_SUFFIX + ".html"); String html = FileUtils.readFileToString(projectFiles.getHtmlFile()); Document doc = Jsoup.parse(html); String card = doc.select(".card").first().outerHtml(); Template template = Mustache.compiler().escapeHTML(false).defaultValue("[NOT FOUND]").compile(card); Iterable<CSVRecord> records = getData(projectFiles.getCsvFile(), config); // filter cards List<Integer> filter = config.getCardFilter(); List<CSVRecord> recordList = new ArrayList<>(); int index = 1; for (CSVRecord record : records) { if (filter.size() == 0 || filter.contains(index)) { recordList.add(record); } index++; } StringBuilder sb = new StringBuilder(); writeHeader(sb, projectFiles.getCssFile().getName()); Iterator<CSVRecord> recordIter = recordList.iterator(); int rows = config.getGridRowNumber(); int cols = config.getGridColNumber(); recordLoop: { while (recordIter.hasNext()) { sb.append("<table class=\"page\">"); for (int i = 0; i < rows; i++) { sb.append("<tr>"); for (int j = 0; j < cols; j++) { if (recordIter.hasNext()) { sb.append("<td>"); sb.append(template.execute(recordIter.next().toMap())); sb.append("</td>"); } else { sb.append("</tr></table>"); break recordLoop; } } sb.append("</tr>"); } sb.append("</table>"); } } writeFooter(sb); FileUtils.writeStringToFile(target, sb.toString()); Hccd.log("Card sheet file written to " + target.getPath()); } }
Example #27
Source File: MustacheServiceImpl.java From purplejs with Apache License 2.0 | 4 votes |
MustacheServiceImpl() { this.compiler = Mustache.compiler(); }
Example #28
Source File: TemplateContentCompiler.java From Bastion with GNU General Public License v3.0 | 4 votes |
private static Mustache.Compiler getCompiler() { Mustache.Compiler compiler = Mustache.compiler(); compiler.escapeHTML(false); compiler.withDelims("{{ }}"); return compiler; }
Example #29
Source File: AbstractOktaJavaClientCodegen.java From okta-sdk-java with Apache License 2.0 | 4 votes |
@Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); if(!BooleanUtils.toBoolean(model.isEnum)) { String datatype = property.datatype; if (datatype != null && datatype.matches(".+List$") && needToImport(datatype)) { model.imports.add(datatype); } String type = property.complexType; if (type == null) { type = property.baseType; } if (needToImport(type)) { model.imports.add(type); } // super add these imports, and we don't want that dependency model.imports.remove("ApiModelProperty"); model.imports.remove("ApiModel"); //final String lib = getLibrary(); //Needed imports for Jackson based libraries if(additionalProperties.containsKey("jackson")) { model.imports.add("JsonProperty"); } if(additionalProperties.containsKey("gson")) { model.imports.add("SerializedName"); } } else { // enum class //Needed imports for Jackson's JsonCreator if(additionalProperties.containsKey("jackson")) { model.imports.add("JsonCreator"); } } model.vendorExtensions.put("optionalClassnamePartial", (Mustache.Lambda) (frag, out) -> { String templateResource = "/" + templateDir + "/" + model.classname + ".mustache"; URL optionalClassnameTemplate = getClass().getResource(templateResource); Mustache.Compiler compiler = Mustache.compiler().withLoader((name) -> { if (optionalClassnameTemplate != null) { return new InputStreamReader(getClass().getResourceAsStream(templateResource), StandardCharsets.UTF_8); } return new StringReader(""); }); processCompiler(compiler).compile("{{> " + model.classname + "}}").execute(frag.context(), out); }); }
Example #30
Source File: TemplateFieldJoiningAnnotator.java From baleen with Apache License 2.0 | 4 votes |
@Override public void doInitialize(UimaContext aContext) throws ResourceInitializationException { super.doInitialize(aContext); touchedFields = gatherReferencedFields(); compiledTemplate = Mustache.compiler().compile(mustacheTemplate); }