    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *     http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017
    018package org.apache.commons.configuration2;
    019
    020import org.apache.commons.configuration2.tree.ConfigurationNodeVisitorAdapter;
    021import org.apache.commons.configuration2.tree.NodeHandler;
    022import org.apache.commons.configuration2.tree.NodeTreeWalker;
    023import org.xml.sax.Attributes;
    024import org.xml.sax.helpers.AttributesImpl;
    025
    026/**
    027 * <p>
    028 * A specialized SAX2 XML parser that "parses" hierarchical configuration objects.
    029 * </p>
    030 * <p>
    031 * This class mimics to be a SAX conform XML parser. Instead of parsing XML documents it processes a
    032 * {@code Configuration} object and generates SAX events for the single properties defined there. This enables the whole
    033 * world of XML processing for configuration objects.
    034 * </p>
    035 * <p>
    036 * The {@code HierarchicalConfiguration} object to be parsed can be specified using a constructor or the
    037 * {@code setConfiguration()} method. This object will be processed by the {@code parse()} methods. Note that these
    038 * methods ignore their argument.
    039 * </p>
    040 *
    041 * @param <T> the type of the nodes supported by this reader
    042 */
    043public class HierarchicalConfigurationXMLReader<T> extends ConfigurationXMLReader {
    044    /** Stores the configuration object to be parsed. */
    045    private HierarchicalConfiguration<T> configuration;
    046
    047    /**
    048     * Creates a new instance of {@code HierarchicalConfigurationXMLReader}.
    049     */
    050    public HierarchicalConfigurationXMLReader() {
    051    }
    052
    053    /**
    054     * Creates a new instance of {@code HierarchicalConfigurationXMLReader} and sets the configuration to be parsed.
    055     *
    056     * @param config the configuration object
    057     */
    058    public HierarchicalConfigurationXMLReader(final HierarchicalConfiguration<T> config) {
    059        this();
    060        setConfiguration(config);
    061    }
    062
    063    /**
    064     * Gets the configuration object to be parsed.
    065     *
    066     * @return the configuration object to be parsed
    067     */
    068    public HierarchicalConfiguration<T> getConfiguration() {
    069        return configuration;
    070    }
    071
    072    /**
    073     * Sets the configuration object to be parsed.
    074     *
    075     * @param config the configuration object to be parsed
    076     */
    077    public void setConfiguration(final HierarchicalConfiguration<T> config) {
    078        configuration = config;
    079    }
    080
    081    /**
    082     * Gets the configuration object to be processed.
    083     *
    084     * @return the actual configuration object
    085     */
    086    @Override
    087    public Configuration getParsedConfiguration() {
    088        return getConfiguration();
    089    }
    090
    091    /**
    092     * Processes the actual configuration object to generate SAX parsing events.
    093     */
    094    @Override
    095    protected void processKeys() {
    096        final NodeHandler<T> nodeHandler = getConfiguration().getNodeModel().getNodeHandler();
    097        NodeTreeWalker.INSTANCE.walkDFS(nodeHandler.getRootNode(), new SAXVisitor(), nodeHandler);
    098    }
    099
    100    /**
    101     * A specialized visitor class for generating SAX events for a hierarchical node structure.
    102     */
    103    private class SAXVisitor extends ConfigurationNodeVisitorAdapter<T> {
    104        /** Constant for the attribute type. */
    105        private static final String ATTR_TYPE = "CDATA";
    106
    107        /**
    108         * Visits the specified node after its children have been processed.
    109         *
    110         * @param node the actual node
    111         * @param handler the node handler
    112         */
    113        @Override
    114        public void visitAfterChildren(final T node, final NodeHandler<T> handler) {
    115            fireElementEnd(nodeName(node, handler));
    116        }
    117
    118        /**
    119         * Visits the specified node.
    120         *
    121         * @param node the actual node
    122         * @param handler the node handler
    123         */
    124        @Override
    125        public void visitBeforeChildren(final T node, final NodeHandler<T> handler) {
    126            fireElementStart(nodeName(node, handler), fetchAttributes(node, handler));
    127
    128            final Object value = handler.getValue(node);
    129            if (value != null) {
    130                fireCharacters(value.toString());
    131            }
    132        }
    133
    134        /**
    135         * Checks if iteration should be terminated. This implementation stops iteration after an exception has occurred.
    136         *
    137         * @return a flag if iteration should be stopped
    138         */
    139        @Override
    140        public boolean terminate() {
    141            return getException() != null;
    142        }
    143
    144        /**
    145         * Returns an object with all attributes for the specified node.
    146         *
    147         * @param node the current node
    148         * @param handler the node handler
    149         * @return an object with all attributes of this node
    150         */
    151        protected Attributes fetchAttributes(final T node, final NodeHandler<T> handler) {
    152            final AttributesImpl attrs = new AttributesImpl();
    153
    154            handler.getAttributes(node).forEach(attr -> {
    155                final Object value = handler.getAttributeValue(node, attr);
    156                if (value != null) {
    157                    attrs.addAttribute(NS_URI, attr, attr, ATTR_TYPE, value.toString());
    158                }
    159            });
    160
    161            return attrs;
    162        }
    163
    164        /**
    165         * Helper method for determining the name of a node. If a node has no name (which is true for the root node), the
    166         * specified default name will be used.
    167         *
    168         * @param node the node to be checked
    169         * @param handler the node handler
    170         * @return the name for this node
    171         */
    172        private String nodeName(final T node, final NodeHandler<T> handler) {
    173            final String nodeName = handler.nodeName(node);
    174            return nodeName == null ? getRootName() : nodeName;
    175        }
    176    }
    177}