All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.zodiac.template.velocity.impl.EscapeSupportDefinitionParser Maven / Gradle / Ivy

package org.zodiac.template.velocity.impl;

import static org.zodiac.core.context.ext.util.DomUtil.*;
import static org.zodiac.core.context.ext.util.SpringExtUtil.*;

import java.util.List;

import org.zodiac.core.context.ext.support.parser.AbstractSingleBeanDefinitionParser;
import org.zodiac.sdk.toolkit.util.lang.StrUtil;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;
import org.zodiac.template.velocity.support.EscapeSupport;
import org.zodiac.template.velocity.support.EscapeSupport.EscapeRule;

public class EscapeSupportDefinitionParser extends AbstractSingleBeanDefinitionParser {
    @Override
    protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
        attributesToProperties(element, builder, "defaultEscape");

        ElementSelector escapeSelector = and(sameNs(element), name("escape"));
        ElementSelector noescapeSelector = and(sameNs(element), name("noescape"));

        List rules = createManagedList(element, parserContext);

        for (Element subElement : subElements(element)) {
            if (escapeSelector.accept(subElement)) {
                rules.add(parseEscape(subElement, parserContext, builder.getRawBeanDefinition(),
                    StrUtil.trimToNull(subElement.getAttribute("type"))));
            } else if (noescapeSelector.accept(subElement)) {
                rules.add(parseEscape(subElement, parserContext, builder.getRawBeanDefinition(), "noescape"));
            }
        }

        builder.addPropertyValue("escapeRules", rules);
    }

    private BeanDefinition parseEscape(Element element, ParserContext parserContext, BeanDefinition containingBD,
        String type) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(EscapeRule.class);

        // arg 1. escapeType
        builder.addConstructorArgValue(type);

        // arg 2. pattern names
        List patterns = createManagedList(element, parserContext);

        for (Element subElement : subElements(element, and(sameNs(element), name("if-matches")))) {
            patterns.add(subElement.getAttribute("pattern"));
        }

        builder.addConstructorArgValue(patterns);

        return builder.getBeanDefinition();
    }
}