org.trimou.engine.config.EngineConfigurationKey Java Examples

The following examples show how to use org.trimou.engine.config.EngineConfigurationKey. 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: MustacheEngineTest.java    From trimou with Apache License 2.0 6 votes vote down vote up
@Test
public void testTemplateCacheUsedForSource() {
    final AtomicInteger locatorCalled = new AtomicInteger(0);
    MustacheEngine engine = MustacheEngineBuilder.newBuilder()
            .addTemplateLocator((name) -> {
                locatorCalled.incrementAndGet();
                return new StringReader("{{this}}");
            }).build();
    assertEquals("{{this}}", engine.getMustacheSource("any"));
    assertEquals("{{this}}", engine.getMustacheSource("any"));
    assertEquals(2, locatorCalled.get());
    locatorCalled.set(0);
    engine = MustacheEngineBuilder.newBuilder()
            .setProperty(
                    EngineConfigurationKey.TEMPLATE_CACHE_USED_FOR_SOURCE,
                    true)
            .addTemplateLocator((name) -> {
                locatorCalled.incrementAndGet();
                return new StringReader("{{this}}");
            }).build();
    assertEquals("{{this}}", engine.getMustacheSource("any"));
    assertEquals("{{this}}", engine.getMustacheSource("any"));
    assertEquals(1, locatorCalled.get());
}
 
Example #2
Source File: ServletContextTemplateLocatorTest.java    From trimou with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncoding() {

    TemplateLocator locator = new ServletContextTemplateLocator(10,
            "/templates", "html");

    MustacheEngine engine = MustacheEngineBuilder.newBuilder()
            .addTemplateLocator(locator)
            .setProperty(EngineConfigurationKey.DEFAULT_FILE_ENCODING,
                    "windows-1250")
            .build();

    Mustache encoding = engine.getMustache("encoding");
    assertNotNull(encoding);
    assertEquals("Hurá ěščřřžžýá!", encoding.render(null));
}
 
Example #3
Source File: MustacheEngineProducer.java    From trimou with Apache License 2.0 6 votes vote down vote up
@ApplicationScoped
@Produces
public MustacheEngine produceMustacheEngine(
        SimpleStatsCollector simpleStatsCollector) {
    // 1. CDI and servlet resolvers are registered automatically
    // 2. Precompile all available templates
    // 3. Do not escape values
    // 4. PrettyTimeHelper is registered automatically
    // 5. Register extra helpers (set, isOdd, ...)
    // 6. ServletContextTemplateLocator is most suitable for webapps
    // 7. The current locale will be based on the Accept-Language header
    // 8. Minify all the templates
    // 9. Collect some basic rendering statistics
    return MustacheEngineBuilder.newBuilder()
            .setProperty(EngineConfigurationKey.PRECOMPILE_ALL_TEMPLATES,
                    true)
            .setProperty(EngineConfigurationKey.SKIP_VALUE_ESCAPING, true)
            .registerHelpers(HelpersBuilder.extra()
                    .add("format", new DateTimeFormatHelper()).build())
            .addTemplateLocator(ServletContextTemplateLocator.builder()
                    .setRootPath("/WEB-INF/templates").setSuffix("html")
                    .build())
            .setLocaleSupport(new RequestLocaleSupport())
            .addMustacheListener(Minify.htmlListener())
            .addMustacheListener(simpleStatsCollector).build();
}
 
Example #4
Source File: TrimouProperties.java    From trimou with Apache License 2.0 6 votes vote down vote up
/**
 * Apply the {@link TrimouProperties} to a {@link MustacheEngineBuilder}.
 *
 * @param engineBuilder the Trimou mustache engine builder to apply the properties to
 */
