001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.osm;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.geom.Area;
007import java.util.ArrayList;
008import java.util.Collection;
009import java.util.HashMap;
010import java.util.HashSet;
011import java.util.Iterator;
012import java.util.LinkedList;
013import java.util.List;
014import java.util.Map;
015import java.util.Set;
016
017import org.openstreetmap.josm.data.DataSource;
018import org.openstreetmap.josm.data.conflict.Conflict;
019import org.openstreetmap.josm.data.conflict.ConflictCollection;
020import org.openstreetmap.josm.gui.progress.ProgressMonitor;
021import org.openstreetmap.josm.tools.CheckParameterUtil;
022import org.openstreetmap.josm.tools.JosmRuntimeException;
023
024/**
025 * A dataset merger which takes a target and a source dataset and merges the source data set
026 * onto the target dataset.
027 *
028 */
029public class DataSetMerger {
030
031    /** the collection of conflicts created during merging */
032    private final ConflictCollection conflicts;
033
034    /** the target dataset for merging */
035    private final DataSet targetDataSet;
036    /** the source dataset where primitives are merged from */
037    private final DataSet sourceDataSet;
038
039    /**
040     * A map of all primitives that got replaced with other primitives.
041     * Key is the PrimitiveId in their dataset, the value is the PrimitiveId in my dataset
042     */
043    private final Map<PrimitiveId, PrimitiveId> mergedMap;
044    /** a set of primitive ids for which we have to fix references (to nodes and
045     * to relation members) after the first phase of merging
046     */
047    private final Set<PrimitiveId> objectsWithChildrenToMerge;
048    private final Set<OsmPrimitive> objectsToDelete;
049
050    /**
051     * constructor
052     * <p>
053     * The visitor will merge <code>sourceDataSet</code> onto <code>targetDataSet</code>
054     *
055     * @param targetDataSet dataset with my primitives. Must not be null.
056     * @param sourceDataSet dataset with their primitives. Ignored, if null.
057     * @throws IllegalArgumentException if myDataSet is null
058     */
059    public DataSetMerger(DataSet targetDataSet, DataSet sourceDataSet) {
060        CheckParameterUtil.ensureParameterNotNull(targetDataSet, "targetDataSet");
061        this.targetDataSet = targetDataSet;
062        this.sourceDataSet = sourceDataSet;
063        conflicts = new ConflictCollection();
064        mergedMap = new HashMap<>();
065        objectsWithChildrenToMerge = new HashSet<>();
066        objectsToDelete = new HashSet<>();
067    }
068
069    /**
070     * Merges a primitive onto primitives dataset.
071     * <p>
072     * If other.id != 0 it tries to merge it with an corresponding primitive from
073     * my dataset with the same id. If this is not possible a conflict is remembered
074     * in {@link #conflicts}.
075     * <p>
076     * If other.id == 0 (new primitive) it tries to find a primitive in my dataset with id == 0 which
077     * is semantically equal. If it finds one it merges its technical attributes onto
078     * my primitive.
079     *
080     * @param source the primitive to merge
081     * @param candidates a set of possible candidates for a new primitive
082     */
083    protected void mergePrimitive(OsmPrimitive source, Collection<? extends OsmPrimitive> candidates) {
084        if (!source.isNew()) {
085            // try to merge onto a matching primitive with the same defined id
086            //
087            if (mergeById(source))
088                return;
089        } else {
090            // ignore deleted primitives from source
091            if (source.isDeleted()) return;
092
093            // try to merge onto a primitive  which has no id assigned
094            // yet but which is equal in its semantic attributes
095            //
096            for (OsmPrimitive target : candidates) {
097                if (!target.isNew() || target.isDeleted()) {
098                    continue;
099                }
100                if (target.hasEqualSemanticAttributes(source)) {
101                    mergedMap.put(source.getPrimitiveId(), target.getPrimitiveId());
102                    // copy the technical attributes from other version
103                    target.setVisible(source.isVisible());
104                    target.setUser(source.getUser());
105                    target.setRawTimestamp(source.getRawTimestamp());
106                    target.setModified(source.isModified());
107                    objectsWithChildrenToMerge.add(source.getPrimitiveId());
108                    return;
109                }
110            }
111        }
112
113        // If we get here we didn't find a suitable primitive in
114        // the target dataset. Create a clone and add it to the target dataset.
115        //
116        OsmPrimitive target;
117        switch (source.getType()) {
118        case NODE: target = source.isNew() ? new Node() : new Node(source.getId()); break;
119        case WAY: target = source.isNew() ? new Way() : new Way(source.getId()); break;
120        case RELATION: target = source.isNew() ? new Relation() : new Relation(source.getId()); break;
121        default: throw new AssertionError();
122        }
123        target.mergeFrom(source);
124        targetDataSet.addPrimitive(target);
125        mergedMap.put(source.getPrimitiveId(), target.getPrimitiveId());
126        objectsWithChildrenToMerge.add(source.getPrimitiveId());
127    }
128
129    protected OsmPrimitive getMergeTarget(OsmPrimitive mergeSource) {
130        PrimitiveId targetId = mergedMap.get(mergeSource.getPrimitiveId());
131        if (targetId == null)
132            return null;
133        return targetDataSet.getPrimitiveById(targetId);
134    }
135
136    protected void addConflict(Conflict<?> c) {
137        c.setMergedMap(mergedMap);
138        conflicts.add(c);
139    }
140
141    protected void addConflict(OsmPrimitive my, OsmPrimitive their) {
142        addConflict(new Conflict<>(my, their));
143    }
144
145    private void replaceConflict(Conflict<?> oldConflict, Conflict<?> newConflict) {
146        newConflict.setMergedMap(mergedMap);
147        conflicts.remove(oldConflict);
148        conflicts.add(newConflict);
149    }
150
151    protected void fixIncomplete(Way other) {
152        Way myWay = (Way) getMergeTarget(other);
153        if (myWay == null)
154            throw new JosmRuntimeException(tr("Missing merge target for way with id {0}", other.getUniqueId()));
155    }
156
157    /**
158     * Postprocess the dataset and fix all merged references to point to the actual data.
159     */
160    public void fixReferences() {
161        for (Way w : sourceDataSet.getWays()) {
162            if (!conflicts.hasConflictForTheir(w) && objectsWithChildrenToMerge.contains(w.getPrimitiveId())) {
163                mergeNodeList(w);
164                fixIncomplete(w);
165            }
166        }
167        for (Relation r : sourceDataSet.getRelations()) {
168            if (!conflicts.hasConflictForTheir(r) && objectsWithChildrenToMerge.contains(r.getPrimitiveId())) {
169                mergeRelationMembers(r);
170            }
171        }
172
173        deleteMarkedObjects();
174    }
175
176    /**
177     * Deleted objects in objectsToDelete set and create conflicts for objects that cannot
178     * be deleted because they're referenced in the target dataset.
179     */
180    protected void deleteMarkedObjects() {
181        boolean flag;
182        do {
183            flag = false;
184            for (Iterator<OsmPrimitive> it = objectsToDelete.iterator(); it.hasNext();) {
185                OsmPrimitive target = it.next();
186                OsmPrimitive source = sourceDataSet.getPrimitiveById(target.getPrimitiveId());
187                if (source == null)
188                    throw new JosmRuntimeException(
189                            tr("Object of type {0} with id {1} was marked to be deleted, but it''s missing in the source dataset",
190                            target.getType(), target.getUniqueId()));
191
192                List<OsmPrimitive> referrers = target.getReferrers();
193                if (referrers.isEmpty()) {
194                    IPrimitive.resetPrimitiveChildren(target);
195                    target.mergeFrom(source);
196                    target.setDeleted(true);
197                    it.remove();
198                    flag = true;
199                } else {
200                    for (OsmPrimitive referrer : referrers) {
201                        // If one of object referrers isn't going to be deleted,
202                        // add a conflict and don't delete the object
203                        if (!objectsToDelete.contains(referrer)) {
204                            addConflict(target, source);
205                            it.remove();
206                            flag = true;
207                            break;
208                        }
209                    }
210                }
211
212            }
213        } while (flag);
214
215        if (!objectsToDelete.isEmpty()) {
216            // There are some more objects rest in the objectsToDelete set
217            // This can be because of cross-referenced relations.
218            for (OsmPrimitive osm: objectsToDelete) {
219                IPrimitive.resetPrimitiveChildren(osm);
220            }
221            for (OsmPrimitive osm: objectsToDelete) {
222                osm.setDeleted(true);
223                osm.mergeFrom(sourceDataSet.getPrimitiveById(osm.getPrimitiveId()));
224            }
225        }
226    }
227
228    /**
229     * Merges the node list of a source way onto its target way.
230     *
231     * @param source the source way
232     * @throws IllegalStateException if no target way can be found for the source way
233     * @throws IllegalStateException if there isn't a target node for one of the nodes in the source way
234     *
235     */
236    private void mergeNodeList(Way source) {
237        Way target = (Way) getMergeTarget(source);
238        if (target == null)
239            throw new IllegalStateException(tr("Missing merge target for way with id {0}", source.getUniqueId()));
240
241        List<Node> newNodes = new ArrayList<>(source.getNodesCount());
242        for (Node sourceNode : source.getNodes()) {
243            Node targetNode = (Node) getMergeTarget(sourceNode);
244            if (targetNode != null) {
245                newNodes.add(targetNode);
246                if (targetNode.isDeleted() && !conflicts.hasConflictForMy(targetNode)) {
247                    addConflict(new Conflict<>(targetNode, sourceNode, true));
248                    targetNode.setDeleted(false);
249                }
250            } else
251                throw new IllegalStateException(tr("Missing merge target for node with id {0}", sourceNode.getUniqueId()));
252        }
253        target.setNodes(newNodes);
254    }
255
256    /**
257     * Merges the relation members of a source relation onto the corresponding target relation.
258     * @param source the source relation
259     * @throws IllegalStateException if there is no corresponding target relation
260     * @throws IllegalStateException if there isn't a corresponding target object for one of the relation
261     * members in source
262     */
263    private void mergeRelationMembers(Relation source) {
264        Relation target = (Relation) getMergeTarget(source);
265        if (target == null)
266            throw new IllegalStateException(tr("Missing merge target for relation with id {0}", source.getUniqueId()));
267        List<RelationMember> newMembers = new LinkedList<>();
268        for (RelationMember sourceMember : source.getMembers()) {
269            OsmPrimitive targetMember = getMergeTarget(sourceMember.getMember());
270            if (targetMember == null)
271                throw new IllegalStateException(tr("Missing merge target of type {0} with id {1}",
272                        sourceMember.getType(), sourceMember.getUniqueId()));
273            newMembers.add(new RelationMember(sourceMember.getRole(), targetMember));
274            if (targetMember.isDeleted() && !conflicts.hasConflictForMy(targetMember)) {
275                addConflict(new Conflict<>(targetMember, sourceMember.getMember(), true));
276                targetMember.setDeleted(false);
277            }
278        }
279        target.setMembers(newMembers);
280    }
281
282    /**
283     * Tries to merge a primitive <code>source</code> into an existing primitive with the same id.
284     *
285     * @param source  the source primitive which is to be merged into a target primitive
286     * @return true, if this method was able to merge <code>source</code> into a target object; false, otherwise
287     */
288    private boolean mergeById(OsmPrimitive source) {
289        OsmPrimitive target = targetDataSet.getPrimitiveById(source.getId(), source.getType());
290        // merge other into an existing primitive with the same id, if possible
291        //
292        if (target == null)
293            return false;
294        // found a corresponding target, remember it
295        mergedMap.put(source.getPrimitiveId(), target.getPrimitiveId());
296
297        if (target.getVersion() > source.getVersion())
298            // target.version > source.version => keep target version
299            return true;
300
301        boolean mergeFromSource = false;
302        boolean haveSameVersion = target.getVersion() == source.getVersion();
303
304        if (haveSameVersion && !target.isModified() && !source.isModified()
305                && target.isVisible() != source.isVisible()) {
306            // Same version, but different "visible" attribute and neither of them are modified.
307            // It indicates a serious problem in datasets.
308            // For example, datasets can be fetched from different OSM servers or badly hand-modified.
309            // We should not merge these datasets.
310            throw new DataIntegrityProblemException(tr("Conflict in ''visible'' attribute for object of type {0} with id {1}",
311                    target.getType(), target.getId()));
312        }
313
314        if (!target.isModified() && source.isDeleted()) {
315            // target not modified and source is deleted
316            // So mark it to be deleted. See #20091
317            //
318            objectsToDelete.add(target);
319        } else if (source.isIncomplete()) {
320            // source is incomplete. Nothing to do.
321            //
322        } else if (target.isIncomplete()) {
323            // target is incomplete, source completes it
324            // => merge source into target
325            //
326            mergeFromSource = true;
327        } else if (target.isDeleted() && source.isDeleted() && !haveSameVersion) {
328            // both deleted. Source is newer. Take source. See #19783
329            mergeFromSource = true;
330        } else if (target.isDeleted() && !source.isDeleted() && haveSameVersion) {
331            // same version, but target is deleted. Assume target takes precedence
332            // otherwise too many conflicts when refreshing from the server
333            // but, if source is modified, there is a conflict
334            Conflict<?> currentConflict = null;
335            if (source.isModified()) {
336                currentConflict = new Conflict<>(target, source, true);
337                addConflict(currentConflict);
338            }
339            // or, if source has a referrer that is not in the target dataset there is a conflict
340            // If target dataset refers to the deleted primitive, conflict will be added in fixReferences method
341            for (OsmPrimitive referrer: source.getReferrers()) {
342                if (targetDataSet.getPrimitiveById(referrer.getPrimitiveId()) == null) {
343                    final Conflict<?> newConflict = new Conflict<>(target, source, true);
344                    if (currentConflict != null) { // See #23930
345                        replaceConflict(currentConflict, newConflict);
346                    } else {
347                        addConflict(newConflict);
348                    }
349                    target.setDeleted(false);
350                    break;
351                }
352            }
353        } else if (!target.isModified() && source.isModified()) {
354            // target not modified. We can assume that source is the most recent version.
355            // clone it into target.
356            mergeFromSource = true;
357        } else if (!target.isModified() && !source.isModified()) {
358            // both not modified. Merge nevertheless, even if versions are the same
359            // This helps when updating "empty" relations, see #4295
360            mergeFromSource = true;
361        } else if (target.isModified() && !source.isModified() && haveSameVersion) {
362            // target is same as source but target is modified
363            // => keep target and reset modified flag if target and source are semantically equal
364            if (target.hasEqualSemanticAttributes(source, false)) {
365                target.setModified(false);
366            }
367            target.setReferrersDownloaded(target.isReferrersDownloaded() || source.isReferrersDownloaded());
368        } else if (source.isDeleted() != target.isDeleted()) {
369            // target is modified and deleted state differs.
370            // this has to be resolved manually.
371            //
372            addConflict(target, source);
373        } else if (!target.hasEqualSemanticAttributes(source)) {
374            // target is modified and is not semantically equal with source. Can't automatically
375            // resolve the differences
376            // =>  create a conflict
377            addConflict(target, source);
378        } else {
379            // clone from other. mergeFrom will mainly copy
380            // technical attributes like timestamp or user information. Semantic
381            // attributes should already be equal if we get here.
382            //
383            mergeFromSource = true;
384        }
385        if (mergeFromSource) {
386            boolean backupReferrersDownloadedStatus = target.isReferrersDownloaded() && haveSameVersion;
387            target.mergeFrom(source);
388            if (backupReferrersDownloadedStatus && !target.isReferrersDownloaded()) {
389                target.setReferrersDownloaded(true);
390            }
391            objectsWithChildrenToMerge.add(source.getPrimitiveId());
392        }
393        return true;
394    }
395
396    /**
397     * Runs the merge operation. Successfully merged {@link OsmPrimitive}s are in
398     * {@link #getTargetDataSet()}.
399     * <p>
400     * See {@link #getConflicts()} for a map of conflicts after the merge operation.
401     */
402    public void merge() {
403        merge(null);
404    }
405
406    /**
407     * Runs the merge operation. Successfully merged {@link OsmPrimitive}s are in
408     * {@link #getTargetDataSet()}.
409     * <p>
410     * See {@link #getConflicts()} for a map of conflicts after the merge operation.
411     * @param progressMonitor The progress monitor
412     */
413    public void merge(ProgressMonitor progressMonitor) {
414        merge(progressMonitor, true);
415    }
416
417    /**
418     * Runs the merge operation. Successfully merged {@link OsmPrimitive}s are in
419     * {@link #getTargetDataSet()}.
420     * <p>
421     * See {@link #getConflicts()} for a map of conflicts after the merge operation.
422     * @param progressMonitor The progress monitor
423     * @param mergeBounds Whether or not to merge the bounds of the new DataSet to
424     * the existing DataSet
425     * @since 15127
426     */
427    public void merge(ProgressMonitor progressMonitor, boolean mergeBounds) {
428        if (sourceDataSet == null)
429            return;
430        if (progressMonitor != null) {
431            progressMonitor.beginTask(tr("Merging data..."), sourceDataSet.allPrimitives().size());
432        }
433        targetDataSet.update(() -> {
434            List<? extends OsmPrimitive> candidates = null;
435            for (Node node: sourceDataSet.getNodes()) {
436                // lazy initialisation to improve performance, see #19898
437                if (candidates == null) {
438                    candidates = new ArrayList<>(targetDataSet.getNodes());
439                }
440                mergePrimitive(node, candidates);
441                if (progressMonitor != null) {
442                    progressMonitor.worked(1);
443                }
444            }
445            candidates = null;
446            for (Way way: sourceDataSet.getWays()) {
447                // lazy initialisation to improve performance
448                if (candidates == null) {
449                    candidates = new ArrayList<>(targetDataSet.getWays());
450                }
451                mergePrimitive(way, candidates);
452                if (progressMonitor != null) {
453                    progressMonitor.worked(1);
454                }
455            }
456            candidates = null;
457            for (Relation relation: sourceDataSet.getRelations()) {
458                // lazy initialisation to improve performance
459                if (candidates == null) {
460                    candidates = new ArrayList<>(targetDataSet.getRelations());
461                }
462                mergePrimitive(relation, candidates);
463                if (progressMonitor != null) {
464                    progressMonitor.worked(1);
465                }
466            }
467            candidates = null;
468            fixReferences();
469
470            Area a = targetDataSet.getDataSourceArea();
471
472            // copy the merged layer's data source info.
473            // only add source rectangles if they are not contained in the layer already.
474            if (mergeBounds) {
475                for (DataSource src : sourceDataSet.getDataSources()) {
476                    if (a == null || !a.contains(src.bounds.asRect())) {
477                        targetDataSet.addDataSource(src);
478                    }
479                }
480            }
481
482            // copy the merged layer's API version
483            if (targetDataSet.getVersion() == null) {
484                targetDataSet.setVersion(sourceDataSet.getVersion());
485            }
486
487            // copy the merged layer's policies and locked status
488            if (sourceDataSet.getUploadPolicy() != null && (targetDataSet.getUploadPolicy() == null
489                    || sourceDataSet.getUploadPolicy().compareTo(targetDataSet.getUploadPolicy()) > 0)) {
490                targetDataSet.setUploadPolicy(sourceDataSet.getUploadPolicy());
491            }
492            if (sourceDataSet.getDownloadPolicy() != null && (targetDataSet.getDownloadPolicy() == null
493                    || sourceDataSet.getDownloadPolicy().compareTo(targetDataSet.getDownloadPolicy()) > 0)) {
494                targetDataSet.setDownloadPolicy(sourceDataSet.getDownloadPolicy());
495            }
496            if (sourceDataSet.isLocked() && !targetDataSet.isLocked()) {
497                targetDataSet.lock();
498            }
499        });
500        if (progressMonitor != null) {
501            progressMonitor.finishTask();
502        }
503    }
504
505    /**
506     * replies my dataset
507     *
508     * @return the own (target) data set
509     */
510    public DataSet getTargetDataSet() {
511        return targetDataSet;
512    }
513
514    /**
515     * replies the map of conflicts
516     *
517     * @return the map of conflicts
518     */
519    public ConflictCollection getConflicts() {
520        return conflicts;
521    }
522}