001// License: GPL. See LICENSE file for details.
002package org.openstreetmap.josm.data.validation.util;
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;
012import org.openstreetmap.josm.data.osm.visitor.AbstractVisitor;
013
014/**
015 * A visitor that aggregates all primitives it visits.
016 * <p>
017 * The primitives are sorted according to their type: first nodes, then ways.
018 *
019 * @author frsantos
020 */
021public class AggregatePrimitivesVisitor extends AbstractVisitor {
022    /** Aggregated data */
023    final Collection<OsmPrimitive> aggregatedData = new HashSet<>();
024
025    /**
026     * Visits a collection of primitives
027     * @param data The collection of primitives
028     * @return The aggregated primitives
029     */
030    public Collection<OsmPrimitive> visit(Collection<OsmPrimitive> data) {
031        for (OsmPrimitive osm : data) {
032            osm.accept(this);
033        }
034
035        return aggregatedData;
036    }
037
038    @Override
039    public void visit(Node n) {
040        if (!aggregatedData.contains(n)) {
041            aggregatedData.add(n);
042        }
043    }
044
045    @Override
046    public void visit(Way w) {
047        if (!aggregatedData.contains(w)) {
048            aggregatedData.add(w);
049            for (Node n : w.getNodes()) {
050                visit(n);
051            }
052        }
053    }
054
055    @Override
056    public void visit(Relation r) {
057        if (!aggregatedData.contains(r)) {
058            aggregatedData.add(r);
059            for (RelationMember m : r.getMembers()) {
060                m.getMember().accept(this);
061            }
062        }
063    }
064}