public void applyToTrimouMustacheEngineBuilder(final MustacheEngineBuilder engineBuilder) {
    engineBuilder
            .setProperty(EngineConfigurationKey.START_DELIMITER, getStartDelimiter())
            .setProperty(EngineConfigurationKey.END_DELIMITER, getEndDelimiter())
            .setProperty(EngineConfigurationKey.PRECOMPILE_ALL_TEMPLATES, isPrecompileTemplates())
            .setProperty(EngineConfigurationKey.REMOVE_STANDALONE_LINES, isRemoveStandaloneLines())
            .setProperty(EngineConfigurationKey.REMOVE_UNNECESSARY_SEGMENTS, isRemoveUnnecessarySegments())
            .setProperty(EngineConfigurationKey.DEBUG_MODE, isDebugMode())
            .setProperty(EngineConfigurationKey.CACHE_SECTION_LITERAL_BLOCK, isCacheSectionLiteralBlock())
            .setProperty(EngineConfigurationKey.TEMPLATE_RECURSIVE_INVOCATION_LIMIT,
                    getTemplateRecursiveInvocationLimit())
            .setProperty(EngineConfigurationKey.SKIP_VALUE_ESCAPING, isSkipValueEscaping())
            .setProperty(EngineConfigurationKey.DEFAULT_FILE_ENCODING, getCharset().name())
            .setProperty(EngineConfigurationKey.TEMPLATE_CACHE_ENABLED, isCache())
            .setProperty(EngineConfigurationKey.TEMPLATE_CACHE_EXPIRATION_TIMEOUT,
                    getTemplateCacheExpirationTimeout())
            .setProperty(EngineConfigurationKey.HANDLEBARS_SUPPORT_ENABLED, isEnableHelper())
            .setProperty(EngineConfigurationKey.REUSE_LINE_SEPARATOR_SEGMENTS, isReuseLineSeparatorSegments())
            .setProperty(EngineConfigurationKey.ITERATION_METADATA_ALIAS, getIterationMetadataAlias())
            .setProperty(EngineConfigurationKey.RESOLVER_HINTS_ENABLED, isEnableResolverHints())
            .setProperty(EngineConfigurationKey.NESTED_TEMPLATE_SUPPORT_ENABLED, isEnableNestedTemplates())
            .setProperty(EngineConfigurationKey.TEMPLATE_CACHE_USED_FOR_SOURCE, isCacheTemplateSources());
}
 
Example #5
Source File: Trimou.java    From template-benchmark with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Setup
public void setup() {
    template = MustacheEngineBuilder.newBuilder()
            // Disable HTML escaping
            .setProperty(EngineConfigurationKey.SKIP_VALUE_ESCAPING, true)
            // Disable useless resolver
            .setProperty(CombinedIndexResolver.ENABLED_KEY, false)
            .addTemplateLocator(ClassPathTemplateLocator.builder(1).setRootPath("templates").setScanClasspath(false).setSuffix("trimou.html").build())
            .registerHelpers(HelpersBuilder.extra().build())
            // This is a single purpose helper
            // It's a pity we can't use JDK8 extension and SimpleHelpers util class
            .registerHelper("minusClass", new BasicValueHelper() {
                @Override
                public void execute(Options options) {
                    Object value = options.getParameters().get(0);
                    if (value instanceof Double && (Double) value < 0) {
                        options.append(" class=\"minus\"");
                    }
                    // We don't handle any other number types
                }
            }).build().getMustache("stocks");
    this.context = getContext();
}
 
Example #6
Source File: TrimouViewResolverTest.java    From trimou with Apache License 2.0 6 votes vote down vote up
@Test
public void cacheDisabled() throws Exception {
    resolver.setEngine(MustacheEngineBuilder.newBuilder()
            .setProperty(EngineConfigurationKey.TEMPLATE_CACHE_ENABLED, false)
            .setProperty(EngineConfigurationKey.DEBUG_MODE, false)
            .build());
    assertThat(resolver.isCache(), is(false));
    resolver.setEngine(MustacheEngineBuilder.newBuilder()
            .setProperty(EngineConfigurationKey.TEMPLATE_CACHE_ENABLED, true)
            .setProperty(EngineConfigurationKey.DEBUG_MODE, true)
            .build());
    assertThat(resolver.isCache(), is(false));
    resolver.setEngine(MustacheEngineBuilder.newBuilder()
            .setProperty(EngineConfigurationKey.TEMPLATE_CACHE_ENABLED, false)
            .setProperty(EngineConfigurationKey.DEBUG_MODE, true)
            .build());
    assertThat(resolver.isCache(), is(false));
    resolver.setEngine(MustacheEngineBuilder.newBuilder()
            .setProperty(EngineConfigurationKey.TEMPLATE_CACHE_ENABLED, true)
            .setProperty(EngineConfigurationKey.DEBUG_MODE, false)
            .build());
    assertThat(resolver.isCache(), is(true));
    resolver.setCacheLimit(0);
    assertThat(resolver.isCache(), is(false));
}
 
