All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.camunda.bpm.engine.impl.tree.TreeWalker Maven / Gradle / Ivy

/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.camunda.bpm.engine.impl.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * Abstract class that walks through a tree hierarchy. The subclass define the
 * type of tree and provide the concrete walking behavior.
 *
 * @author Thorben Lindhauer
 *
 */
public abstract class TreeWalker {

  protected T currentElement;

  protected List> preVisitor = new ArrayList>();

  protected List> postVisitor = new ArrayList>();

  protected abstract T nextElement();

  public TreeWalker(T initialElement) {
    currentElement = initialElement;
  }

  public TreeWalker addPreVisitor(TreeVisitor collector) {
    this.preVisitor.add(collector);
    return this;
  }

  public TreeWalker addPostVisitor(TreeVisitor collector) {
    this.postVisitor.add(collector);
    return this;
  }

  public void walkWhile() {
    walkWhile(new NullCondition());
  }

  public void walkUntil() {
    walkUntil(new NullCondition());
  }

  public T walkWhile(WalkCondition condition) {
    while (!condition.isFulfilled(currentElement)) {
      for (TreeVisitor collector : preVisitor) {
        collector.visit(currentElement);
      }

      currentElement = nextElement();

      for (TreeVisitor collector : postVisitor) {
        collector.visit(currentElement);
      }
    }
    return getCurrentElement();
  }

  public T walkUntil(WalkCondition condition) {
    do {
      for (TreeVisitor collector : preVisitor) {
        collector.visit(currentElement);
      }

      currentElement = nextElement();

      for (TreeVisitor collector : postVisitor) {
        collector.visit(currentElement);
      }
    } while (!condition.isFulfilled(currentElement));
    return getCurrentElement();
  }

  public T getCurrentElement() {
    return currentElement;
  }

  public interface WalkCondition {
    boolean isFulfilled(S element);
  }

  public static class NullCondition implements WalkCondition {

    public boolean isFulfilled(S element) {
      return element == null;
    }

    public static  WalkCondition notNull() {
      return new NullCondition();
    }

  }
}