Java Code Examples for org.apache.commons.configuration2.tree.ImmutableNode#Builder

The following examples show how to use org.apache.commons.configuration2.tree.ImmutableNode#Builder . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestXPathExpressionEngine.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether duplicates are correctly resolved when querying for
 * canonical keys.
 */
@Test
public void testCanonicalKeyWithDuplicates()
{
    final ImmutableNode.Builder parentBuilder = new ImmutableNode.Builder(3);
    final ImmutableNode c1 = new ImmutableNode.Builder().name("child").create();
    final ImmutableNode c2 = new ImmutableNode.Builder().name("child").create();
    final ImmutableNode c3 =
            new ImmutableNode.Builder().name("child_other").create();
    parentBuilder.addChildren(Arrays.asList(c1, c2, c3));
    final ImmutableNode parent = parentBuilder.create();
    final NodeHandler<ImmutableNode> testHandler =
            new InMemoryNodeModel(parent).getNodeHandler();
    final XPathExpressionEngine engine = new XPathExpressionEngine();
    assertEquals("Wrong key 1", "parent/child[1]",
            engine.canonicalKey(c1, "parent", testHandler));
    assertEquals("Wrong key 2", "parent/child[2]",
            engine.canonicalKey(c2, "parent", testHandler));
}
 
Example 2
Source File: TestXPathExpressionEngine.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether a canonical key can be queried if all child nodes have
 * different names.
 */
@Test
public void testCanonicalKeyNoDuplicates()
{
    final ImmutableNode.Builder parentBuilder = new ImmutableNode.Builder(2);
    final ImmutableNode c1 = new ImmutableNode.Builder().name("child").create();
    final ImmutableNode c2 =
            new ImmutableNode.Builder().name("child_other").create();
    parentBuilder.addChildren(Arrays.asList(c2, c1));
    final ImmutableNode parent = parentBuilder.create();
    final NodeHandler<ImmutableNode> testHandler =
            new InMemoryNodeModel(parent).getNodeHandler();
    final XPathExpressionEngine engine = new XPathExpressionEngine();
    assertEquals("Wrong canonical key", "parent/child[1]",
            engine.canonicalKey(c1, "parent", testHandler));
}
 
Example 3
Source File: CombinedConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Handles a single component of the at path. A corresponding node is
 * created and added to the hierarchical path to the original root node
 * of the configuration.
 *
 * @param builder the current node builder object
 * @param currentComponent the name of the current path component
 * @param components an iterator with all components of the at path
 * @param orgRoot the original root node of the wrapped configuration
 */
private void prependAtPathComponent(final ImmutableNode.Builder builder,
        final String currentComponent, final Iterator<String> components,
        final ImmutableNode orgRoot)
{
    builder.name(currentComponent);
    if (components.hasNext())
    {
        final ImmutableNode.Builder childBuilder =
                new ImmutableNode.Builder();
        prependAtPathComponent(childBuilder, components.next(),
                components, orgRoot);
        builder.addChild(childBuilder.create());
    }
    else
    {
        builder.addChildren(orgRoot.getChildren());
        builder.addAttributes(orgRoot.getAttributes());
        builder.value(orgRoot.getValue());
    }
}
 
Example 4
Source File: BaseHierarchicalConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
@Override
public void visitBeforeChildren(final ImmutableNode node,
        final NodeHandler<ImmutableNode> handler)
{
    if (isLeafNode(node, handler))
    {
        handleLeafNode(node, handler);
    }
    else
    {
        final ImmutableNode.Builder builder =
                new ImmutableNode.Builder(handler.getChildrenCount(
                        node, null))
                        .name(handler.nodeName(node))
                        .value(interpolate(handler.getValue(node)))
                        .addAttributes(
                                interpolateAttributes(node, handler));
        push(builder);
    }
}
 
Example 5
Source File: AbstractXPathTest.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Recursive helper method for creating a level of the node hierarchy.
 *
 * @param parentBuilder the builder for the parent node
 * @param value the value of the parent node
 * @param level the level counter
 */
