org.thymeleaf.dialect.IDialect Java Examples

The following examples show how to use org.thymeleaf.dialect.IDialect. 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: WallRideThymeleafConfiguration.java    From wallride with Apache License 2.0 6 votes vote down vote up
@Bean
	public SpringTemplateEngine templateEngine(WallRideThymeleafDialect wallRideThymeleafDialect) {
		SpringTemplateEngine engine = new SpringTemplateEngine();
//		engine.setTemplateResolver(templateResolver());
		Set<ITemplateResolver> templateResolvers = new LinkedHashSet<>();
		templateResolvers.add(homePathTemplateResolver());
		templateResolvers.add(classPathTemplateResolver());
		engine.setTemplateResolvers(templateResolvers);

		Set<IDialect> dialects = new HashSet<>();
		dialects.add(new SpringSecurityDialect());
		dialects.add(new Java8TimeDialect());
		dialects.add(wallRideThymeleafDialect);
		engine.setAdditionalDialects(dialects);
		return engine;
	}
 
Example #2
Source File: ThymeleafTemplateEngineTest.java    From enkan with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void configure() {
    Set<IDialect> dialects = new HashSet<>();
    engine = builder(new ThymeleafTemplateEngine())
            .set(ThymeleafTemplateEngine::setDialects, dialects)
            .build();
    engine.lifecycle().start(engine);
    HttpResponse response = engine.render("test1", "name", "kawasima", "message", "hello");
    try (BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream) response.getBody()))) {
        String result = reader.lines().collect(Collectors.joining("\n"));
        System.out.println(result);
        assertTrue(result.contains("<span th:text=\"${name}\">"));
    } catch (IOException e) {
        fail("IOException occurred");
    }
}
 
Example #3
Source File: ThymeleafCsrfDialectTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@Test
public void testThatServiceIsRegisteredOnTheArrivalOfThymeleaf() {
    ThymeleafCsrfDialect component = new ThymeleafCsrfDialect();
    component.csrf = new CSRFServiceImpl();
    ((CSRFServiceImpl) component.csrf).crypto = new CryptoServiceSingleton(CSRFServiceImplTest.SECRET, Hash.MD5,
            128, Crypto.AES_CBC_ALGORITHM, 20);
    component.context = mock(BundleContext.class);
    when(component.context.registerService(any(Class.class), any(IDialect.class), Matchers.<Dictionary<String, Object>>any()))
            .thenReturn(mock(ServiceRegistration.class));

    assertThat(component.reg).isNull();

    TemplateEngine engine = mock(TemplateEngine.class);
    when(engine.name()).thenReturn("thymeleaf");
    component.bindTemplateEngine(engine);

    assertThat(component.reg).isNotNull();

    component.unbindTemplateEngine(engine);
    assertThat(component.reg).isNull();
}
 
Example #4
Source File: WisdomTemplateEngineTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomDialect() {
    MyDialect dialect = new MyDialect();
    final WisdomTemplateEngine engine = createWisdomEngine(ImmutableSet.<IDialect>of(dialect));
    engine.initialize();
    final Template template = mock(Template.class);
    when(template.fullName()).thenReturn("templates/dialect.thl.html");

    final FakeRouter router = new FakeRouter();
    final Controller controller = new FakeController();
    router.addController(controller);
    final Assets assets = mock(Assets.class);


    Action.ActionResult result = action(new Invocation() {
        @Override
        public Result invoke() throws Throwable {
            return ok(engine.process(template, controller, router, assets, ImmutableMap.<String, Object>of()));
        }
    }).parameter("key", "param").invoke();

    String content = (String) result.getResult().getRenderable().content();
    assertThat(content).contains("Hello, World!");
}
 
Example #5
Source File: ThymeleafConfig.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Bean
    public SpringTemplateEngine templateEngine(final ServletContextTemplateResolver templateResolver) {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver);
//        engine.setEnableSpringELCompiler(true);

        engine.setAdditionalDialects(new HashSet<IDialect>() {{
            add(new LayoutDialect());
            add(new SpringSecurityDialect());
        }});
        return engine;
    }
 
