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

Last change on this file since 2594 was 2591, checked in by jttt, 14 years ago

Fix #4114 - NPE when zooming out after updating a partially downloaded relation or downloding the referrers of a node

  • Property svn:eol-style set to native
File size: 16.9 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;
15
16/**
17 * A dataset merger which takes a target and a source dataset and merges the source data set
18 * onto the target dataset.
19 *
20 */
21public class DataSetMerger {
22 private static Logger logger = Logger.getLogger(DataSetMerger.class.getName());
23
24 /** the collection of conflicts created during merging */
25 private ConflictCollection conflicts;
26
27 /** the target dataset for merging */
28 private final DataSet targetDataSet;
29 /** the source dataset where primitives are merged from */
30 private final DataSet sourceDataSet;
31
32 /**
33 * A map of all primitives that got replaced with other primitives.
34 * Key is the primitive id in their dataset, the value is the id in my dataset
35 */
36 private Map<Long, Long> mergedMap;
37 /** a set of primitive ids for which we have to fix references (to nodes and
38 * to relation members) after the first phase of merging
39 */
40 private Set<PrimitiveId> objectsWithChildrenToMerge;
41 private Set<OsmPrimitive> deletedObjectsToUnlink;
42
43 /**
44 * constructor
45 *
46 * The visitor will merge <code>theirDataSet</code> onto <code>myDataSet</code>
47 *
48 * @param targetDataSet dataset with my primitives. Must not be null.
49 * @param sourceDataSet dataset with their primitives. Ignored, if null.
50 * @throws IllegalArgumentException thrown if myDataSet is null
51 */
52 public DataSetMerger(DataSet targetDataSet, DataSet sourceDataSet) throws IllegalArgumentException {
53 if (targetDataSet == null)
54 throw new IllegalArgumentException(tr("Parameter ''{0}'' must not be null", "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 myWay.setHasIncompleteNodes();
148 }
149
150 /**
151 * A way in the target dataset might be incomplete because at least one of its nodes is incomplete.
152 * The nodes might have become complete because a complete node was merged into in the
153 * merge operation.
154 *
155 * This method loops over all parent ways of such nodes and turns them into complete ways
156 * if necessary.
157 *
158 * @param other
159 */
160 protected void fixIncompleteParentWays(Node other) {
161 Node myNode = (Node)getMergeTarget(other);
162 if (myNode == null)
163 throw new RuntimeException(tr("Missing merge target for node with id {0}", other.getUniqueId()));
164 if (myNode.isIncomplete() || myNode.isDeleted() || !myNode.isVisible()) return;
165
166 for (Way w: OsmPrimitive.getFilteredList(myNode.getReferrers(), Way.class)) {
167 w.setHasIncompleteNodes();
168 }
169 }
170
171 /**
172 * Postprocess the dataset and fix all merged references to point to the actual
173 * data.
174 */
175 public void fixReferences() {
176 for (Way w : sourceDataSet.getWays()) {
177 if (!conflicts.hasConflictForTheir(w) && objectsWithChildrenToMerge.contains(w.getPrimitiveId())) {
178 mergeNodeList(w);
179 fixIncomplete(w);
180 }
181 }
182 for (Relation r : sourceDataSet.getRelations()) {
183 if (!conflicts.hasConflictForTheir(r) && objectsWithChildrenToMerge.contains(r.getPrimitiveId())) {
184 mergeRelationMembers(r);
185 }
186 }
187 for (OsmPrimitive source: deletedObjectsToUnlink) {
188 OsmPrimitive target = getMergeTarget(source);
189 if (target == null)
190 throw new RuntimeException(tr("Missing merge target for object with id {0}", source.getUniqueId()));
191 targetDataSet.unlinkReferencesToPrimitive(target);
192 }
193 // objectsWithChildrenToMerge also includes complete nodes which have
194 // been merged into their incomplete equivalents.
195 //
196 for (PrimitiveId id: objectsWithChildrenToMerge) {
197 if (!id.getType().equals(OsmPrimitiveType.NODE)) {
198 continue;
199 }
200 Node n = (Node)sourceDataSet.getPrimitiveById(id);
201 if (!conflicts.hasConflictForTheir(n)) {
202 fixIncompleteParentWays(n);
203 }
204 }
205
206 }
207
208 /**
209 * Merges the node list of a source way onto its target way.
210 *
211 * @param source the source way
212 * @throws IllegalStateException thrown if no target way can be found for the source way
213 * @throws IllegalStateException thrown if there isn't a target node for one of the nodes in the source way
214 *
215 */
216 private void mergeNodeList(Way source) throws IllegalStateException {
217 Way target = (Way)getMergeTarget(source);
218 if (target == null)
219 throw new IllegalStateException(tr("Missing merge target for way with id {0}", source.getUniqueId()));
220
221 List<Node> newNodes = new LinkedList<Node>();
222 for (Node sourceNode : source.getNodes()) {
223 Node targetNode = (Node)getMergeTarget(sourceNode);
224 if (targetNode != null) {
225 if (!targetNode.isDeleted() && targetNode.isVisible()) {
226 newNodes.add(targetNode);
227 } else {
228 target.setModified(true);
229 }
230 } else
231 throw new IllegalStateException(tr("Missing merge target for node with id {0}", sourceNode.getUniqueId()));
232 }
233 target.setNodes(newNodes);
234 }
235
236 /**
237 * Merges the relation members of a source relation onto the corresponding target relation.
238 * @param source the source relation
239 * @throws IllegalStateException thrown if there is no corresponding target relation
240 * @throws IllegalStateException thrown if there isn't a corresponding target object for one of the relation
241 * members in source
242 */
243 private void mergeRelationMembers(Relation source) throws IllegalStateException {
244 Relation target = (Relation) getMergeTarget(source);
245 if (target == null)
246 throw new IllegalStateException(tr("Missing merge target for relation with id {0}", source.getUniqueId()));
247 LinkedList<RelationMember> newMembers = new LinkedList<RelationMember>();
248 for (RelationMember sourceMember : source.getMembers()) {
249 OsmPrimitive targetMember = getMergeTarget(sourceMember.getMember());
250 if (targetMember == null)
251 throw new IllegalStateException(tr("Missing merge target of type {0} with id {1}", targetMember.getType(), targetMember.getUniqueId()));
252 if (! targetMember.isDeleted() && targetMember.isVisible()) {
253 RelationMember newMember = new RelationMember(sourceMember.getRole(), targetMember);
254 newMembers.add(newMember);
255 } else {
256 target.setModified(true);
257 }
258 }
259 target.setMembers(newMembers);
260 }
261
262 /**
263 * Tries to merge a primitive <code>source</code> into an existing primitive with the same id.
264 *
265 * @param source the source primitive which is to be merged into a target primitive
266 * @return true, if this method was able to merge <code>source</code> into a target object; false, otherwise
267 */
268 private boolean mergeById(OsmPrimitive source) {
269 OsmPrimitive target = targetDataSet.getPrimitiveById(source.getId(), source.getType());
270 // merge other into an existing primitive with the same id, if possible
271 //
272 if (target == null)
273 return false;
274 // found a corresponding target, remember it
275 mergedMap.put(source.getUniqueId(), target.getUniqueId());
276
277 if (target.getVersion() > source.getVersion())
278 // target.version > source.version => keep target version
279 return true;
280 if (! target.isVisible() && source.isVisible()) {
281 // should not happen
282 //
283 logger.warning(tr("Target object with id {0} and version {1} is visible although "
284 + "source object with lower version {2} is not visible. "
285 + "Can''t deal with this inconsistency. Keeping target object. ",
286 Long.toString(target.getId()),Long.toString(target.getVersion()), Long.toString(source.getVersion())
287 ));
288 } else if (target.isVisible() && ! source.isVisible()) {
289 // this is always a conflict because the user has to decide whether
290 // he wants to create a clone of its target primitive or whether he
291 // wants to purge the target from the local dataset. He can't keep it unchanged
292 // because it was deleted on the server.
293 //
294 conflicts.add(target,source);
295 } else if (target.isIncomplete() && !source.isIncomplete()) {
296 // target is incomplete, source completes it
297 // => merge source into target
298 //
299 target.mergeFrom(source);
300 objectsWithChildrenToMerge.add(source.getPrimitiveId());
301 } else if (!target.isIncomplete() && source.isIncomplete()) {
302 // target is complete and source is incomplete
303 // => keep target, it has more information already
304 //
305 } else if (target.isIncomplete() && source.isIncomplete()) {
306 // target and source are incomplete. Doesn't matter which one to
307 // take. We take target.
308 //
309 } else if (target.isDeleted() && ! source.isDeleted() && target.getVersion() == source.getVersion()) {
310 // same version, but target is deleted. Assume target takes precedence
311 // otherwise too many conflicts when refreshing from the server
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.
321 //
322 if (source.isDeleted()) {
323 deletedObjectsToUnlink.add(source);
324 }
325 target.mergeFrom(source);
326 objectsWithChildrenToMerge.add(source.getPrimitiveId());
327 } else if (! target.isModified() && !source.isModified() && target.getVersion() == source.getVersion()) {
328 // both not modified. Keep mine
329 //
330 } else if (! target.isModified() && !source.isModified() && target.getVersion() < source.getVersion()) {
331 // my not modified but other is newer. clone other onto mine.
332 //
333 target.mergeFrom(source);
334 objectsWithChildrenToMerge.add(source.getPrimitiveId());
335 } else if (target.isModified() && ! source.isModified() && target.getVersion() == source.getVersion()) {
336 // target is same as source but target is modified
337 // => keep target
338 } else if (! target.hasEqualSemanticAttributes(source)) {
339 // target is modified and is not semantically equal with source. Can't automatically
340 // resolve the differences
341 // => create a conflict
342 conflicts.add(target,source);
343 } else {
344 // clone from other, but keep the modified flag. mergeFrom will mainly copy
345 // technical attributes like timestamp or user information. Semantic
346 // attributes should already be equal if we get here.
347 //
348 target.mergeFrom(source);
349 target.setModified(true);
350 objectsWithChildrenToMerge.add(source.getPrimitiveId());
351 }
352 return true;
353 }
354
355 /**
356 * Runs the merge operation. Successfully merged {@see OsmPrimitive}s are in
357 * {@see #getMyDataSet()}.
358 *
359 * See {@see #getConflicts()} for a map of conflicts after the merge operation.
360 */
361 public void merge() {
362 if (sourceDataSet == null)
363 return;
364 targetDataSet.beginUpdate();
365 try {
366 for (Node node: sourceDataSet.getNodes()) {
367 mergePrimitive(node);
368 }
369 for (Way way: sourceDataSet.getWays()) {
370 mergePrimitive(way);
371 }
372 for (Relation relation: sourceDataSet.getRelations()) {
373 mergePrimitive(relation);
374 }
375 fixReferences();
376 } finally {
377 targetDataSet.endUpdate();
378 }
379 }
380
381 /**
382 * replies my dataset
383 *
384 * @return
385 */
386 public DataSet getTargetDataSet() {
387 return targetDataSet;
388 }
389
390 /**
391 * replies the map of conflicts
392 *
393 * @return the map of conflicts
394 */
395 public ConflictCollection getConflicts() {
396 return conflicts;
397 }
398}
Note: See TracBrowser for help on using the repository browser.