private void createLevel(final ImmutableNode.Builder parentBuilder, final String value,
        final int level)
{
    if (level >= 0)
    {
        final String prefix = value == null ? "" : value + ".";
        for (int i = 1; i <= CHILD_COUNT; i++)
        {
            final ImmutableNode.Builder childBuilder =
                    new ImmutableNode.Builder();
            childBuilder.name(i % 2 == 0 ? CHILD_NAME1 : CHILD_NAME2);
            final String currentValue = prefix + i;
            childBuilder.value(currentValue);
            createLevel(childBuilder, currentValue, level - 1);
            childBuilder.addAttribute(ATTR_NAME, String.valueOf(i));
            parentBuilder.addChild(childBuilder.create());
        }
    }
}
 
Example 6
Source File: TestConfigurationAttributePointer.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception
{
    final ImmutableNode.Builder ndBuilder = new ImmutableNode.Builder();
    ndBuilder.name("parent").addAttribute(ATTR_NAME, ATTR_VALUE);
    final ImmutableNode nd = ndBuilder.create();
    parent =
            new ConfigurationNodePointer<>(nd, Locale.ENGLISH,
                    new InMemoryNodeModel(nd).getNodeHandler());
    pointer =
            new ConfigurationAttributePointer<>(parent,
                    ATTR_NAME);
}
 
Example 7
Source File: TestAbstractHierarchicalConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests isEmpty() if the structure contains some nodes without values.
 */
@Test
public void testIsEmptyNodesWithNoValues()
{
    final ImmutableNode.Builder rootBuilder = new ImmutableNode.Builder(1);
    final ImmutableNode.Builder nodeBuilder = new ImmutableNode.Builder(1);
    nodeBuilder.addChild(NodeStructureHelper.createNode("child", null));
    rootBuilder.addChild(nodeBuilder.create());
    config =
            new AbstractHierarchicalConfigurationTestImpl(
                    new InMemoryNodeModel(rootBuilder.create()));
    assertTrue("Not empty", config.isEmpty());
}
 
Example 8
Source File: TestXPathExpressionEngine.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether the parent key can be undefined when querying a canonical
 * key.
 */
@Test
public void testCanonicalKeyNoParentKey()
{
    final ImmutableNode.Builder parentBuilder = new ImmutableNode.Builder(1);
    final ImmutableNode c1 = new ImmutableNode.Builder().name("child").create();
    final ImmutableNode parent = parentBuilder.addChild(c1).create();
    final NodeHandler<ImmutableNode> testHandler =
            new InMemoryNodeModel(parent).getNodeHandler();
    final XPathExpressionEngine engine = new XPathExpressionEngine();
    assertEquals("Wrong key", "child[1]",
            engine.canonicalKey(c1, null, testHandler));
}
 
Example 9
Source File: AbstractYAMLBasedConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Parses a map structure. The single keys of the map are processed
 * recursively.
 *
 * @param map the map to be processed
 * @param key the key under which this map is to be stored
 * @return a node representing this map
 */
private static List<ImmutableNode> parseMap(final Map<String, Object> map, final String key)
{
    final ImmutableNode.Builder subtree = new ImmutableNode.Builder().name(key);
    for (final Map.Entry<String, Object> entry : map.entrySet())
    {
        final List<ImmutableNode> children =
                constructHierarchy(entry.getKey(), entry.getValue());
        for (final ImmutableNode child : children)
        {
            subtree.addChild(child);
        }
    }
    return Collections.singletonList(subtree.create());
}
 
Example 10
Source File: INIConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the node(s) for the given key value-pair. If delimiter parsing is
 * enabled, the value string is split if possible, and for each single value
 * a node is created. Otherwise only a single node is added to the section.
 *
 * @param sectionBuilder the section builder for adding new nodes
 * @param key the key
 * @param value the value string
 */
private void createValueNodes(final ImmutableNode.Builder sectionBuilder,
        final String key, final String value)
{
    final Collection<String> values =
            getListDelimiterHandler().split(value, false);

    for (final String v : values)
    {
        sectionBuilder.addChild(new ImmutableNode.Builder().name(key)
                .value(v).create());
    }
}
 