Example #6
Source File: ThymeleafCsrfDialect.java    From wisdom with Apache License 2.0 5 votes vote down vote up
protected IDialect createDialect() {
    return new AbstractDialect() {
        @Override
        public String getPrefix() {
            return "csrf";
        }

        @Override
        public Set<IProcessor> getProcessors() {
            return ImmutableSet.<IProcessor>of(new CSRFElementProcessor());
        }
    };
}
 
Example #7
Source File: WallRideMailConfiguration.java    From wallride with Apache License 2.0 5 votes vote down vote up
@Bean(name = "emailTemplateEngine")
public SpringTemplateEngine emailTemplateEngine() {
	SpringTemplateEngine engine = new SpringTemplateEngine();
	Set<ITemplateResolver> resolvers = new HashSet<>();
	resolvers.add(emailTemplateResolver());
	engine.setTemplateResolvers(resolvers);

	Set<IDialect> dialects = new HashSet<>();
	dialects.add(wallRideThymeleafDialect);
	dialects.add(new Java8TimeDialect());
	engine.setAdditionalDialects(dialects);
	return engine;
}
 
Example #8
Source File: WebAdminConfiguration.java    From wallride with Apache License 2.0 5 votes vote down vote up
@Bean
public SpringTemplateEngine templateEngine() {
	SpringTemplateEngine engine = new SpringTemplateEngine();
	Set<ITemplateResolver> resolvers = new HashSet<>();
	resolvers.add(adminTemplateResolver());
	engine.setTemplateResolvers(resolvers);

	Set<IDialect> dialects = new HashSet<>();
	dialects.add(new SpringSecurityDialect());
	dialects.add(new Java8TimeDialect());
	dialects.add(wallRideThymeleafDialect);
	engine.setAdditionalDialects(dialects);
	return engine;
}
 
Example #9
Source File: ThymeleafCsrfDialectTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@Test
public void testTheCreatedProcessorWhenNoTokenCreated() {
    ThymeleafCsrfDialect component = new ThymeleafCsrfDialect();
    component.csrf = new CSRFServiceImpl();
    ((CSRFServiceImpl) component.csrf).crypto = new CryptoServiceSingleton(CSRFServiceImplTest.SECRET, Hash.MD5,
            128, Crypto.AES_CBC_ALGORITHM, 20);
    final Configuration configuration = mock(Configuration.class);
    when(configuration.getWithDefault("token.name", "csrfToken")).thenReturn("csrfToken");
    ((CSRFServiceImpl) component.csrf).configuration = configuration;

    FakeContext ctxt = new FakeContext();
    Context.CONTEXT.set(ctxt);

    IDialect dialect = component.createDialect();
    assertThat(dialect.getPrefix()).isEqualToIgnoringCase("csrf");
    assertThat(dialect.getProcessors()).hasSize(1);

    IProcessor processor = dialect.getProcessors().iterator().next();
    assertThat(processor).isInstanceOf(ThymeleafCsrfDialect.CSRFElementProcessor.class);

    List<Node> nodes = ((ThymeleafCsrfDialect.CSRFElementProcessor) processor).getMarkupSubstitutes(null, null);
    assertThat(nodes).hasSize(1);
    assertThat(nodes.get(0)).isInstanceOf(Element.class);
    Element element = (Element) nodes.get(0);
    assertThat(element.getNormalizedName()).isEqualTo("input");
    assertThat(element.getAttributeFromNormalizedName("type").getValue()).isEqualTo("hidden");
    assertThat(element.getAttributeFromNormalizedName("name").getValue()).isEqualTo("csrfToken");
    assertThat(element.getAttributeFromNormalizedName("value").getValue()).isEqualTo("invalid");
}
 
