001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.validation.tests;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.util.ArrayList;
007import java.util.Collection;
008import java.util.Collections;
009import java.util.HashSet;
010import java.util.LinkedList;
011import java.util.List;
012import java.util.Map;
013import java.util.Objects;
014import java.util.Set;
015
016import org.openstreetmap.josm.command.ChangeCommand;
017import org.openstreetmap.josm.command.Command;
018import org.openstreetmap.josm.command.DeleteCommand;
019import org.openstreetmap.josm.command.SequenceCommand;
020import org.openstreetmap.josm.data.coor.LatLon;
021import org.openstreetmap.josm.data.osm.Node;
022import org.openstreetmap.josm.data.osm.OsmPrimitive;
023import org.openstreetmap.josm.data.osm.Relation;
024import org.openstreetmap.josm.data.osm.RelationMember;
025import org.openstreetmap.josm.data.osm.Way;
026import org.openstreetmap.josm.data.validation.Severity;
027import org.openstreetmap.josm.data.validation.Test;
028import org.openstreetmap.josm.data.validation.TestError;
029import org.openstreetmap.josm.gui.progress.ProgressMonitor;
030import org.openstreetmap.josm.tools.MultiMap;
031
032/**
033 * Tests if there are duplicate ways
034 */
035public class DuplicateWay extends Test {
036
037    /**
038      * Class to store a way reduced to coordinates and keys. Essentially this is used to call the
039      * <code>equals{}</code> function.
040      */
041    private static class WayPair {
042        private final List<LatLon> coor;
043        private final Map<String, String> keys;
044
045        WayPair(List<LatLon> coor, Map<String, String> keys) {
046            this.coor = coor;
047            this.keys = keys;
048        }
049
050        @Override
051        public int hashCode() {
052            return Objects.hash(coor, keys);
053        }
054
055        @Override
056        public boolean equals(Object obj) {
057            if (this == obj) return true;
058            if (obj == null || getClass() != obj.getClass()) return false;
059            WayPair wayPair = (WayPair) obj;
060            return Objects.equals(coor, wayPair.coor) &&
061                    Objects.equals(keys, wayPair.keys);
062        }
063    }
064
065    /**
066      * Class to store a way reduced to coordinates. Essentially this is used to call the
067      * <code>equals{}</code> function.
068      */
069    private static class WayPairNoTags {
070        private final List<LatLon> coor;
071
072        WayPairNoTags(List<LatLon> coor) {
073            this.coor = coor;
074        }
075
076        @Override
077        public int hashCode() {
078            return Objects.hash(coor);
079        }
080
081        @Override
082        public boolean equals(Object obj) {
083            if (this == obj) return true;
084            if (obj == null || getClass() != obj.getClass()) return false;
085            WayPairNoTags that = (WayPairNoTags) obj;
086            return Objects.equals(coor, that.coor);
087        }
088    }
089
090    /** Test identification for exactly identical ways (coordinates and tags). */
091    protected static final int DUPLICATE_WAY = 1401;
092    /** Test identification for identical ways (coordinates only). */
093    protected static final int SAME_WAY = 1402;
094
095    /** Bag of all ways */
096    private MultiMap<WayPair, OsmPrimitive> ways;
097
098    /** Bag of all ways, regardless of tags */
099    private MultiMap<WayPairNoTags, OsmPrimitive> waysNoTags;
100
101    /** Set of known hashcodes for list of coordinates **/
102    private Set<Integer> knownHashCodes;
103
104    /**
105     * Constructor
106     */
107    public DuplicateWay() {
108        super(tr("Duplicated ways"),
109                tr("This test checks that there are no ways with same node coordinates and optionally also same tags."));
110    }
111
112    @Override
113    public void startTest(ProgressMonitor monitor) {
114        super.startTest(monitor);
115        ways = new MultiMap<>(1000);
116        waysNoTags = new MultiMap<>(1000);
117        knownHashCodes = new HashSet<>(1000);
118    }
119
120    @Override
121    public void endTest() {
122        super.endTest();
123        for (Set<OsmPrimitive> duplicated : ways.values()) {
124            if (duplicated.size() > 1) {
125                TestError testError = new TestError(this, Severity.ERROR, tr("Duplicated ways"), DUPLICATE_WAY, duplicated);
126                errors.add(testError);
127            }
128        }
129
130        for (Set<OsmPrimitive> sameway : waysNoTags.values()) {
131            if (sameway.size() > 1) {
132                //Report error only if at least some tags are different, as otherwise the error was already reported as duplicated ways
133                Map<String, String> tags0 = null;
134                boolean skip = true;
135
136                for (OsmPrimitive o : sameway) {
137                    if (tags0 == null) {
138                        tags0 = o.getKeys();
139                        removeUninterestingKeys(tags0);
140                    } else {
141                        Map<String, String> tagsCmp = o.getKeys();
142                        removeUninterestingKeys(tagsCmp);
143                        if (!tagsCmp.equals(tags0)) {
144                            skip = false;
145                            break;
146                        }
147                    }
148                }
149                if (skip) {
150                    continue;
151                }
152                TestError testError = new TestError(this, Severity.WARNING, tr("Ways with same position"), SAME_WAY, sameway);
153                errors.add(testError);
154            }
155        }
156        ways = null;
157        waysNoTags = null;
158        knownHashCodes = null;
159    }
160
161    /**
162     * Remove uninteresting discardable keys to normalize the tags
163     * @param wkeys The tags of the way, obtained by {@code Way#getKeys}
164     */
165    public void removeUninterestingKeys(Map<String, String> wkeys) {
166        for (String key : OsmPrimitive.getDiscardableKeys()) {
167            wkeys.remove(key);
168        }
169    }
170
171    @Override
172    public void visit(Way w) {
173        if (!w.isUsable())
174            return;
175        List<LatLon> wLat = getOrderedNodes(w);
176        // If this way has not direction-dependant keys, make sure the list is ordered the same for all ways (fix #8015)
177        if (!w.hasDirectionKeys()) {
178            int hash = wLat.hashCode();
179            if (!knownHashCodes.contains(hash)) {
180                List<LatLon> reversedwLat = new ArrayList<>(wLat);
181                Collections.reverse(reversedwLat);
182                int reverseHash = reversedwLat.hashCode();
183                if (!knownHashCodes.contains(reverseHash)) {
184                    // Neither hash or reversed hash is known, remember hash
185                    knownHashCodes.add(hash);
186                } else {
187                    // Reversed hash is known, use the reverse list then
188                    wLat = reversedwLat;
189                }
190            }
191        }
192        Map<String, String> wkeys = w.getKeys();
193        removeUninterestingKeys(wkeys);
194        WayPair wKey = new WayPair(wLat, wkeys);
195        ways.put(wKey, w);
196        WayPairNoTags wKeyN = new WayPairNoTags(wLat);
197        waysNoTags.put(wKeyN, w);
198    }
199
200    /**
201     * Replies the ordered list of nodes of way w such as it is easier to find duplicated ways.
202     * In case of a closed way, build the list of lat/lon starting from the node with the lowest id
203     * to ensure this list will produce the same hashcode as the list obtained from another closed
204     * way with the same nodes, in the same order, but that does not start from the same node (fix #8008)
205     * @param w way
206     * @return the ordered list of nodes of way w such as it is easier to find duplicated ways
207     * @since 7721
208     */
209    public static List<LatLon> getOrderedNodes(Way w) {
210        List<Node> wNodes = w.getNodes();                        // The original list of nodes for this way
211        List<Node> wNodesToUse = new ArrayList<>(wNodes.size()); // The list that will be considered for this test
212        if (w.isClosed()) {
213            int lowestIndex = 0;
214            long lowestNodeId = wNodes.get(0).getUniqueId();
215            for (int i = 1; i < wNodes.size(); i++) {
216                if (wNodes.get(i).getUniqueId() < lowestNodeId) {
217                    lowestNodeId = wNodes.get(i).getUniqueId();
218                    lowestIndex = i;
219                }
220            }
221            for (int i = lowestIndex; i < wNodes.size()-1; i++) {
222                wNodesToUse.add(wNodes.get(i));
223            }
224            for (int i = 0; i < lowestIndex; i++) {
225                wNodesToUse.add(wNodes.get(i));
226            }
227            wNodesToUse.add(wNodes.get(lowestIndex));
228        } else {
229            wNodesToUse.addAll(wNodes);
230        }
231        // Build the list of lat/lon
232        List<LatLon> wLat = new ArrayList<>(wNodesToUse.size());
233        for (Node node : wNodesToUse) {
234            wLat.add(node.getCoor());
235        }
236        return wLat;
237    }
238
239    /**
240     * Fix the error by removing all but one instance of duplicate ways
241     */
242    @Override
243    public Command fixError(TestError testError) {
244        Collection<? extends OsmPrimitive> sel = testError.getPrimitives();
245        Set<Way> ways = new HashSet<>();
246
247        for (OsmPrimitive osm : sel) {
248            if (osm instanceof Way && !osm.isDeleted()) {
249                ways.add((Way) osm);
250            }
251        }
252
253        if (ways.size() < 2)
254            return null;
255
256        long idToKeep = 0;
257        Way wayToKeep = ways.iterator().next();
258        // Find the way that is member of one or more relations. (If any)
259        Way wayWithRelations = null;
260        List<Relation> relations = null;
261        for (Way w : ways) {
262            List<Relation> rel = OsmPrimitive.getFilteredList(w.getReferrers(), Relation.class);
263            if (!rel.isEmpty()) {
264                if (wayWithRelations != null)
265                    throw new AssertionError("Cannot fix duplicate Ways: More than one way is relation member.");
266                wayWithRelations = w;
267                relations = rel;
268            }
269            // Only one way will be kept - the one with lowest positive ID, if such exist
270            // or one "at random" if no such exists. Rest of the ways will be deleted
271            if (!w.isNew() && (idToKeep == 0 || w.getId() < idToKeep)) {
272                idToKeep = w.getId();
273                wayToKeep = w;
274            }
275        }
276
277        Collection<Command> commands = new LinkedList<>();
278
279        // Fix relations.
280        if (wayWithRelations != null && wayToKeep != wayWithRelations) {
281            for (Relation rel : relations) {
282                Relation newRel = new Relation(rel);
283                for (int i = 0; i < newRel.getMembers().size(); ++i) {
284                    RelationMember m = newRel.getMember(i);
285                    if (wayWithRelations.equals(m.getMember())) {
286                        newRel.setMember(i, new RelationMember(m.getRole(), wayToKeep));
287                    }
288                }
289                commands.add(new ChangeCommand(rel, newRel));
290            }
291        }
292
293        //Delete all ways in the list
294        //Note: nodes are not deleted, these can be detected and deleted at next pass
295        ways.remove(wayToKeep);
296        commands.add(new DeleteCommand(ways));
297        return new SequenceCommand(tr("Delete duplicate ways"), commands);
298    }
299
300    @Override
301    public boolean isFixable(TestError testError) {
302        if (!(testError.getTester() instanceof DuplicateWay))
303            return false;
304
305        //Do not automatically fix same ways with different tags
306        if (testError.getCode() != DUPLICATE_WAY) return false;
307
308        // We fix it only if there is no more than one way that is relation member.
309        Collection<? extends OsmPrimitive> sel = testError.getPrimitives();
310        Set<Way> ways = new HashSet<>();
311
312        for (OsmPrimitive osm : sel) {
313            if (osm instanceof Way) {
314                ways.add((Way) osm);
315            }
316        }
317
318        if (ways.size() < 2)
319            return false;
320
321        int waysWithRelations = 0;
322        for (Way w : ways) {
323            List<Relation> rel = OsmPrimitive.getFilteredList(w.getReferrers(), Relation.class);
324            if (!rel.isEmpty()) {
325                ++waysWithRelations;
326            }
327        }
328        return waysWithRelations <= 1;
329    }
330}