Example 11
Source File: INIConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new root node from the builders constructed while reading the
 * configuration file.
 *
 * @param rootBuilder the builder for the top-level section
 * @param sectionBuilders a map storing the section builders
 * @return the root node of the newly created hierarchy
 */
private static ImmutableNode createNewRootNode(
        final ImmutableNode.Builder rootBuilder,
        final Map<String, ImmutableNode.Builder> sectionBuilders)
{
    for (final Map.Entry<String, ImmutableNode.Builder> e : sectionBuilders
            .entrySet())
    {
        rootBuilder.addChild(e.getValue().name(e.getKey()).create());
    }
    return rootBuilder.create();
}
 
Example 12
Source File: INIConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Load the configuration from the given reader. Note that the
 * {@code clear()} method is not called so the configuration read in will
 * be merged with the current configuration.
 *
 * @param in the reader to read the configuration from.
 * @throws ConfigurationException If an error occurs while reading the
 *         configuration
 * @throws IOException if an I/O error occurs
 */
@Override
public void read(final Reader in) throws ConfigurationException, IOException
{
    final BufferedReader bufferedReader = new BufferedReader(in);
    final Map<String, ImmutableNode.Builder> sectionBuilders = new LinkedHashMap<>();
    final ImmutableNode.Builder rootBuilder = new ImmutableNode.Builder();

    createNodeBuilders(bufferedReader, rootBuilder, sectionBuilders);
    final ImmutableNode rootNode = createNewRootNode(rootBuilder, sectionBuilders);
    addNodes(null, rootNode.getChildren());
}
 
Example 13
Source File: BaseHierarchicalConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a root node for a subset configuration based on the passed in
 * query results. This method creates a new root node and adds the children
 * and attributes of all result nodes to it. If only a single node value is
 * defined, it is assigned as value of the new root node.
 *
 * @param results the collection of query results
 * @return the root node for the subset configuration
 */
private ImmutableNode createSubsetRootNode(
        final Collection<QueryResult<ImmutableNode>> results)
{
    final ImmutableNode.Builder builder = new ImmutableNode.Builder();
    Object value = null;
    int valueCount = 0;

    for (final QueryResult<ImmutableNode> result : results)
    {
        if (result.isAttributeResult())
        {
            builder.addAttribute(result.getAttributeName(),
                    result.getAttributeValue(getModel().getNodeHandler()));
        }
        else
        {
            if (result.getNode().getValue() != null)
            {
                value = result.getNode().getValue();
                valueCount++;
            }
            builder.addChildren(result.getNode().getChildren());
            builder.addAttributes(result.getNode().getAttributes());
        }
    }

    if (valueCount == 1)
    {
        builder.value(value);
    }
    return builder.create();
}
 
Example 14
Source File: CombinedConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Prepends the at path to the given node.
 *
 * @param node the root node of the represented configuration
 * @return the new root node including the at path
 */
private ImmutableNode prependAtPath(final ImmutableNode node)
{
    final ImmutableNode.Builder pathBuilder = new ImmutableNode.Builder();
    final Iterator<String> pathIterator = atPath.iterator();
    prependAtPathComponent(pathBuilder, pathIterator.next(),
            pathIterator, node);
    return new ImmutableNode.Builder(1).addChild(pathBuilder.create())
            .create();
}
 
Example 15
Source File: TestXMLConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests saving a configuration after a node was added. Test for
 * CONFIGURATION-294.
 */
