pl.chilldev.web.spring.config.XmlnsBeanDefinitionParser.java Source code

Java tutorial

Introduction

Here is the source code for pl.chilldev.web.spring.config.XmlnsBeanDefinitionParser.java

Source

/**
 * This file is part of the ChillDev-Web.
 *
 * @license http://mit-license.org/ The MIT license
 * @copyright 2014  by Rafa Wrzeszcz - Wrzasq.pl.
 */

package pl.chilldev.web.spring.config;

import java.net.URI;
import java.net.URISyntaxException;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;

import org.w3c.dom.Element;

/**
 * `<xmlns>` element parser.
 *
 * @version 0.0.2
 * @since 0.0.1
 */
public class XmlnsBeanDefinitionParser implements BeanDefinitionParser {
    /**
     * `namespace=""` attribute name.
     */
    public static final String ATTRIBUTE_NAMESPACE = "namespace";

    /**
     * `alias=""` attribute name.
     */
    public static final String ATTRIBUTE_ALIAS = "alias";

    /**
     * XML namespaces property name.
     */
    public static final String PROPERTY_XMLNAMESPACES = "xmlNamespaces";

    /**
     * Logger.
     */
    protected Logger logger = LoggerFactory.getLogger(XmlnsBeanDefinitionParser.class);

    /**
     * All aggregated namespaces.
     */
    protected Map<URI, String> namespaces = new HashMap<>();

    /**
     * Initializes bean parser.
     *
     * @param pageMetaModelFactoryBean Page model factory.
     * @since 0.0.2
     */
    public XmlnsBeanDefinitionParser(BeanDefinition pageMetaModelFactoryBean) {
        pageMetaModelFactoryBean.getPropertyValues()
                .addPropertyValue(XmlnsBeanDefinitionParser.PROPERTY_XMLNAMESPACES, this.namespaces);
    }

    /**
     * {@inheritDoc}
     * @since 0.0.1
     */
    @Override
    public BeanDefinition parse(Element element, ParserContext parserContext) {
        try {
            URI namespace = new URI(element.getAttribute(XmlnsBeanDefinitionParser.ATTRIBUTE_NAMESPACE));
            String alias = element.getAttribute(XmlnsBeanDefinitionParser.ATTRIBUTE_ALIAS);

            this.logger.info("Registring XML namespace \"{}\" with alias \"{}\".", namespace, alias);
            this.namespaces.put(namespace, alias);
        } catch (URISyntaxException error) {
            parserContext.getReaderContext().error("Invalid XML namespace URI.", element, error);
        }

        return null;
    }
}