source: josm/trunk/src/org/openstreetmap/josm/data/osm/AbstractPrimitive.java@ 6069

Last change on this file since 6069 was 6069, checked in by stoecker, 11 years ago

see #8853 remove tabs, trailing spaces, windows line ends, strange characters

  • Property svn:eol-style set to native
File size: 22.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.osm;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.text.MessageFormat;
7import java.util.Arrays;
8import java.util.Collection;
9import java.util.Collections;
10import java.util.Date;
11import java.util.HashMap;
12import java.util.HashSet;
13import java.util.Locale;
14import java.util.Map;
15import java.util.Map.Entry;
16import java.util.Set;
17import java.util.concurrent.atomic.AtomicLong;
18
19/**
20* Abstract class to represent common features of the datatypes primitives.
21*
22* @since 4099
23*/
24public abstract class AbstractPrimitive implements IPrimitive {
25
26 private static final AtomicLong idCounter = new AtomicLong(0);
27
28 static long generateUniqueId() {
29 return idCounter.decrementAndGet();
30 }
31
32 /**
33 * This flag shows, that the properties have been changed by the user
34 * and on upload the object will be send to the server.
35 */
36 protected static final int FLAG_MODIFIED = 1 << 0;
37
38 /**
39 * This flag is false, if the object is marked
40 * as deleted on the server.
41 */
42 protected static final int FLAG_VISIBLE = 1 << 1;
43
44 /**
45 * An object that was deleted by the user.
46 * Deleted objects are usually hidden on the map and a request
47 * for deletion will be send to the server on upload.
48 * An object usually cannot be deleted if it has non-deleted
49 * objects still referring to it.
50 */
51 protected static final int FLAG_DELETED = 1 << 2;
52
53 /**
54 * A primitive is incomplete if we know its id and type, but nothing more.
55 * Typically some members of a relation are incomplete until they are
56 * fetched from the server.
57 */
58 protected static final int FLAG_INCOMPLETE = 1 << 3;
59
60 /**
61 * Put several boolean flags to one short int field to save memory.
62 * Other bits of this field are used in subclasses.
63 */
64 protected volatile short flags = FLAG_VISIBLE; // visible per default
65
66 /*-------------------
67 * OTHER PROPERTIES
68 *-------------------*/
69
70 /**
71 * Unique identifier in OSM. This is used to identify objects on the server.
72 * An id of 0 means an unknown id. The object has not been uploaded yet to
73 * know what id it will get.
74 */
75 protected long id = 0;
76
77 /**
78 * User that last modified this primitive, as specified by the server.
79 * Never changed by JOSM.
80 */
81 protected User user = null;
82
83 /**
84 * Contains the version number as returned by the API. Needed to
85 * ensure update consistency
86 */
87 protected int version = 0;
88
89 /**
90 * The id of the changeset this primitive was last uploaded to.
91 * 0 if it wasn't uploaded to a changeset yet of if the changeset
92 * id isn't known.
93 */
94 protected int changesetId;
95
96 protected int timestamp;
97
98 /**
99 * Get and write all attributes from the parameter. Does not fire any listener, so
100 * use this only in the data initializing phase
101 * @param other the primitive to clone data from
102 */
103 public void cloneFrom(AbstractPrimitive other) {
104 setKeys(other.getKeys());
105 id = other.id;
106 if (id <=0) {
107 // reset version and changeset id
108 version = 0;
109 changesetId = 0;
110 }
111 timestamp = other.timestamp;
112 if (id > 0) {
113 version = other.version;
114 }
115 flags = other.flags;
116 user= other.user;
117 if (id > 0 && other.changesetId > 0) {
118 // #4208: sometimes we cloned from other with id < 0 *and*
119 // an assigned changeset id. Don't know why yet. For primitives
120 // with id < 0 we don't propagate the changeset id any more.
121 //
122 setChangesetId(other.changesetId);
123 }
124 }
125
126 /**
127 * Replies the version number as returned by the API. The version is 0 if the id is 0 or
128 * if this primitive is incomplete.
129 *
130 * @see PrimitiveData#setVersion(int)
131 */
132 @Override
133 public int getVersion() {
134 return version;
135 }
136
137 /**
138 * Replies the id of this primitive.
139 *
140 * @return the id of this primitive.
141 */
142 @Override
143 public long getId() {
144 long id = this.id;
145 return id >= 0?id:0;
146 }
147
148 /**
149 * Gets a unique id representing this object.
150 *
151 * @return Osm id if primitive already exists on the server. Unique negative value if primitive is new
152 */
153 @Override
154 public long getUniqueId() {
155 return id;
156 }
157
158 /**
159 *
160 * @return True if primitive is new (not yet uploaded the server, id <= 0)
161 */
162 @Override
163 public boolean isNew() {
164 return id <= 0;
165 }
166
167 /**
168 *
169 * @return True if primitive is new or undeleted
170 * @see #isNew()
171 * @see #isUndeleted()
172 */
173 @Override
174 public boolean isNewOrUndeleted() {
175 return (id <= 0) || ((flags & (FLAG_VISIBLE + FLAG_DELETED)) == 0);
176 }
177
178 /**
179 * Sets the id and the version of this primitive if it is known to the OSM API.
180 *
181 * Since we know the id and its version it can't be incomplete anymore. incomplete
182 * is set to false.
183 *
184 * @param id the id. > 0 required
185 * @param version the version > 0 required
186 * @throws IllegalArgumentException thrown if id <= 0
187 * @throws IllegalArgumentException thrown if version <= 0
188 * @throws DataIntegrityProblemException If id is changed and primitive was already added to the dataset
189 */
190 @Override
191 public void setOsmId(long id, int version) {
192 if (id <= 0)
193 throw new IllegalArgumentException(tr("ID > 0 expected. Got {0}.", id));
194 if (version <= 0)
195 throw new IllegalArgumentException(tr("Version > 0 expected. Got {0}.", version));
196 this.id = id;
197 this.version = version;
198 this.setIncomplete(false);
199 }
200
201 /**
202 * Clears the id and version known to the OSM API. The id and the version is set to 0.
203 * incomplete is set to false. It's preferred to use copy constructor with clearId set to true instead
204 * of calling this method.
205 */
206 public void clearOsmId() {
207 // Not part of dataset - no lock necessary
208 this.id = generateUniqueId();
209 this.version = 0;
210 this.user = null;
211 this.changesetId = 0; // reset changeset id on a new object
212 this.setIncomplete(false);
213 }
214
215 /**
216 * Replies the user who has last touched this object. May be null.
217 *
218 * @return the user who has last touched this object. May be null.
219 */
220 @Override
221 public User getUser() {
222 return user;
223 }
224
225 /**
226 * Sets the user who has last touched this object.
227 *
228 * @param user the user
229 */
230 @Override
231 public void setUser(User user) {
232 this.user = user;
233 }
234
235 /**
236 * Replies the id of the changeset this primitive was last uploaded to.
237 * 0 if this primitive wasn't uploaded to a changeset yet or if the
238 * changeset isn't known.
239 *
240 * @return the id of the changeset this primitive was last uploaded to.
241 */
242 @Override
243 public int getChangesetId() {
244 return changesetId;
245 }
246
247 /**
248 * Sets the changeset id of this primitive. Can't be set on a new
249 * primitive.
250 *
251 * @param changesetId the id. >= 0 required.
252 * @throws IllegalStateException thrown if this primitive is new.
253 * @throws IllegalArgumentException thrown if id < 0
254 */
255 @Override
256 public void setChangesetId(int changesetId) throws IllegalStateException, IllegalArgumentException {
257 if (this.changesetId == changesetId)
258 return;
259 if (changesetId < 0)
260 throw new IllegalArgumentException(MessageFormat.format("Parameter ''{0}'' >= 0 expected, got {1}", "changesetId", changesetId));
261 if (isNew() && changesetId > 0)
262 throw new IllegalStateException(tr("Cannot assign a changesetId > 0 to a new primitive. Value of changesetId is {0}", changesetId));
263
264 int old = this.changesetId;
265 this.changesetId = changesetId;
266 }
267
268 /**
269 * Replies the unique primitive id for this primitive
270 *
271 * @return the unique primitive id for this primitive
272 */
273 @Override
274 public PrimitiveId getPrimitiveId() {
275 return new SimplePrimitiveId(getUniqueId(), getType());
276 }
277
278 public OsmPrimitiveType getDisplayType() {
279 return getType();
280 }
281
282 @Override
283 public void setTimestamp(Date timestamp) {
284 this.timestamp = (int)(timestamp.getTime() / 1000);
285 }
286
287 /**
288 * Time of last modification to this object. This is not set by JOSM but
289 * read from the server and delivered back to the server unmodified. It is
290 * used to check against edit conflicts.
291 *
292 * @return date of last modification
293 */
294 @Override
295 public Date getTimestamp() {
296 return new Date(timestamp * 1000l);
297 }
298
299 @Override
300 public boolean isTimestampEmpty() {
301 return timestamp == 0;
302 }
303
304 /* -------
305 /* FLAGS
306 /* ------*/
307
308 protected void updateFlags(int flag, boolean value) {
309 if (value) {
310 flags |= flag;
311 } else {
312 flags &= ~flag;
313 }
314 }
315
316 /**
317 * Marks this primitive as being modified.
318 *
319 * @param modified true, if this primitive is to be modified
320 */
321 @Override
322 public void setModified(boolean modified) {
323 updateFlags(FLAG_MODIFIED, modified);
324 }
325
326 /**
327 * Replies <code>true</code> if the object has been modified since it was loaded from
328 * the server. In this case, on next upload, this object will be updated.
329 *
330 * Deleted objects are deleted from the server. If the objects are added (id=0),
331 * the modified is ignored and the object is added to the server.
332 *
333 * @return <code>true</code> if the object has been modified since it was loaded from
334 * the server
335 */
336 @Override
337 public boolean isModified() {
338 return (flags & FLAG_MODIFIED) != 0;
339 }
340
341 /**
342 * Replies <code>true</code>, if the object has been deleted.
343 *
344 * @return <code>true</code>, if the object has been deleted.
345 * @see #setDeleted(boolean)
346 */
347 @Override
348 public boolean isDeleted() {
349 return (flags & FLAG_DELETED) != 0;
350 }
351
352 /**
353 * Replies <code>true</code> if the object has been deleted on the server and was undeleted by the user.
354 * @return <code>true</code> if the object has been undeleted
355 */
356 public boolean isUndeleted() {
357 return (flags & (FLAG_VISIBLE + FLAG_DELETED)) == 0;
358 }
359
360 /**
361 * Replies <code>true</code>, if the object is usable
362 * (i.e. complete and not deleted).
363 *
364 * @return <code>true</code>, if the object is usable.
365 * @see #setDeleted(boolean)
366 */
367 public boolean isUsable() {
368 return (flags & (FLAG_DELETED + FLAG_INCOMPLETE)) == 0;
369 }
370
371 /**
372 * Checks if object is known to the server.
373 * Replies true if this primitive is either unknown to the server (i.e. its id
374 * is 0) or it is known to the server and it hasn't be deleted on the server.
375 * Replies false, if this primitive is known on the server and has been deleted
376 * on the server.
377 *
378 * @return <code>true</code>, if the object is visible on server.
379 * @see #setVisible(boolean)
380 */
381 @Override
382 public boolean isVisible() {
383 return (flags & FLAG_VISIBLE) != 0;
384 }
385
386 /**
387 * Sets whether this primitive is visible, i.e. whether it is known on the server
388 * and not deleted on the server.
389 *
390 * @see #isVisible()
391 * @throws IllegalStateException thrown if visible is set to false on an primitive with
392 * id==0
393 */
394 @Override
395 public void setVisible(boolean visible) throws IllegalStateException{
396 if (isNew() && visible == false)
397 throw new IllegalStateException(tr("A primitive with ID = 0 cannot be invisible."));
398 updateFlags(FLAG_VISIBLE, visible);
399 }
400
401 /**
402 * Sets whether this primitive is deleted or not.
403 *
404 * Also marks this primitive as modified if deleted is true.
405 *
406 * @param deleted true, if this primitive is deleted; false, otherwise
407 */
408 @Override
409 public void setDeleted(boolean deleted) {
410 updateFlags(FLAG_DELETED, deleted);
411 setModified(deleted ^ !isVisible());
412 }
413
414 /**
415 * If set to true, this object is incomplete, which means only the id
416 * and type is known (type is the objects instance class)
417 */
418 protected void setIncomplete(boolean incomplete) {
419 updateFlags(FLAG_INCOMPLETE, incomplete);
420 }
421
422 @Override
423 public boolean isIncomplete() {
424 return (flags & FLAG_INCOMPLETE) != 0;
425 }
426
427 protected String getFlagsAsString() {
428 StringBuilder builder = new StringBuilder();
429
430 if (isIncomplete()) {
431 builder.append("I");
432 }
433 if (isModified()) {
434 builder.append("M");
435 }
436 if (isVisible()) {
437 builder.append("V");
438 }
439 if (isDeleted()) {
440 builder.append("D");
441 }
442 return builder.toString();
443 }
444
445 /*------------
446 * Keys handling
447 ------------*/
448
449 // Note that all methods that read keys first make local copy of keys array reference. This is to ensure thread safety - reading
450 // doesn't have to be locked so it's possible that keys array will be modified. But all write methods make copy of keys array so
451 // the array itself will be never modified - only reference will be changed
452
453 /**
454 * The key/value list for this primitive.
455 *
456 */
457 protected String[] keys;
458
459 /**
460 * Replies the map of key/value pairs. Never replies null. The map can be empty, though.
461 *
462 * @return tags of this primitive. Changes made in returned map are not mapped
463 * back to the primitive, use setKeys() to modify the keys
464 */
465 @Override
466 public Map<String, String> getKeys() {
467 Map<String, String> result = new HashMap<String, String>();
468 String[] keys = this.keys;
469 if (keys != null) {
470 for (int i=0; i<keys.length ; i+=2) {
471 result.put(keys[i], keys[i + 1]);
472 }
473 }
474 return result;
475 }
476
477 /**
478 * Sets the keys of this primitives to the key/value pairs in <code>keys</code>.
479 * Old key/value pairs are removed.
480 * If <code>keys</code> is null, clears existing key/value pairs.
481 *
482 * @param keys the key/value pairs to set. If null, removes all existing key/value pairs.
483 */
484 @Override
485 public void setKeys(Map<String, String> keys) {
486 Map<String, String> originalKeys = getKeys();
487 if (keys == null || keys.isEmpty()) {
488 this.keys = null;
489 keysChangedImpl(originalKeys);
490 return;
491 }
492 String[] newKeys = new String[keys.size() * 2];
493 int index = 0;
494 for (Entry<String, String> entry:keys.entrySet()) {
495 newKeys[index++] = entry.getKey();
496 newKeys[index++] = entry.getValue();
497 }
498 this.keys = newKeys;
499 keysChangedImpl(originalKeys);
500 }
501
502 /**
503 * Set the given value to the given key. If key is null, does nothing. If value is null,
504 * removes the key and behaves like {@link #remove(String)}.
505 *
506 * @param key The key, for which the value is to be set. Can be null, does nothing in this case.
507 * @param value The value for the key. If null, removes the respective key/value pair.
508 *
509 * @see #remove(String)
510 */
511 @Override
512 public void put(String key, String value) {
513 Map<String, String> originalKeys = getKeys();
514 if (key == null)
515 return;
516 else if (value == null) {
517 remove(key);
518 } else if (keys == null){
519 keys = new String[] {key, value};
520 keysChangedImpl(originalKeys);
521 } else {
522 for (int i=0; i<keys.length;i+=2) {
523 if (keys[i].equals(key)) {
524 keys[i+1] = value; // This modifies the keys array but it doesn't make it invalidate for any time so its ok (see note no top)
525 keysChangedImpl(originalKeys);
526 return;
527 }
528 }
529 String[] newKeys = new String[keys.length + 2];
530 for (int i=0; i< keys.length;i+=2) {
531 newKeys[i] = keys[i];
532 newKeys[i+1] = keys[i+1];
533 }
534 newKeys[keys.length] = key;
535 newKeys[keys.length + 1] = value;
536 keys = newKeys;
537 keysChangedImpl(originalKeys);
538 }
539 }
540
541 /**
542 * Remove the given key from the list
543 *
544 * @param key the key to be removed. Ignored, if key is null.
545 */
546 @Override
547 public void remove(String key) {
548 if (key == null || keys == null) return;
549 if (!hasKey(key))
550 return;
551 Map<String, String> originalKeys = getKeys();
552 if (keys.length == 2) {
553 keys = null;
554 keysChangedImpl(originalKeys);
555 return;
556 }
557 String[] newKeys = new String[keys.length - 2];
558 int j=0;
559 for (int i=0; i < keys.length; i+=2) {
560 if (!keys[i].equals(key)) {
561 newKeys[j++] = keys[i];
562 newKeys[j++] = keys[i+1];
563 }
564 }
565 keys = newKeys;
566 keysChangedImpl(originalKeys);
567 }
568
569 /**
570 * Removes all keys from this primitive.
571 */
572 @Override
573 public void removeAll() {
574 if (keys != null) {
575 Map<String, String> originalKeys = getKeys();
576 keys = null;
577 keysChangedImpl(originalKeys);
578 }
579 }
580
581 /**
582 * Replies the value for key <code>key</code>. Replies null, if <code>key</code> is null.
583 * Replies null, if there is no value for the given key.
584 *
585 * @param key the key. Can be null, replies null in this case.
586 * @return the value for key <code>key</code>.
587 */
588 @Override
589 public final String get(String key) {
590 String[] keys = this.keys;
591 if (key == null)
592 return null;
593 if (keys == null)
594 return null;
595 for (int i=0; i<keys.length;i+=2) {
596 if (keys[i].equals(key)) return keys[i+1];
597 }
598 return null;
599 }
600
601 public final String getIgnoreCase(String key) {
602 String[] keys = this.keys;
603 if (key == null)
604 return null;
605 if (keys == null)
606 return null;
607 for (int i=0; i<keys.length;i+=2) {
608 if (keys[i].equalsIgnoreCase(key)) return keys[i+1];
609 }
610 return null;
611 }
612
613 @Override
614 public final Collection<String> keySet() {
615 String[] keys = this.keys;
616 if (keys == null)
617 return Collections.emptySet();
618 Set<String> result = new HashSet<String>(keys.length / 2);
619 for (int i=0; i<keys.length; i+=2) {
620 result.add(keys[i]);
621 }
622 return result;
623 }
624
625 /**
626 * Replies true, if the map of key/value pairs of this primitive is not empty.
627 *
628 * @return true, if the map of key/value pairs of this primitive is not empty; false
629 * otherwise
630 */
631 @Override
632 public final boolean hasKeys() {
633 return keys != null;
634 }
635
636 /**
637 * Replies true if this primitive has a tag with key <code>key</code>.
638 *
639 * @param key the key
640 * @return true, if his primitive has a tag with key <code>key</code>
641 */
642 public boolean hasKey(String key) {
643 String[] keys = this.keys;
644 if (key == null) return false;
645 if (keys == null) return false;
646 for (int i=0; i< keys.length;i+=2) {
647 if (keys[i].equals(key)) return true;
648 }
649 return false;
650 }
651
652 /**
653 * Replies true if other isn't null and has the same tags (key/value-pairs) as this.
654 *
655 * @param other the other object primitive
656 * @return true if other isn't null and has the same tags (key/value-pairs) as this.
657 */
658 public boolean hasSameTags(OsmPrimitive other) {
659 // We cannot directly use Arrays.equals(keys, other.keys) as keys is not ordered by key
660 // but we can at least check if both arrays are null or of the same size before creating
661 // and comparing the key maps (costly operation, see #7159)
662 return (keys == null && other.keys == null)
663 || (keys != null && other.keys != null && keys.length == other.keys.length && (keys.length == 0 || getKeys().equals(other.getKeys())));
664 }
665
666 /**
667 * What to do, when the tags have changed by one of the tag-changing methods.
668 */
669 abstract protected void keysChangedImpl(Map<String, String> originalKeys);
670
671 /**
672 * Replies the name of this primitive. The default implementation replies the value
673 * of the tag <tt>name</tt> or null, if this tag is not present.
674 *
675 * @return the name of this primitive
676 */
677 @Override
678 public String getName() {
679 return get("name");
680 }
681
682 /**
683 * Replies the a localized name for this primitive given by the value of the tags (in this order)
684 * <ul>
685 * <li>name:lang_COUNTRY_Variant of the current locale</li>
686 * <li>name:lang_COUNTRY of the current locale</li>
687 * <li>name:lang of the current locale</li>
688 * <li>name of the current locale</li>
689 * </ul>
690 *
691 * null, if no such tag exists
692 *
693 * @return the name of this primitive
694 */
695 @Override
696 public String getLocalName() {
697 String key = "name:" + Locale.getDefault().toString();
698 if (get(key) != null)
699 return get(key);
700 key = "name:" + Locale.getDefault().getLanguage() + "_" + Locale.getDefault().getCountry();
701 if (get(key) != null)
702 return get(key);
703 key = "name:" + Locale.getDefault().getLanguage();
704 if (get(key) != null)
705 return get(key);
706 return getName();
707 }
708
709 /**
710 * Tests whether this primitive contains a tag consisting of {@code key} and any of {@code values}.
711 * @param key the key forming the tag.
712 * @param values one or many values forming the tag.
713 * @return true iff primitive contains a tag consisting of {@code key} and any of {@code values}.
714 */
715 public boolean hasTag(String key, String... values) {
716 return hasTag(key, Arrays.asList(values));
717 }
718
719 /**
720 * Tests whether this primitive contains a tag consisting of {@code key} and any of {@code values}.
721 * @param key the key forming the tag.
722 * @param values one or many values forming the tag.
723 * @return true iff primitive contains a tag consisting of {@code key} and any of {@code values}.
724 */
725 public boolean hasTag(String key, Collection<String> values) {
726 return values.contains(get(key));
727 }
728}
Note: See TracBrowser for help on using the repository browser.