001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.osm.visitor;
003
004import java.util.Collection;
005import java.util.HashSet;
006
007import org.openstreetmap.josm.data.osm.Node;
008import org.openstreetmap.josm.data.osm.OsmPrimitive;
009import org.openstreetmap.josm.data.osm.Relation;
010import org.openstreetmap.josm.data.osm.RelationMember;
011import org.openstreetmap.josm.data.osm.Way;
012
013/**
014 * Collect all nodes a specific osm primitive has.
015 *
016 * @author imi
017 */
018public class AllNodesVisitor extends AbstractVisitor {
019
020    /**
021     * The resulting nodes collected so far.
022     */
023    public Collection<Node> nodes = new HashSet<>();
024
025    /**
026     * Nodes have only itself as nodes.
027     */
028    @Override
029    public void visit(Node n) {
030        nodes.add(n);
031    }
032
033    /**
034     * Ways have their way nodes.
035     */
036    @Override
037    public void visit(Way w) {
038        if (w.isIncomplete()) return;
039        for (Node n : w.getNodes()) {
040            visit(n);
041        }
042    }
043
044    /**
045     * Relations may have any number of nodes.
046     * FIXME: do we want to collect nodes from segs/ways that are relation members?
047     * if so, use AutomatchVisitor!
048     */
049    @Override
050    public void visit(Relation e) {
051        for (RelationMember m : e.getMembers()) {
052            if (m.isNode()) visit(m.getNode());
053        }
054    }
055
056    /**
057     * Replies all nodes contained by the given primitives
058     * @param osms The OSM primitives to inspect
059     * @return All nodes the given primitives have.
060     */
061    public static Collection<Node> getAllNodes(Collection<? extends OsmPrimitive> osms) {
062        AllNodesVisitor v = new AllNodesVisitor();
063        for (OsmPrimitive osm : osms) {
064            osm.accept(v);
065        }
066        return v.nodes;
067    }
068}