    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 *     https://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 */
    017package org.apache.commons.configuration2.tree;
    018
    019import java.util.ArrayList;
    020import java.util.Collections;
    021import java.util.Iterator;
    022import java.util.LinkedList;
    023import java.util.List;
    024
    025import org.apache.commons.lang3.builder.ToStringBuilder;
    026
    027/**
    028 * <p>
    029 * A class for selecting a specific node based on a key or a set of keys.
    030 * </p>
    031 * <p>
    032 * An instance of this class is initialized with the key of a node. It is also possible to concatenate multiple keys -
    033 * for example if a sub key is to be constructed from another sub key. {@code NodeSelector} provides the {@code select()}
    034 * method which evaluates the wrapped keys on a specified root node and returns the resulting unique target node. The
    035 * class expects that the key(s) stored in an instance select exactly one target node. If this is not the case, result
    036 * is <strong>null</strong> indicating that the selection criteria are not sufficient.
    037 * </p>
    038 * <p>
    039 * Implementation node: Instances of this class are immutable. They can be shared between arbitrary components.
    040 * </p>
    041 *
    042 * @since 2.0
    043 */
    044public class NodeSelector {
    045    /** Stores the wrapped keys. */
    046    private final List<String> nodeKeys;
    047
    048    /**
    049     * Creates a new instance of {@code NodeSelector} and initializes it with the list of keys to be used as selection
    050     * criteria.
    051     *
    052     * @param keys the keys for selecting nodes
    053     */
    054    private NodeSelector(final List<String> keys) {
    055        nodeKeys = keys;
    056    }
    057
    058    /**
    059     * Creates a new instance of {@code NodeSelector} and initializes it with the key to the target node.
    060     *
    061     * @param key the key
    062     */
    063    public NodeSelector(final String key) {
    064        this(Collections.singletonList(key));
    065    }
    066
    067    /**
    068     * Compares this object with another one. Two instances of {@code NodeSelector} are considered equal if they have the
    069     * same keys as selection criteria.
    070     *
    071     * @param obj the object to be compared
    072     * @return a flag whether these objects are equal
    073     */
    074    @Override
    075    public boolean equals(final Object obj) {
    076        if (this == obj) {
    077            return true;
    078        }
    079        if (!(obj instanceof NodeSelector)) {
    080            return false;
    081        }
    082
    083        final NodeSelector c = (NodeSelector) obj;
    084        return nodeKeys.equals(c.nodeKeys);
    085    }
    086
    087    /**
    088     * Executes a query for a given key and filters the results for nodes only.
    089     *
    090     * @param root the root node for the query
    091     * @param resolver the {@code NodeKeyResolver}
    092     * @param handler the {@code NodeHandler}
    093     * @param key the key
    094     * @param nodes here the results are stored
    095     */
    096    private void getFilteredResults(final ImmutableNode root, final NodeKeyResolver<ImmutableNode> resolver, final NodeHandler<ImmutableNode> handler,
    097        final String key, final List<ImmutableNode> nodes) {
    098        final List<QueryResult<ImmutableNode>> results = resolver.resolveKey(root, key, handler);
    099        results.forEach(result -> {
    100            if (!result.isAttributeResult()) {
    101                nodes.add(result.getNode());
    102            }
    103        });
    104    }
    105
    106    /**
    107     * Returns a hash code for this object.
    108     *
    109     * @return a hash code
    110     */
    111    @Override
    112    public int hashCode() {
    113        return nodeKeys.hashCode();
    114    }
    115
    116    /**
    117     * Applies this {@code NodeSelector} on the specified root node. This method applies the selection criteria stored in
    118     * this object and tries to determine a single target node. If this is successful, the target node is returned.
    119     * Otherwise, result is <strong>null</strong>.
    120     *
    121     * @param root the root node on which to apply this selector
    122     * @param resolver the {@code NodeKeyResolver}
    123     * @param handler the {@code NodeHandler}
    124     * @return the selected target node or <strong>null</strong>
    125     */
    126    public ImmutableNode select(final ImmutableNode root, final NodeKeyResolver<ImmutableNode> resolver, final NodeHandler<ImmutableNode> handler) {
    127        List<ImmutableNode> nodes = new LinkedList<>();
    128        final Iterator<String> itKeys = nodeKeys.iterator();
    129        getFilteredResults(root, resolver, handler, itKeys.next(), nodes);
    130
    131        while (itKeys.hasNext()) {
    132            final String currentKey = itKeys.next();
    133            final List<ImmutableNode> currentResults = new LinkedList<>();
    134            nodes.forEach(currentRoot -> getFilteredResults(currentRoot, resolver, handler, currentKey, currentResults));
    135            nodes = currentResults;
    136        }
    137
    138        return nodes.size() == 1 ? nodes.get(0) : null;
    139    }
    140
    141    /**
    142     * Creates a sub {@code NodeSelector} object which uses the key(s) of this selector plus the specified key as selection
    143     * criteria. This is useful when another selection is to be performed on the results of a first selector.
    144     *
    145     * @param subKey the additional key for the sub selector
    146     * @return the sub {@code NodeSelector} instance
    147     */
    148    public NodeSelector subSelector(final String subKey) {
    149        final List<String> keys = new ArrayList<>(nodeKeys.size() + 1);
    150        keys.addAll(nodeKeys);
    151        keys.add(subKey);
    152        return new NodeSelector(keys);
    153    }
    154
    155    /**
    156     * Returns a string representation for this object. This string contains the keys to be used as selection criteria.
    157     *
    158     * @return a string for this object
    159     */
    160    @Override
    161    public String toString() {
    162        return new ToStringBuilder(this).append("keys", nodeKeys).toString();
    163    }
    164}