Example #7
Source File: TrimouViewResolver.java    From trimou with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    engine = MustacheEngineBuilder.newBuilder()
            .setProperty(EngineConfigurationKey.TEMPLATE_CACHE_ENABLED,
                    isCache())
            .setProperty(
                    EngineConfigurationKey.TEMPLATE_CACHE_EXPIRATION_TIMEOUT,
                    getCacheExpiration())
            .setProperty(EngineConfigurationKey.DEFAULT_FILE_ENCODING,
                    getFileEncoding())
            .setProperty(EngineConfigurationKey.HANDLEBARS_SUPPORT_ENABLED,
                    isHandlebarsSupport())
            .setProperty(EngineConfigurationKey.DEBUG_MODE, isDebug())
            .setProperty(EngineConfigurationKey.PRECOMPILE_ALL_TEMPLATES,
                    isPreCompile())
            .registerHelpers(helpers)
            .addTemplateLocator(ServletContextTemplateLocator.builder()
                    .setPriority(1).setRootPath(getPrefix())
                    .setSuffix(getSuffixWithoutSeparator())
                    .setServletContext(getServletContext()).build())
            .build();
}
 
Example #8
Source File: DefaultParsingHandler.java    From trimou with Apache License 2.0 6 votes vote down vote up
@Override
public void startTemplate(String name, Delimiters delimiters,
        MustacheEngine engine) {

    this.delimiters = delimiters;
    this.engine = engine;
    this.templateName = name;

    containerStack.addFirst(new RootSegmentBase());

    skipValueEscaping = engine.getConfiguration().getBooleanPropertyValue(
            EngineConfigurationKey.SKIP_VALUE_ESCAPING);
    handlebarsSupportEnabled = engine.getConfiguration()
            .getBooleanPropertyValue(
                    EngineConfigurationKey.HANDLEBARS_SUPPORT_ENABLED);

    start = System.currentTimeMillis();
    LOGGER.debug("Start compilation of {}", new Object[] { name });
}
 
Example #9
Source File: DefaultParser.java    From trimou with Apache License 2.0 6 votes vote down vote up
/**
 * Identify the tag type (variable, comment, etc.).
 *
 * @param buffer
 * @param delimiters
 * @return the tag type
 */
private MustacheTagType identifyTagType(String buffer) {

    if (buffer.length() == 0) {
        return MustacheTagType.VARIABLE;
    }

    // Triple mustache is supported for default delimiters only
    if (delimiters.hasDefaultDelimitersSet()
            && buffer.charAt(0) == ((String) EngineConfigurationKey.START_DELIMITER
                    .getDefaultValue()).charAt(0)
            && buffer.charAt(buffer.length() - 1) == ((String) EngineConfigurationKey.END_DELIMITER
                    .getDefaultValue()).charAt(0)) {
        return MustacheTagType.UNESCAPE_VARIABLE;
    }

    Character command = buffer.charAt(0);

    for (MustacheTagType type : MustacheTagType.values()) {
        if (command.equals(type.getCommand())) {
            return type;
        }
    }
    return MustacheTagType.VARIABLE;
}
 
Example #10
Source File: DefaultParser.java    From trimou with Apache License 2.0 6 votes vote down vote up
/**
 * Extract the tag content.
 *
 * @param buffer
 * @return
 */