Example #10
Source File: ThymeleafCsrfDialectTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@Test
public void testTheCreatedProcessorWithToken() {
    ThymeleafCsrfDialect component = new ThymeleafCsrfDialect();
    component.csrf = new CSRFServiceImpl();
    ((CSRFServiceImpl) component.csrf).crypto = new CryptoServiceSingleton(CSRFServiceImplTest.SECRET, Hash.MD5,
            128, Crypto.AES_CBC_ALGORITHM, 20);
    final Configuration configuration = mock(Configuration.class);
    when(configuration.getWithDefault("token.name", "csrfToken")).thenReturn("csrfToken");
    ((CSRFServiceImpl) component.csrf).configuration = configuration;

    FakeContext ctxt = new FakeContext();
    ctxt.getFakeRequest().data().put(CSRFServiceImpl.TOKEN_KEY, "token");
    Context.CONTEXT.set(ctxt);

    IDialect dialect = component.createDialect();
    assertThat(dialect.getPrefix()).isEqualToIgnoringCase("csrf");
    assertThat(dialect.getProcessors()).hasSize(1);

    IProcessor processor = dialect.getProcessors().iterator().next();
    assertThat(processor).isInstanceOf(ThymeleafCsrfDialect.CSRFElementProcessor.class);

    List<Node> nodes = ((ThymeleafCsrfDialect.CSRFElementProcessor) processor).getMarkupSubstitutes(null, null);
    assertThat(nodes).hasSize(1);
    assertThat(nodes.get(0)).isInstanceOf(Element.class);
    Element element = (Element) nodes.get(0);
    assertThat(element.getNormalizedName()).isEqualTo("input");
    assertThat(element.getAttributeFromNormalizedName("type").getValue()).isEqualTo("hidden");
    assertThat(element.getAttributeFromNormalizedName("name").getValue()).isEqualTo("csrfToken");
    assertThat(element.getAttributeFromNormalizedName("value").getValue()).isEqualTo("token");
}
 
Example #11
Source File: ThymeleafTemplateCollector.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * A new dialect is now available.
 * @param dialect the dialect
 */
@Bind(optional = true, aggregate = true)
public synchronized void bindDialect(IDialect dialect) {
    LOGGER.debug("Binding a new dialect using the prefix '{}' and containing {}",
            dialect.getPrefix(),
            dialect.getProcessors());
    if (this.dialects.add(dialect)) {
        // We must reconfigure the engine
        configure();
        // Update all templates.
        for (Template template : getTemplates()) {
            ((ThymeLeafTemplateImplementation) template).updateEngine(engine);
        }
    }
}
 
Example #12
Source File: ThymeleafTemplateCollector.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * A dialect has left.
 * @param dialect the dialect that has left
 */
@Unbind
public synchronized void unbindDialect(IDialect dialect) {
    LOGGER.debug("Binding a new dialect {}, processors: {}", dialect.getPrefix(),
            dialect.getProcessors());
    if (this.dialects.remove(dialect)) {
        configure();
        for (Template template : getTemplates()) {
            ((ThymeLeafTemplateImplementation) template).updateEngine(engine);
        }
    }
}
 
Example #13
Source File: WisdomTemplateEngine.java    From wisdom with Apache License 2.0 5 votes vote down vote up
public WisdomTemplateEngine(Set<IDialect> dialects) {
    super();
    // We clear the dialects as we are using our own standard dialect.
    clearDialects();
    addDialect(new WisdomStandardDialect());
    addDialect(new LayoutDialect());

    if (dialects != null) {
        setAdditionalDialects(dialects);
    }
}
 
Example #14
Source File: AddDialect.java    From ogham with Apache License 2.0 5 votes vote down vote up
private static MessagingService createService(IDialect dialect) {
	// init the builder with default values
	MessagingBuilder builder = MessagingBuilder.standard();
	// register the dialect for both email and sms
	builder.email()
			.template(ThymeleafV3EmailBuilder.class)
				.engine()
					.addDialect(dialect);
	builder.sms()
			.template(ThymeleafV3SmsBuilder.class)
				.engine()
					.addDialect(dialect);
	// instantiate the service
	return builder.build();
}
 
Example #15
Source File: ThymeleafConfig.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Bean
    public SpringTemplateEngine templateEngine(final ServletContextTemplateResolver templateResolver) {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver);
//        engine.setEnableSpringELCompiler(true);

        engine.setAdditionalDialects(new HashSet<IDialect>() {{
            add(new LayoutDialect());
            add(new SpringSecurityDialect());
        }});
        return engine;
    }
 
Example #16
Source File: ThymeleafConfig.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Bean
    public SpringTemplateEngine templateEngine(final ServletContextTemplateResolver templateResolver) {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver);
//        engine.setEnableSpringELCompiler(true);

        engine.setAdditionalDialects(new HashSet<IDialect>() {{
            add(new LayoutDialect());
            add(new SpringSecurityDialect());
        }});
        return engine;
    }
 
Example #17
Source File: ThymeleafConfig.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Bean
    public SpringTemplateEngine templateEngine(final ServletContextTemplateResolver templateResolver) {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver);
