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