private String extractContent(MustacheTagType tagType, String buffer) {

    switch (tagType) {
    case VARIABLE:
        return buffer.trim();
    case UNESCAPE_VARIABLE:
        return (buffer.charAt(0) == ((String) EngineConfigurationKey.START_DELIMITER
                .getDefaultValue()).charAt(0) ? buffer.substring(1,
                buffer.length() - 1).trim() : buffer.substring(1).trim());
    case SECTION:
    case INVERTED_SECTION:
    case PARTIAL:
    case EXTEND:
    case EXTEND_SECTION:
    case SECTION_END:
    case NESTED_TEMPLATE:
    case COMMENT:
        return buffer.substring(1).trim();
    case DELIMITER:
        return buffer.trim();
    default:
        return null;
    }
}
 
Example #11
Source File: SectionSegment.java    From trimou with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param text
 * @param origin
 * @param segments
 */
public SectionSegment(String text, Origin origin, List<Segment> segments) {
    super(text, origin, segments);
    this.helperHandler = isHandlebarsSupportEnabled()
            ? HelperExecutionHandler.from(text, getEngine(), this) : null;

    if (helperHandler == null) {
        this.iterationMetaAlias = getEngineConfiguration()
                .getStringPropertyValue(
                        EngineConfigurationKey.ITERATION_METADATA_ALIAS);
        this.provider = new ValueProvider(text, getEngineConfiguration());
    } else {
        this.iterationMetaAlias = null;
        this.provider = null;
    }
}
 
Example #12
Source File: ValueProvider.java    From trimou with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param text
 * @param configuration
 */
ValueProvider(String text, Configuration configuration) {
    this.key = text;
    ArrayList<String> parts = new ArrayList<>();
    for (Iterator<String> iterator = configuration.getKeySplitter()
            .split(text); iterator.hasNext();) {
        parts.add(iterator.next());
    }
    this.keyParts = parts.toArray(new String[parts.size()]);
    if (configuration.getBooleanPropertyValue(
            EngineConfigurationKey.RESOLVER_HINTS_ENABLED)) {
        this.hint = new AtomicReference<>();
    } else {
        this.hint = null;
    }
}
 
Example #13
Source File: ExtendSegmentTest.java    From trimou with Apache License 2.0 6 votes vote down vote up
@Test
public void testRecursiveInvocationLimitExceeded() {

    MapTemplateLocator locator = new MapTemplateLocator(ImmutableMap.of(
            "super", "/n{{<super}}{{/super}}"));
    MustacheEngine engine = MustacheEngineBuilder
            .newBuilder()
            .addTemplateLocator(locator)
            .setProperty(
                    EngineConfigurationKey.TEMPLATE_RECURSIVE_INVOCATION_LIMIT,
                    5).build();

    try {
        engine.getMustache("super").render(null);
        fail("Limit exceeded and no exception thrown");
    } catch (MustacheException e) {
        if (!e.getCode()
                .equals(MustacheProblem.RENDER_TEMPLATE_INVOCATION_RECURSIVE_LIMIT_EXCEEDED)) {
            fail("Invalid problem");
        }
        System.out.println(e.getMessage());
        // else {
        // e.printStackTrace();
        // }
    }
}
 
Example #14
Source File: LiteralBlockSegmentTest.java    From trimou with Apache License 2.0 6 votes vote down vote up
@Before
public void buildEngine() {
    textParam = null;

    MapTemplateLocator locator = new MapTemplateLocator(ImmutableMap.of(
            "partial", "{{! No content}}", "super",
            "{{$extendMe}}Hello{{/extendMe}}"));

    engine = MustacheEngineBuilder
            .newBuilder()
            .addGlobalData("foo", foo)
            .addTemplateLocator(locator)
            .setProperty(
                    EngineConfigurationKey.REMOVE_UNNECESSARY_SEGMENTS,
                    false).build();
}
 
Example #15
Source File: PartialSegmentTest.java    From trimou with Apache License 2.0 6 votes vote down vote up
@Test
public void testTemplateInvocationsStack() {
    // See also bug #42
    String partial = "!";
    StringBuilder template = new StringBuilder();
    StringBuilder result = new StringBuilder();
    int loop = 2 * Integer
            .valueOf(EngineConfigurationKey.TEMPLATE_RECURSIVE_INVOCATION_LIMIT
                    .getDefaultValue().toString());
    for (int i = 0; i < loop; i++) {
        template.append("{{> partial}}");
        result.append(partial);
    }
    MustacheEngine engine = MustacheEngineBuilder
            .newBuilder()
            .addTemplateLocator(
                    new MapTemplateLocator(ImmutableMap.of("template",
                            template.toString(), "partial",
                            partial.toString()))).build();
    assertEquals(result.toString(),
            engine.getMustache("template").render(null));
}
 
Example #16
Source File: ValueSegmentTest.java    From trimou with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
// EngineConfigurationKey.NO_VALUE_INDICATES_PROBLEM used intentionally to
// test backwards compatibility
@Test
public void testNoValueProblem() {
    try {
        MustacheEngineBuilder
                .newBuilder()
                .setProperty(
                        EngineConfigurationKey.NO_VALUE_INDICATES_PROBLEM,
                        true).build()
                .compileMustache("value_segment_problem", "{{foo}}")
                .render(null);
    } catch (MustacheException e) {
        if (!e.getCode().equals(MustacheProblem.RENDER_NO_VALUE)) {
            fail("Invalid problem");
        }
        System.out.println(e.getMessage());
    }
}
 
Example #17
Source File: ValueSegmentTest.java    From trimou with Apache License 2.0 6 votes vote down vote up
@Test
public void testValueEscaping() {
    String shouldBeEscaped = "<&>";
    assertEquals(
            "&lt;&amp;&gt;",
            MustacheEngineBuilder
                    .newBuilder()
                    .build()
                    .compileMustache("value_escaping", "{{foo}}")
                    .render(ImmutableMap.<String, Object> of("foo",
                            shouldBeEscaped)));
    assertEquals(
            shouldBeEscaped,
            MustacheEngineBuilder
                    .newBuilder()
                    .setProperty(
                            EngineConfigurationKey.SKIP_VALUE_ESCAPING,
                            true)
                    .build()
                    .compileMustache("skip_value_escaping", "{{foo}}")
                    .render(ImmutableMap.<String, Object> of("foo",
                            shouldBeEscaped)));
}
 
Example #18
Source File: MustacheEngineTest.java    From trimou with Apache License 2.0 6 votes vote down vote up
@Test
public void testTemplateCacheExpirationTimeout()
        throws InterruptedException {

    Map<String, String> templates = new HashMap<>();
    templates.put("foo", "0");
    long timeout = 1;

    MustacheEngine engine = MustacheEngineBuilder
            .newBuilder()
            .setProperty(
                    EngineConfigurationKey.TEMPLATE_CACHE_EXPIRATION_TIMEOUT,
                    timeout)
            .addTemplateLocator(new MapTemplateLocator(templates)).build();
    assertEquals("0", engine.getMustache("foo").render(null));
    templates.put("foo", "1");
    assertEquals("0", engine.getMustache("foo").render(null));
    Thread.sleep((2 * timeout) * 1000);
    assertEquals("1", engine.getMustache("foo").render(null));
}
 
Example #19
Source File: DefaultMustacheEngine.java    From trimou with Apache License 2.0 6 votes vote down vote up
private <K, V> ComputingCache<K, V> buildCache(String name,
        ComputingCache.Function<K, V> loader,
        ComputingCache.Listener<K> listener) {

    Long expirationTimeout = configuration.getLongPropertyValue(
            EngineConfigurationKey.TEMPLATE_CACHE_EXPIRATION_TIMEOUT);

    if (expirationTimeout > 0) {
        LOGGER.info("{} cache expiration timeout set: {} seconds", name, expirationTimeout);
        expirationTimeout = expirationTimeout * 1000L;
    } else {
        expirationTimeout = null;
    }
    return configuration.getComputingCacheFactory().create(
            MustacheEngine.COMPUTING_CACHE_CONSUMER_ID, loader,
            expirationTimeout, null, listener);
}
 
