FindNodeVisitor.java

  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.  *     http://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. package org.apache.commons.configuration2;

  18. import org.apache.commons.configuration2.tree.ConfigurationNodeVisitorAdapter;
  19. import org.apache.commons.configuration2.tree.NodeHandler;

  20. /**
  21.  * <p>
  22.  * A specialized {@code NodeVisitor} implementation which searches for a specific node in a hierarchy.
  23.  * </p>
  24.  *
  25.  * @param <T> the type of the nodes to be visited
  26.  */
  27. final class FindNodeVisitor<T> extends ConfigurationNodeVisitorAdapter<T> {
  28.     /** The node to be searched for. */
  29.     private final T searchNode;

  30.     /** A flag whether the node was found. */
  31.     private boolean found;

  32.     /**
  33.      * Creates a new instance of {@code FindNodeVisitor} and sets the node to be searched for.
  34.      *
  35.      * @param node the search node
  36.      */
  37.     public FindNodeVisitor(final T node) {
  38.         searchNode = node;
  39.     }

  40.     /**
  41.      * Returns a flag whether the search node was found in the last search operation.
  42.      *
  43.      * @return <strong>true</strong> if the search node was found; <strong>false</strong> otherwise
  44.      */
  45.     public boolean isFound() {
  46.         return found;
  47.     }

  48.     /**
  49.      * Resets this visitor. This method sets the {@code found} property to <strong>false</strong> again, so that this instance can be
  50.      * used to inspect another nodes hierarchy.
  51.      */
  52.     public void reset() {
  53.         found = false;
  54.     }

  55.     /**
  56.      * {@inheritDoc} This implementation returns <strong>true</strong> as soon as the node was found.
  57.      */
  58.     @Override
  59.     public boolean terminate() {
  60.         return found;
  61.     }

  62.     @Override
  63.     public void visitBeforeChildren(final T node, final NodeHandler<T> handler) {
  64.         if (node.equals(searchNode)) {
  65.             found = true;
  66.         }
  67.     }
  68. }