@Test
public void testAddNodesAndSave() throws ConfigurationException
{
    final ImmutableNode.Builder bldrNode = new ImmutableNode.Builder(1);
    bldrNode.addChild(NodeStructureHelper.createNode("child", null));
    bldrNode.addAttribute("attr", "");
    final ImmutableNode node2 = NodeStructureHelper.createNode("test2", null);
    conf.addNodes("add.nodes",
            Arrays.asList(bldrNode.name("test").create(), node2));
    saveTestConfig();
    conf.setProperty("add.nodes.test", "true");
    conf.setProperty("add.nodes.test.child", "yes");
    conf.setProperty("add.nodes.test[@attr]", "existing");
    conf.setProperty("add.nodes.test2", "anotherValue");
    saveTestConfig();
    final XMLConfiguration c2 = new XMLConfiguration();
    load(c2, testSaveConf.getAbsolutePath());
    assertEquals("Value was not saved", "true", c2
            .getString("add.nodes.test"));
    assertEquals("Child value was not saved", "yes", c2
            .getString("add.nodes.test.child"));
    assertEquals("Attr value was not saved", "existing", c2
            .getString("add.nodes.test[@attr]"));
    assertEquals("Node2 not saved", "anotherValue", c2
            .getString("add.nodes.test2"));
}
 
Example 16
Source File: INIConfiguration.java    From commons-configuration with Apache License 2.0 4 votes vote down vote up
/**
 * Reads the content of an INI file from the passed in reader and creates a
 * structure of builders for constructing the {@code ImmutableNode} objects
 * representing the data.
 *
 * @param in the reader
 * @param rootBuilder the builder for the top-level section
 * @param sectionBuilders a map storing the section builders
 * @throws IOException if an I/O error occurs
 */
private void createNodeBuilders(final BufferedReader in,
        final ImmutableNode.Builder rootBuilder,
        final Map<String, ImmutableNode.Builder> sectionBuilders)
        throws IOException
{
    ImmutableNode.Builder sectionBuilder = rootBuilder;
    String line = in.readLine();
    while (line != null)
    {
        line = line.trim();
        if (!isCommentLine(line))
        {
            if (isSectionLine(line))
            {
                final String section = line.substring(1, line.length() - 1);
                sectionBuilder = sectionBuilders.get(section);
                if (sectionBuilder == null)
                {
                    sectionBuilder = new ImmutableNode.Builder();
                    sectionBuilders.put(section, sectionBuilder);
                }
            }

            else
            {
                String key;
                String value = "";
                final int index = findSeparator(line);
                if (index >= 0)
                {
                    key = line.substring(0, index);
                    value = parseValue(line.substring(index + 1), in);
                }
                else
                {
                    key = line;
                }
                key = key.trim();
                if (key.length() < 1)
                {
                    // use space for properties with no key
                    key = " ";
                }
                createValueNodes(sectionBuilder, key, value);
            }
        }

        line = in.readLine();
    }
}
 
Example 17
Source File: XMLConfiguration.java    From commons-configuration with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new child node, assigns its value, and adds it to its parent.
 * This method also deals with elements whose value is a list. In this case
 * multiple child elements must be added. The return value is the first
 * child node which was added.
 *
 * @param parent the builder for the parent element
 * @param child the builder for the child element
 * @param elem the associated XML element
 * @param value the value of the child element
 * @param trim flag whether texts of elements should be trimmed
 * @param attrmap a map with the attributes of the current node
 * @param elemRefs a map for assigning references objects to nodes; can be
 *        <b>null</b>, then reference objects are irrelevant
 * @return the first child node added to the parent
 */
private ImmutableNode createChildNodeWithValue(final ImmutableNode.Builder parent,
        final ImmutableNode.Builder child, final Element elem, final String value,
        final boolean trim, final Map<String, String> attrmap,
        final Map<ImmutableNode, Object> elemRefs)
{
    ImmutableNode addedChildNode;
    Collection<String> values;

    if (value != null)
    {
        values = getListDelimiterHandler().split(value, trim);
    }
    else
    {
        values = Collections.emptyList();
    }

    if (values.size() > 1)
    {
        final Map<ImmutableNode, Object> refs = isSingleElementList(elem) ? elemRefs : null;
        final Iterator<String> it = values.iterator();
        // Create new node for the original child's first value
        child.value(it.next());
        addedChildNode = child.create();
        parent.addChild(addedChildNode);
        XMLListReference.assignListReference(refs, addedChildNode, elem);

        // add multiple new children
        while (it.hasNext())
        {
            final ImmutableNode.Builder c = new ImmutableNode.Builder();
            c.name(addedChildNode.getNodeName());
            c.value(it.next());
            c.addAttributes(attrmap);
            final ImmutableNode newChild = c.create();
            parent.addChild(newChild);
            XMLListReference.assignListReference(refs, newChild, null);
        }
    }
    else if (values.size() == 1)
    {
        // we will have to replace the value because it might
        // contain escaped delimiters
        child.value(values.iterator().next());
        addedChildNode = child.create();
        parent.addChild(addedChildNode);
    }
    else
    {
        addedChildNode = child.create();
        parent.addChild(addedChildNode);
    }

    return addedChildNode;
}
 