Example #20
Source File: ApiGeneratorProcessor.java    From flo with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
  super.init(processingEnv);
  types = processingEnv.getTypeUtils();
  elements = processingEnv.getElementUtils();
  filer = processingEnv.getFiler();
  messager = processingEnv.getMessager();

  engine = MustacheEngineBuilder
      .newBuilder()
      .addResolver(new MapResolver())
      .addResolver(new ReflectionResolver())
      .setProperty(EngineConfigurationKey.DEFAULT_FILE_ENCODING, StandardCharsets.UTF_8.name())
      .addTemplateLocator(ClassPathTemplateLocator.builder(1)
                              .setClassLoader(this.getClass().getClassLoader())
                              .setSuffix("mustache").build())
      .build();

  messager.printMessage(NOTE, ApiGeneratorProcessor.class.getSimpleName() + " loaded");
}
 
Example #21
Source File: TrimouProperties.java    From trimou with Apache License 2.0 5 votes vote down vote up
public TrimouProperties() {
    super(SpringResourceTemplateLocator.DEFAULT_PREFIX, SpringResourceTemplateLocator.DEFAULT_SUFFIX);
    final boolean cacheEnabled = getDefaultBooleanValue(EngineConfigurationKey.TEMPLATE_CACHE_ENABLED);
    setCache(cacheEnabled);
    if (getCharset() == null) {
        setCharset(StandardCharsets.UTF_8);
    }
}
 
Example #22
Source File: FileSystemTemplateLocatorTest.java    From trimou with Apache License 2.0 5 votes vote down vote up
@Test
public void testEncoding() throws IOException {
    TemplateLocator locator = new FileSystemTemplateLocator(1,
            "src/test/resources/locator/file", "html");
    // Just to init the locator
    MustacheEngineBuilder.newBuilder()
            .setProperty(EngineConfigurationKey.DEFAULT_FILE_ENCODING,
                    "windows-1250")
            .addTemplateLocator(locator).build();
    assertEquals("Hurá ěščřřžžýá!", read(locator.locate("encoding")));
}
 
Example #23
Source File: ExtendSegmentTest.java    From trimou with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecursiveInvocationAllowed() {
    MapTemplateLocator locator = new MapTemplateLocator(
            ImmutableMap
                    .of("super",
                            "{{$content}}{{<super}}{{$content}}Mooo{{/content}}{{/super}}{{/content}}"));
    MustacheEngine engine = MustacheEngineBuilder
            .newBuilder()
            .addTemplateLocator(locator)
            .setProperty(
                    EngineConfigurationKey.TEMPLATE_RECURSIVE_INVOCATION_LIMIT,
                    5).build();
    assertEquals("Mooo", engine.getMustache("super").render(null));
}
 
Example #24
Source File: ClassPathTemplateLocatorTest.java    From trimou with Apache License 2.0 5 votes vote down vote up
@Test
public void testEncoding() throws IOException {
    TemplateLocator locator = new ClassPathTemplateLocator(1,
            "locator/file", "html");
    // Just to init the locator
    MustacheEngineBuilder
            .newBuilder()
            .setProperty(EngineConfigurationKey.DEFAULT_FILE_ENCODING,
                    "windows-1250").addTemplateLocator(locator).build();
    assertEquals("Hurá ěščřřžžýá!", read(locator.locate("encoding")));
}
 
Example #25
Source File: ExtendSegmentTest.java    From trimou with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecursiveInvocationDisabled() {
    MapTemplateLocator locator = new MapTemplateLocator(
            ImmutableMap
                    .of("super",
                            "{{$content}}{{<super}}{{$content}}Mooo{{/content}}{{/super}}{{/content}}"));
    MustacheEngine engine = MustacheEngineBuilder
            .newBuilder()
            .addTemplateLocator(locator)
            .setProperty(
                    EngineConfigurationKey.TEMPLATE_RECURSIVE_INVOCATION_LIMIT,
                    0).build();

    try {
        engine.getMustache("super").render(null);
        fail("Limit exceeded and no exception thrown");
    } catch (MustacheException e) {
        if (!e.getCode()
                .equals(MustacheProblem.RENDER_TEMPLATE_INVOCATION_RECURSIVE_LIMIT_EXCEEDED)) {
            fail("Invalid problem");
        }
        System.out.println(e.getMessage());
        // else {
        // e.printStackTrace();
        // }
    }
}
 
Example #26
Source File: Patterns.java    From trimou with Apache License 2.0 5 votes vote down vote up
/**
 * Delimiters are quoted to avoid regexp reserved characters conflict.
 *
 * @param configuration
 * @return the new delimiters pattern
 */
public static Pattern newMustacheTagPattern(Configuration configuration) {
    StringBuilder regex = new StringBuilder();
    regex.append(Pattern.quote(configuration
            .getStringPropertyValue(EngineConfigurationKey.START_DELIMITER)));
    regex.append(".*?");
    regex.append(Pattern.quote(configuration
            .getStringPropertyValue(EngineConfigurationKey.END_DELIMITER)));
    return Pattern.compile(regex.toString());
}
 
Example #27
Source File: ExtendSegmentTest.java    From trimou with Apache License 2.0 5 votes vote down vote up
@Test
public void testCachedPartialSegmentNotUsed() {
    Map<String, String> map = new HashMap<>();
    map.put("super", "{{$section1}}Martin{{/section1}}");
    map.put("sub", "{{<super}}{{$section1}}{{this}}{{/section1}}{{/super}}");
    MapTemplateLocator locator = new MapTemplateLocator(map);
    MustacheEngine engine = MustacheEngineBuilder.newBuilder()
            .addTemplateLocator(locator).setProperty(EngineConfigurationKey.DEBUG_MODE, true).build();
    Mustache mustache = engine.getMustache("sub");
    assertEquals("foo", mustache.render("foo"));
    map.put("super", "{{$section2}}Martin{{/section2}}");
    engine.invalidateTemplateCache();
    assertEquals("Martin", mustache.render("foo"));
}
 
Example #28
Source File: TrimouViewRenderer.java    From trimou with Apache License 2.0 5 votes vote down vote up
@Override
public void render(View view, Locale locale, OutputStream output) throws IOException, WebApplicationException {

    Mustache template = null;

    if (hasLocalizedTemplates && locale != null) {
        // First try the Locale
        template = engine.getMustache(getLocalizedTemplateName(view.getTemplateName(), locale.toString()));
        if (template == null) {
            // Then only the language
            template = engine.getMustache(getLocalizedTemplateName(view.getTemplateName(), locale.getLanguage()));
        }
    }

    if (template == null) {
        template = engine.getMustache(view.getTemplateName());
    }

    if (template == null) {
        throw new FileNotFoundException("Template not found: " + view.getTemplateName());
    }

    final Writer writer = new OutputStreamWriter(output, engine.getConfiguration().getStringPropertyValue(EngineConfigurationKey.DEFAULT_FILE_ENCODING));

    try {
        template.render(writer, view);
    } catch (MustacheException e) {
        throw new IOException(e);
    } finally {
        writer.flush();
    }
}
 
Example #29
Source File: TrimouViewResolver.java    From trimou with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true, if the cache of the {@link MustacheEngine} is enabled and the debug mode is disabled. Also Spring's
 * view resolution caching must be enabled.
 */
@Override
public boolean isCache() {
    return engine.getConfiguration().getBooleanPropertyValue(EngineConfigurationKey.TEMPLATE_CACHE_ENABLED)
            && !engine.getConfiguration().getBooleanPropertyValue(EngineConfigurationKey.DEBUG_MODE)
            && super.isCache();
}
 
Example #30
Source File: NestedTemplateTest.java    From trimou with Apache License 2.0 5 votes vote down vote up
@Test
public void testNestedTemplateSupportDisabled() {
    engine = MustacheEngineBuilder.newBuilder()
            .addGlobalData("+foo", "Hello")
            .setProperty(
                    EngineConfigurationKey.NESTED_TEMPLATE_SUPPORT_ENABLED,
                    false)
            .build();
    assertEquals("Hello world!",
            engine.compileMustache("nested_disabled", "{{+foo}} world!")
                    .render(null));
}