//        engine.setEnableSpringELCompiler(true);

        engine.setAdditionalDialects(new HashSet<IDialect>() {{
            add(new LayoutDialect());
            add(new SpringSecurityDialect());
        }});
        return engine;
    }
 
Example #18
Source File: ThymeleafTemplateCollectorTest.java    From wisdom with Apache License 2.0 4 votes vote down vote up
@Test
public void testBindAndUnbindDialects() throws Exception {
    BundleContext ctxt = mock(BundleContext.class);
    Bundle bundle = mock(Bundle.class);
    when(ctxt.getBundle()).thenReturn(bundle);
    when(bundle.getBundleContext()).thenReturn(ctxt);
    when(ctxt.registerService(any(Class.class), any(Template.class), any(Dictionary.class))).thenReturn(mock
            (ServiceRegistration.class));
    ThymeleafTemplateCollector collector = new ThymeleafTemplateCollector(ctxt);
    collector.configuration = mock(ApplicationConfiguration.class);
    when(collector.configuration.getWithDefault("application.template.thymeleaf.mode",
            "HTML5")).thenReturn("HTML5");
    when(collector.configuration.getIntegerWithDefault("application.template.thymeleaf.ttl",
            60 * 1000)).thenReturn(60 * 1000);
    collector.messageResolver = new WisdomMessageResolver();
    collector.configure();

    assertThat(collector.getTemplates()).isEmpty();
    WisdomTemplateEngine engine = collector.engine;
    File javascript = new File("src/test/resources/templates/javascript.thl.html");
    collector.addTemplate(bundle, javascript.toURI().toURL());

    assertThat(collector.getTemplates()).hasSize(1);

    IDialect dialect = new MyDialect();
    collector.bindDialect(dialect);
    assertThat(collector.engine).isNotSameAs(engine);
    engine = collector.engine;
    assertThat(collector.dialects).hasSize(1);

    // Rebind the same.
    collector.bindDialect(dialect);
    assertThat(collector.engine).isSameAs(engine);
    assertThat(collector.dialects).hasSize(1);

    // Unbind
    collector.unbindDialect(dialect);
    assertThat(collector.dialects).hasSize(0);
    assertThat(collector.engine).isNotSameAs(engine);
    engine = collector.engine;

    collector.unbindDialect(dialect);
    assertThat(collector.dialects).hasSize(0);
    assertThat(collector.engine).isSameAs(engine);
}
 
Example #19
Source File: WisdomTemplateEngineTest.java    From wisdom with Apache License 2.0 4 votes vote down vote up
@Test
public void testCustomDialectDynamics() throws MalformedURLException {
    MyDialect dialect = new MyDialect();
    MyFileTemplateResolver resolver = new MyFileTemplateResolver();
    final WisdomTemplateEngine engine = createWisdomEngine(ImmutableSet.<IDialect>of(dialect));
    engine.setTemplateResolver(resolver);
    engine.initialize();
    File file = new File("src/test/resources/templates/dialect.thl.html");
    assertThat(file).exists();

    final FakeRouter router = new FakeRouter();
    final Controller controller = new FakeController();
    final Assets assets = mock(Assets.class);
    final ThymeLeafTemplateImplementation template = new ThymeLeafTemplateImplementation(engine, file, router,
            assets, null);
    router.addController(controller);

    Action.ActionResult result = action(new Invocation() {
        @Override
        public Result invoke() throws Throwable {
            return ok(template.render(controller));

        }
    }).invoke();

    String content = (String) result.getResult().getRenderable().content();
    assertThat(content).contains("Hello, World!");

    final WisdomTemplateEngine engine2 = createWisdomEngine();
    engine2.setTemplateResolver(resolver);
    engine2.initialize();
    template.updateEngine(engine2);

    result = action(new Invocation() {
        @Override
        public Result invoke() throws Throwable {
            return ok(template.render(controller));
        }
    }).invoke();

    content = (String) result.getResult().getRenderable().content();
    assertThat(content).doesNotContain("Hello, World!").contains("Hi ya!");
}
 
Example #20
Source File: WisdomTemplateEngineTest.java    From wisdom with Apache License 2.0 4 votes vote down vote up
private WisdomTemplateEngine createWisdomEngine(Set<IDialect> dialects) {
    WisdomTemplateEngine engine = new WisdomTemplateEngine(dialects);
    engine.setTemplateResolver(new ClassLoaderTemplateResolver());
    return engine;
}
 