Example 18
Source File: XMLConfiguration.java    From commons-configuration with Apache License 2.0 4 votes vote down vote up
/**
 * Helper method for building the internal storage hierarchy. The XML
 * elements are transformed into node objects.
 *
 * @param node a builder for the current node
 * @param refValue stores the text value of the element
 * @param element the current XML element
 * @param elemRefs a map for assigning references objects to nodes; can be
 *        <b>null</b>, then reference objects are irrelevant
 * @param trim a flag whether the text content of elements should be
 *        trimmed; this controls the whitespace handling
 * @param level the current level in the hierarchy
 * @return a map with all attribute values extracted for the current node;
 *         this map also contains the value of the trim flag for this node
 *         under the key {@value #ATTR_SPACE}
 */
private Map<String, String> constructHierarchy(final ImmutableNode.Builder node,
        final MutableObject<String> refValue, final Element element,
        final Map<ImmutableNode, Object> elemRefs, final boolean trim, final int level)
{
    final boolean trimFlag = shouldTrim(element, trim);
    final Map<String, String> attributes = processAttributes(element);
    attributes.put(ATTR_SPACE_INTERNAL, String.valueOf(trimFlag));
    final StringBuilder buffer = new StringBuilder();
    final NodeList list = element.getChildNodes();
    boolean hasChildren = false;

    for (int i = 0; i < list.getLength(); i++)
    {
        final org.w3c.dom.Node w3cNode = list.item(i);
        if (w3cNode instanceof Element)
        {
            final Element child = (Element) w3cNode;
            final ImmutableNode.Builder childNode = new ImmutableNode.Builder();
            childNode.name(child.getTagName());
            final MutableObject<String> refChildValue =
                    new MutableObject<>();
            final Map<String, String> attrmap =
                    constructHierarchy(childNode, refChildValue, child,
                            elemRefs, trimFlag, level + 1);
            final Boolean childTrim = Boolean.valueOf(attrmap.remove(ATTR_SPACE_INTERNAL));
            childNode.addAttributes(attrmap);
            final ImmutableNode newChild =
                    createChildNodeWithValue(node, childNode, child,
                            refChildValue.getValue(),
                            childTrim.booleanValue(), attrmap, elemRefs);
            if (elemRefs != null && !elemRefs.containsKey(newChild))
            {
                elemRefs.put(newChild, child);
            }
            hasChildren = true;
        }
        else if (w3cNode instanceof Text)
        {
            final Text data = (Text) w3cNode;
            buffer.append(data.getData());
        }
    }

    boolean childrenFlag = false;
    if (hasChildren || trimFlag)
    {
        childrenFlag = hasChildren || attributes.size() > 1;
    }
    final String text = determineValue(buffer.toString(), childrenFlag, trimFlag);
    if (text.length() > 0 || (!childrenFlag && level != 0))
    {
        refValue.setValue(text);
    }
    return attributes;
}
 
Example 19
Source File: BaseHierarchicalConfiguration.java    From commons-configuration with Apache License 2.0 2 votes vote down vote up
/**
 * Pops the top-level element from the stack.
 *
 * @return the element popped from the stack
 */
private ImmutableNode.Builder pop()
{
    return builderStack.remove(0);
}
 
Example 20
Source File: BaseHierarchicalConfiguration.java    From commons-configuration with Apache License 2.0 2 votes vote down vote up
/**
 * Pushes a new builder on the stack.
 *
 * @param builder the builder
 */
private void push(final ImmutableNode.Builder builder)
{
    builderStack.add(0, builder);
}