source: josm/trunk/src/org/openstreetmap/josm/data/osm/DataSetMerger.java@ 2933

Last change on this file since 2933 was 2933, checked in by mjulius, 14 years ago

fixes #4467 - Don't silently drop locally deleted member primitives from downloaded ways and relation
conflicts are created instead

  • Property svn:eol-style set to native
File size: 17.4 KB
Line 
1package org.openstreetmap.josm.data.osm;
2
3import static org.openstreetmap.josm.tools.I18n.tr;
4
5import java.util.Collection;
6import java.util.HashMap;
7import java.util.HashSet;
8import java.util.LinkedList;
9import java.util.List;
10import java.util.Map;
11import java.util.Set;
12import java.util.logging.Logger;
13
14import org.openstreetmap.josm.data.conflict.ConflictCollection;
15import org.openstreetmap.josm.tools.CheckParameterUtil;
16
17/**
18 * A dataset merger which takes a target and a source dataset and merges the source data set
19 * onto the target dataset.
20 *
21 */
22public class DataSetMerger {
23 private static Logger logger = Logger.getLogger(DataSetMerger.class.getName());
24
25 /** the collection of conflicts created during merging */
26 private ConflictCollection conflicts;
27
28 /** the target dataset for merging */
29 private final DataSet targetDataSet;
30 /** the source dataset where primitives are merged from */
31 private final DataSet sourceDataSet;
32
33 /**
34 * A map of all primitives that got replaced with other primitives.
35 * Key is the primitive id in their dataset, the value is the id in my dataset
36 */
37 private Map<Long, Long> mergedMap;
38 /** a set of primitive ids for which we have to fix references (to nodes and
39 * to relation members) after the first phase of merging
40 */
41 private Set<PrimitiveId> objectsWithChildrenToMerge;
42 private Set<OsmPrimitive> deletedObjectsToUnlink;
43
44 /**
45 * constructor
46 *
47 * The visitor will merge <code>theirDataSet</code> onto <code>myDataSet</code>
48 *
49 * @param targetDataSet dataset with my primitives. Must not be null.
50 * @param sourceDataSet dataset with their primitives. Ignored, if null.
51 * @throws IllegalArgumentException thrown if myDataSet is null
52 */
53 public DataSetMerger(DataSet targetDataSet, DataSet sourceDataSet) throws IllegalArgumentException {
54 CheckParameterUtil.ensureParameterNotNull(targetDataSet, "targetDataSet");
55 this.targetDataSet = targetDataSet;
56 this.sourceDataSet = sourceDataSet;
57 conflicts = new ConflictCollection();
58 mergedMap = new HashMap<Long, Long>();
59 objectsWithChildrenToMerge = new HashSet<PrimitiveId>();
60 deletedObjectsToUnlink = new HashSet<OsmPrimitive>();
61 }
62
63 /**
64 * Merges a primitive <code>other</code> of type <P> onto my primitives.
65 *
66 * If other.id != 0 it tries to merge it with an corresponding primitive from
67 * my dataset with the same id. If this is not possible a conflict is remembered
68 * in {@see #conflicts}.
69 *
70 * If other.id == 0 it tries to find a primitive in my dataset with id == 0 which
71 * is semantically equal. If it finds one it merges its technical attributes onto
72 * my primitive.
73 *
74 * @param <P> the type of the other primitive
75 * @param source the other primitive
76 */
77 protected void mergePrimitive(OsmPrimitive source) {
78 if (!source.isNew() ) {
79 // try to merge onto a matching primitive with the same
80 // defined id
81 //
82 if (mergeById(source))
83 return;
84 //if (!source.isVisible())
85 // ignore it
86 // return;
87 } else {
88 // try to merge onto a primitive which has no id assigned
89 // yet but which is equal in its semantic attributes
90 //
91 Collection<? extends OsmPrimitive> candidates = null;
92 switch(source.getType()) {
93 case NODE: candidates = targetDataSet.getNodes(); break;
94 case WAY: candidates =targetDataSet.getWays(); break;
95 case RELATION: candidates = targetDataSet.getRelations(); break;
96 }
97 for (OsmPrimitive target : candidates) {
98 if (!target.isNew()) {
99 continue;
100 }
101 if (target.hasEqualSemanticAttributes(source)) {
102 mergedMap.put(source.getUniqueId(), target.getUniqueId());
103 if (target.isDeleted() != source.isDeleted()) {
104 // differences in deleted state have to be merged manually
105 //
106 conflicts.add(target, source);
107 } else {
108 // copy the technical attributes from other
109 // version
110 target.setVisible(source.isVisible());
111 target.setUser(source.getUser());
112 target.setTimestamp(source.getTimestamp());
113 target.setModified(source.isModified());
114 objectsWithChildrenToMerge.add(source.getPrimitiveId());
115 }
116 return;
117 }
118 }
119 }
120
121 // If we get here we didn't find a suitable primitive in
122 // the target dataset. Create a clone and add it to the target dataset.
123 //
124 OsmPrimitive target = null;
125 switch(source.getType()) {
126 case NODE: target = source.isNew() ? new Node() : new Node(source.getId()); break;
127 case WAY: target = source.isNew() ? new Way() : new Way(source.getId()); break;
128 case RELATION: target = source.isNew() ? new Relation() : new Relation(source.getId()); break;
129 }
130 target.mergeFrom(source);
131 targetDataSet.addPrimitive(target);
132 mergedMap.put(source.getUniqueId(), target.getUniqueId());
133 objectsWithChildrenToMerge.add(source.getPrimitiveId());
134 }
135
136 protected OsmPrimitive getMergeTarget(OsmPrimitive mergeSource) throws IllegalStateException{
137 Long targetId = mergedMap.get(mergeSource.getUniqueId());
138 if (targetId == null)
139 return null;
140 return targetDataSet.getPrimitiveById(targetId, mergeSource.getType());
141 }
142
143 protected void fixIncomplete(Way other) {
144 Way myWay = (Way)getMergeTarget(other);
145 if (myWay == null)
146 throw new RuntimeException(tr("Missing merge target for way with id {0}", other.getUniqueId()));
147 }
148
149 /**
150 * A way in the target dataset might be incomplete because at least one of its nodes is incomplete.
151 * The nodes might have become complete because a complete node was merged into in the
152 * merge operation.
153 *
154 * This method loops over all parent ways of such nodes and turns them into complete ways
155 * if necessary.
156 *
157 * @param other
158 */
159 protected void fixIncompleteParentWays(Node other) {
160 Node myNode = (Node)getMergeTarget(other);
161 if (myNode == null)
162 throw new RuntimeException(tr("Missing merge target for node with id {0}", other.getUniqueId()));
163 if (myNode.isIncomplete() || myNode.isDeleted() || !myNode.isVisible()) return;
164 }
165
166 /**
167 * Postprocess the dataset and fix all merged references to point to the actual
168 * data.
169 */
170 public void fixReferences() {
171 for (Way w : sourceDataSet.getWays()) {
172 if (!conflicts.hasConflictForTheir(w) && objectsWithChildrenToMerge.contains(w.getPrimitiveId())) {
173 mergeNodeList(w);
174 fixIncomplete(w);
175 }
176 }
177 for (Relation r : sourceDataSet.getRelations()) {
178 if (!conflicts.hasConflictForTheir(r) && objectsWithChildrenToMerge.contains(r.getPrimitiveId())) {
179 mergeRelationMembers(r);
180 }
181 }
182 for (OsmPrimitive source: deletedObjectsToUnlink) {
183 OsmPrimitive target = getMergeTarget(source);
184 if (target == null)
185 throw new RuntimeException(tr("Missing merge target for object with id {0}", source.getUniqueId()));
186 targetDataSet.unlinkReferencesToPrimitive(target);
187 }
188 // objectsWithChildrenToMerge also includes complete nodes which have
189 // been merged into their incomplete equivalents.
190 //
191 for (PrimitiveId id: objectsWithChildrenToMerge) {
192 if (!id.getType().equals(OsmPrimitiveType.NODE)) {
193 continue;
194 }
195 Node n = (Node)sourceDataSet.getPrimitiveById(id);
196 if (!conflicts.hasConflictForTheir(n)) {
197 fixIncompleteParentWays(n);
198 }
199 }
200
201 }
202
203 /**
204 * Merges the node list of a source way onto its target way.
205 *
206 * @param source the source way
207 * @throws IllegalStateException thrown if no target way can be found for the source way
208 * @throws IllegalStateException thrown if there isn't a target node for one of the nodes in the source way
209 *
210 */
211 private void mergeNodeList(Way source) throws IllegalStateException {
212 Way target = (Way)getMergeTarget(source);
213 if (target == null)
214 throw new IllegalStateException(tr("Missing merge target for way with id {0}", source.getUniqueId()));
215
216 List<Node> newNodes = new LinkedList<Node>();
217 for (Node sourceNode : source.getNodes()) {
218 Node targetNode = (Node)getMergeTarget(sourceNode);
219 if (targetNode != null) {
220 if (targetNode.isVisible()) {
221 newNodes.add(targetNode);
222 } else {
223 target.setModified(true);
224 }
225 } else
226 throw new IllegalStateException(tr("Missing merge target for node with id {0}", sourceNode.getUniqueId()));
227 }
228 target.setNodes(newNodes);
229 }
230
231 /**
232 * Merges the relation members of a source relation onto the corresponding target relation.
233 * @param source the source relation
234 * @throws IllegalStateException thrown if there is no corresponding target relation
235 * @throws IllegalStateException thrown if there isn't a corresponding target object for one of the relation
236 * members in source
237 */
238 private void mergeRelationMembers(Relation source) throws IllegalStateException {
239 Relation target = (Relation) getMergeTarget(source);
240 if (target == null)
241 throw new IllegalStateException(tr("Missing merge target for relation with id {0}", source.getUniqueId()));
242 LinkedList<RelationMember> newMembers = new LinkedList<RelationMember>();
243 for (RelationMember sourceMember : source.getMembers()) {
244 OsmPrimitive targetMember = getMergeTarget(sourceMember.getMember());
245 if (targetMember == null)
246 throw new IllegalStateException(tr("Missing merge target of type {0} with id {1}", sourceMember.getType(), sourceMember.getUniqueId()));
247 if (targetMember.isVisible()) {
248 RelationMember newMember = new RelationMember(sourceMember.getRole(), targetMember);
249 newMembers.add(newMember);
250 } else {
251 target.setModified(true);
252 }
253 }
254 target.setMembers(newMembers);
255 }
256
257 /**
258 * Tries to merge a primitive <code>source</code> into an existing primitive with the same id.
259 *
260 * @param source the source primitive which is to be merged into a target primitive
261 * @return true, if this method was able to merge <code>source</code> into a target object; false, otherwise
262 */
263 private boolean mergeById(OsmPrimitive source) {
264 OsmPrimitive target = targetDataSet.getPrimitiveById(source.getId(), source.getType());
265 // merge other into an existing primitive with the same id, if possible
266 //
267 if (target == null)
268 return false;
269 // found a corresponding target, remember it
270 mergedMap.put(source.getUniqueId(), target.getUniqueId());
271
272 if (target.getVersion() > source.getVersion())
273 // target.version > source.version => keep target version
274 return true;
275 if (! target.isVisible() && source.isVisible()) {
276 // should not happen
277 // FIXME: this message does not make sense, source version can not be lower than
278 // target version at this point
279 logger.warning(tr("Target object with id {0} and version {1} is visible although "
280 + "source object with lower version {2} is not visible. "
281 + "Cannot deal with this inconsistency. Keeping target object. ",
282 Long.toString(target.getId()),Long.toString(target.getVersion()), Long.toString(source.getVersion())
283 ));
284 } else if (target.isVisible() && ! source.isVisible()) {
285 // this is always a conflict because the user has to decide whether
286 // he wants to create a clone of its target primitive or whether he
287 // wants to purge the target from the local dataset. He can't keep it unchanged
288 // because it was deleted on the server.
289 //
290 conflicts.add(target,source);
291 } else if (target.isIncomplete() && !source.isIncomplete()) {
292 // target is incomplete, source completes it
293 // => merge source into target
294 //
295 target.mergeFrom(source);
296 objectsWithChildrenToMerge.add(source.getPrimitiveId());
297 } else if (!target.isIncomplete() && source.isIncomplete()) {
298 // target is complete and source is incomplete
299 // => keep target, it has more information already
300 //
301 } else if (target.isIncomplete() && source.isIncomplete()) {
302 // target and source are incomplete. Doesn't matter which one to
303 // take. We take target.
304 //
305 } else if (target.isDeleted() && ! source.isDeleted() && target.getVersion() == source.getVersion()) {
306 // same version, but target is deleted. Assume target takes precedence
307 // otherwise too many conflicts when refreshing from the server
308 // but, if source has referrers there is a conflict
309 if (!source.getReferrers().isEmpty()) {
310 conflicts.add(target, source);
311 }
312 } else if (target.isDeleted() != source.isDeleted()) {
313 // differences in deleted state have to be resolved manually. This can
314 // happen if one layer is merged onto another layer
315 //
316 conflicts.add(target,source);
317 } else if (! target.isModified() && source.isModified()) {
318 // target not modified. We can assume that source is the most recent version.
319 // clone it into target. But check first, whether source is deleted. if so,
320 // make sure that target is not referenced any more in myDataSet. If it is there
321 // is a conflict
322 if (source.isDeleted()) {
323 if (!target.getReferrers().isEmpty()) {
324 conflicts.add(target, source);
325 }
326 } else {
327 target.mergeFrom(source);
328 objectsWithChildrenToMerge.add(source.getPrimitiveId());
329 }
330 } else if (! target.isModified() && !source.isModified() && target.getVersion() == source.getVersion()) {
331 // both not modified. Merge nevertheless.
332 // This helps when updating "empty" relations, see #4295
333 target.mergeFrom(source);
334 objectsWithChildrenToMerge.add(source.getPrimitiveId());
335 } else if (! target.isModified() && !source.isModified() && target.getVersion() < source.getVersion()) {
336 // my not modified but other is newer. clone other onto mine.
337 //
338 target.mergeFrom(source);
339 objectsWithChildrenToMerge.add(source.getPrimitiveId());
340 } else if (target.isModified() && ! source.isModified() && target.getVersion() == source.getVersion()) {
341 // target is same as source but target is modified
342 // => keep target and reset modified flag if target and source are semantically equal
343 if (target.hasEqualSemanticAttributes(source)) {
344 target.setModified(false);
345 }
346 } else if (! target.hasEqualSemanticAttributes(source)) {
347 // target is modified and is not semantically equal with source. Can't automatically
348 // resolve the differences
349 // => create a conflict
350 conflicts.add(target,source);
351 } else {
352 // clone from other, but keep the modified flag. mergeFrom will mainly copy
353 // technical attributes like timestamp or user information. Semantic
354 // attributes should already be equal if we get here.
355 //
356 target.mergeFrom(source);
357 target.setModified(true);
358 objectsWithChildrenToMerge.add(source.getPrimitiveId());
359 }
360 return true;
361 }
362
363 /**
364 * Runs the merge operation. Successfully merged {@see OsmPrimitive}s are in
365 * {@see #getMyDataSet()}.
366 *
367 * See {@see #getConflicts()} for a map of conflicts after the merge operation.
368 */
369 public void merge() {
370 if (sourceDataSet == null)
371 return;
372 targetDataSet.beginUpdate();
373 try {
374 for (Node node: sourceDataSet.getNodes()) {
375 mergePrimitive(node);
376 }
377 for (Way way: sourceDataSet.getWays()) {
378 mergePrimitive(way);
379 }
380 for (Relation relation: sourceDataSet.getRelations()) {
381 mergePrimitive(relation);
382 }
383 fixReferences();
384 } finally {
385 targetDataSet.endUpdate();
386 }
387 }
388
389 /**
390 * replies my dataset
391 *
392 * @return
393 */
394 public DataSet getTargetDataSet() {
395 return targetDataSet;
396 }
397
398 /**
399 * replies the map of conflicts
400 *
401 * @return the map of conflicts
402 */
403 public ConflictCollection getConflicts() {
404 return conflicts;
405 }
406}
Note: See TracBrowser for help on using the repository browser.