Example #21
Source File: WisdomTemplateEngineTest.java    From wisdom with Apache License 2.0 4 votes vote down vote up
private WisdomTemplateEngine createWisdomEngine() {
    return createWisdomEngine(Collections.<IDialect>emptySet());
}
 
Example #22
Source File: ThymeleafCsrfDialect.java    From wisdom with Apache License 2.0 4 votes vote down vote up
private void publishDialect() {
    reg = context.registerService(IDialect.class, createDialect(), null);
}
 
Example #23
Source File: AbstractThymeleafEngineConfigBuilder.java    From ogham with Apache License 2.0 4 votes vote down vote up
protected Map<String, IDialect> dialectsByPrefix() {
	if (dialectsByPrefix == null) {
		dialectsByPrefix = new HashMap<>();
	}
	return dialectsByPrefix;
}
 
Example #24
Source File: AbstractThymeleafEngineConfigBuilder.java    From ogham with Apache License 2.0 4 votes vote down vote up
protected Set<IDialect> dialects() {
	if (dialects == null) {
		dialects = new HashSet<>();
	}
	return dialects;
}
 
Example #25
Source File: AddDialect.java    From ogham with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
	IDialect dialect = null;
	createService(dialect);
}
 
Example #26
Source File: ThymeleafServiceImpl.java    From purplejs with Apache License 2.0 4 votes vote down vote up
private static Set<IDialect> loadDialects()
{
    return Sets.newHashSet( ServiceLoader.load( IDialect.class ) );
}
 
Example #27
Source File: ThymeleafTemplateEngine.java    From enkan with Eclipse Public License 1.0 4 votes vote down vote up
public void setDialects(Set<IDialect> dialects) {
    this.dialects = dialects;
}
 
Example #28
Source File: AbstractThymeleafEngineConfigBuilder.java    From ogham with Apache License 2.0 2 votes vote down vote up
/**
 * <p>
 * Sets an additional set of dialects for this template engine, all of them
 * using their default prefixes.
 * </p>
 * <p>
 * This operation can only be executed before processing templates for the
 * first time. Once a template is processed, the template engine is
 * considered to be <i>initialized</i>, and from then on any attempt to
 * change its configuration will result in an exception.
 * </p>
 * 
 * @param additionalDialects
 *            the new set of {@link IDialect} objects to be used.
 * 
 * @since 2.0.9
 * @return this for fluent use
 */
public MYSELF setAdditionalDialects(final Set<IDialect> additionalDialects) {
	dialects().addAll(additionalDialects);
	return myself;
}
 
Example #29
Source File: AbstractThymeleafEngineConfigBuilder.java    From ogham with Apache License 2.0 2 votes vote down vote up
/**
 * <p>
 * Sets a new set of dialects for this template engine, all of them using
 * their default prefixes.
 * </p>
 * <p>
 * This operation can only be executed before processing templates for the
 * first time. Once a template is processed, the template engine is
 * considered to be <i>initialized</i>, and from then on any attempt to
 * change its configuration will result in an exception.
 * </p>
 * 
 * @param dialects
 *            the new set of {@link IDialect} objects to be used.
 * @return this for fluent use
 */
public MYSELF setDialects(final Set<IDialect> dialects) {
	this.dialects().clear();
	this.dialects().addAll(dialects);
	return myself;
}
 
Example #30
Source File: AbstractThymeleafEngineConfigBuilder.java    From ogham with Apache License 2.0 2 votes vote down vote up
/**
 * <p>
 * Sets a new set of dialects for this template engine, referenced by the
 * prefixes they will be using.
 * </p>
 * <p>
 * This operation can only be executed before processing templates for the
 * first time. Once a template is processed, the template engine is
 * considered to be <i>initialized</i>, and from then on any attempt to
 * change its configuration will result in an exception.
 * </p>
 * 
 * @param dialects
 *            the new map of {@link IDialect} objects to be used, referenced
 *            by their prefixes.
 * @return this for fluent use
 */
public MYSELF setDialectsByPrefix(final Map<String, IDialect> dialects) {
	dialectsByPrefix().clear();
	dialectsByPrefix().putAll(dialects);
	return myself;
}