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

graphql.language.NodeTraverser Maven / Gradle / Ivy

There is a newer version: 230521-nf-execution
Show newest version
package graphql.language;

import graphql.util.SimpleTraverserContext;
import graphql.util.TraversalControl;
import graphql.util.Traverser;
import graphql.util.TraverserContext;
import graphql.util.TraverserVisitor;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class NodeTraverser {

    public enum LeaveOrEnter {
        LEAVE,
        ENTER
    }

    private final Map, Object> rootVars;
    private final Function> getChildren;

    public NodeTraverser(Map, Object> rootVars, Function> getChildren) {
        this.rootVars = rootVars;
        this.getChildren = getChildren;
    }

    public NodeTraverser() {
        this(Collections.emptyMap(), Node::getChildren);
    }


    public void depthFirst(NodeVisitor nodeVisitor, Node root) {
        doTraverse(nodeVisitor, Collections.singleton(root));
    }

    public void depthFirst(NodeVisitor nodeVisitor, Collection roots) {
        doTraverse(nodeVisitor, roots);
    }

    private void doTraverse(NodeVisitor nodeVisitor, Collection roots) {
        Traverser nodeTraverser = Traverser.depthFirst(this.getChildren);
        nodeTraverser.rootVars(rootVars);
        TraverserVisitor traverserVisitor = new TraverserVisitor() {

            public TraversalControl enter(TraverserContext context) {
                context.setVar(LeaveOrEnter.class, LeaveOrEnter.ENTER);
                return context.thisNode().accept(context, nodeVisitor);
            }

            public TraversalControl leave(TraverserContext context) {
                context.setVar(LeaveOrEnter.class, LeaveOrEnter.LEAVE);
                return context.thisNode().accept(context, nodeVisitor);
            }
        };
        nodeTraverser.traverse(roots, traverserVisitor);
    }

    public static  T oneVisitWithResult(Node node, NodeVisitor nodeVisitor) {
        SimpleTraverserContext context = new SimpleTraverserContext<>(node);
        node.accept(context, nodeVisitor);
        return (T) context.getResult();
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy