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

Last change on this file since 3153 was 3053, checked in by jttt, 14 years ago

Fix tests

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