View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.configuration2;
19  
20  import org.apache.commons.configuration2.tree.ConfigurationNodeVisitorAdapter;
21  import org.apache.commons.configuration2.tree.NodeHandler;
22  import org.apache.commons.configuration2.tree.NodeTreeWalker;
23  import org.xml.sax.Attributes;
24  import org.xml.sax.helpers.AttributesImpl;
25  
26  /**
27   * <p>
28   * A specialized SAX2 XML parser that "parses" hierarchical configuration objects.
29   * </p>
30   * <p>
31   * This class mimics to be a SAX conform XML parser. Instead of parsing XML documents it processes a
32   * {@code Configuration} object and generates SAX events for the single properties defined there. This enables the whole
33   * world of XML processing for configuration objects.
34   * </p>
35   * <p>
36   * The {@code HierarchicalConfiguration} object to be parsed can be specified using a constructor or the
37   * {@code setConfiguration()} method. This object will be processed by the {@code parse()} methods. Note that these
38   * methods ignore their argument.
39   * </p>
40   *
41   * @param <T> the type of the nodes supported by this reader
42   */
43  public class HierarchicalConfigurationXMLReader<T> extends ConfigurationXMLReader {
44  
45      /**
46       * A specialized visitor class for generating SAX events for a hierarchical node structure.
47       */
48      private final class SAXVisitor extends ConfigurationNodeVisitorAdapter<T> {
49  
50          /** Constant for the attribute type. */
51          private static final String ATTR_TYPE = "CDATA";
52  
53          /**
54           * Returns an object with all attributes for the specified node.
55           *
56           * @param node the current node
57           * @param handler the node handler
58           * @return an object with all attributes of this node
59           */
60          protected Attributes fetchAttributes(final T node, final NodeHandler<T> handler) {
61              final AttributesImpl attrs = new AttributesImpl();
62  
63              handler.getAttributes(node).forEach(attr -> {
64                  final Object value = handler.getAttributeValue(node, attr);
65                  if (value != null) {
66                      attrs.addAttribute(NS_URI, attr, attr, ATTR_TYPE, value.toString());
67                  }
68              });
69  
70              return attrs;
71          }
72  
73          /**
74           * Helper method for determining the name of a node. If a node has no name (which is true for the root node), the
75           * specified default name will be used.
76           *
77           * @param node the node to be checked
78           * @param handler the node handler
79           * @return the name for this node
80           */
81          private String nodeName(final T node, final NodeHandler<T> handler) {
82              final String nodeName = handler.nodeName(node);
83              return nodeName == null ? getRootName() : nodeName;
84          }
85  
86          /**
87           * Checks if iteration should be terminated. This implementation stops iteration after an exception has occurred.
88           *
89           * @return a flag if iteration should be stopped
90           */
91          @Override
92          public boolean terminate() {
93              return getException() != null;
94          }
95  
96          /**
97           * Visits the specified node after its children have been processed.
98           *
99           * @param node the actual node
100          * @param handler the node handler
101          */
102         @Override
103         public void visitAfterChildren(final T node, final NodeHandler<T> handler) {
104             fireElementEnd(nodeName(node, handler));
105         }
106 
107         /**
108          * Visits the specified node.
109          *
110          * @param node the actual node
111          * @param handler the node handler
112          */
113         @Override
114         public void visitBeforeChildren(final T node, final NodeHandler<T> handler) {
115             fireElementStart(nodeName(node, handler), fetchAttributes(node, handler));
116 
117             final Object value = handler.getValue(node);
118             if (value != null) {
119                 fireCharacters(value.toString());
120             }
121         }
122     }
123 
124     /** Stores the configuration object to be parsed. */
125     private HierarchicalConfiguration<T> configuration;
126 
127     /**
128      * Creates a new instance of {@code HierarchicalConfigurationXMLReader}.
129      */
130     public HierarchicalConfigurationXMLReader() {
131     }
132 
133     /**
134      * Creates a new instance of {@code HierarchicalConfigurationXMLReader} and sets the configuration to be parsed.
135      *
136      * @param config the configuration object
137      */
138     public HierarchicalConfigurationXMLReader(final HierarchicalConfiguration<T> config) {
139         this();
140         setConfiguration(config);
141     }
142 
143     /**
144      * Gets the configuration object to be parsed.
145      *
146      * @return the configuration object to be parsed
147      */
148     public HierarchicalConfiguration<T> getConfiguration() {
149         return configuration;
150     }
151 
152     /**
153      * Gets the configuration object to be processed.
154      *
155      * @return the actual configuration object
156      */
157     @Override
158     public Configuration getParsedConfiguration() {
159         return getConfiguration();
160     }
161 
162     /**
163      * Processes the actual configuration object to generate SAX parsing events.
164      */
165     @Override
166     protected void processKeys() {
167         final NodeHandler<T> nodeHandler = getConfiguration().getNodeModel().getNodeHandler();
168         NodeTreeWalker.INSTANCE.walkDFS(nodeHandler.getRootNode(), new SAXVisitor(), nodeHandler);
169     }
170 
171     /**
172      * Sets the configuration object to be parsed.
173      *
174      * @param config the configuration object to be parsed
175      */
176     public void setConfiguration(final HierarchicalConfiguration<T> config) {
177         configuration = config;
178     }
179 }