9f714a08fa52544f2d1ffa2b772e5472be4c3b62
[juplo-dialect] / src / main / java / de / juplo / thymeleaf / ActiveElementProcessor.java
1 package de.juplo.thymeleaf;
2
3
4 import org.thymeleaf.Arguments;
5 import org.thymeleaf.Configuration;
6 import org.thymeleaf.dom.Element;
7 import org.thymeleaf.dom.Node;
8 import org.thymeleaf.processor.AbstractProcessor;
9 import org.thymeleaf.processor.IProcessorMatcher;
10 import org.thymeleaf.processor.ProcessorMatchingContext;
11 import org.thymeleaf.processor.ProcessorResult;
12 import org.thymeleaf.processor.AttributeNameProcessorMatcher;
13 import org.thymeleaf.standard.expression.IStandardExpression;
14 import org.thymeleaf.standard.expression.IStandardExpressionParser;
15 import org.thymeleaf.standard.expression.StandardExpressions;
16
17
18 /**
19  * Replaces the element by the tag <code>&lt;strong&gt;</code>, if it is
20  * marked as active.
21  * @author Kai Moritz
22  */
23 public class ActiveElementProcessor extends AbstractProcessor
24 {
25   private final AttributeNameProcessorMatcher matcher =
26       new AttributeNameProcessorMatcher("active");
27
28
29   @Override
30   public IProcessorMatcher<? extends Node> getMatcher()
31   {
32     return matcher;
33   }
34
35   @Override
36   protected ProcessorResult doProcess(
37       Arguments arguments,
38       ProcessorMatchingContext context,
39       Node node
40       )
41   {
42     // Because of the type of applicability being used, casts to Element here will not fail
43     final Element element = (Element) node;
44     final String[] names = this.matcher.getAttributeNames(context);
45
46     for (final String name : names)
47     {
48       if (element.hasNormalizedAttribute(name))
49       {
50         Configuration configuration = arguments.getConfiguration();
51         IStandardExpressionParser parser =
52             StandardExpressions.getExpressionParser(configuration);
53         String value = element.getAttributeValue(name);
54         IStandardExpression expression =
55             parser.parseExpression(configuration, arguments, value);
56         element.removeAttribute(name);
57         if ((Boolean)expression.execute(configuration, arguments))
58         {
59           Element strong =
60               element.cloneElementNodeWithNewName(element, "strong", true);
61           element.clearChildren();
62           element.addChild(strong);
63           element.getParent().extractChild(element);
64         }
65         break;
66       }
67     }
68     return ProcessorResult.OK;
69   }
70
71   @Override
72   public int getPrecedence()
73   {
74     // Be sure to be executed first
75     return 0;
76   }
77 }