001 // License: GPL. For details, see LICENSE file.
002 package org.openstreetmap.josm.data.osm;
003
004 import java.io.Serializable;
005 import java.util.regex.Matcher;
006 import java.util.regex.Pattern;
007
008 public class SimplePrimitiveId implements PrimitiveId, Serializable {
009 private final long id;
010 private final OsmPrimitiveType type;
011
012 public SimplePrimitiveId(long id, OsmPrimitiveType type) {
013 this.id = id;
014 this.type = type;
015 }
016
017 public OsmPrimitiveType getType() {
018 return type;
019 }
020
021 public long getUniqueId() {
022 return id;
023 }
024
025 public boolean isNew() {
026 return id <= 0;
027 }
028
029 @Override
030 public int hashCode() {
031 final int prime = 31;
032 int result = 1;
033 result = prime * result + (int) (id ^ (id >>> 32));
034 result = prime * result + ((type == null) ? 0 : type.hashCode());
035 return result;
036 }
037
038 @Override
039 public boolean equals(Object obj) {
040 if (this == obj)
041 return true;
042 if (obj == null)
043 return false;
044 if (getClass() != obj.getClass())
045 return false;
046 SimplePrimitiveId other = (SimplePrimitiveId) obj;
047 if (id != other.id)
048 return false;
049 if (type == null) {
050 if (other.type != null)
051 return false;
052 } else if (!type.equals(other.type))
053 return false;
054 return true;
055 }
056
057 @Override
058 public String toString() {
059 return type + " " + id;
060 }
061
062 /**
063 * Parses a {@code OsmPrimitiveType} from the string {@code s}.
064 * @param s the string to be parsed, e.g., {@code n1}, {@code node1},
065 * {@code w1}, {@code way1}, {@code r1}, {@code rel1}, {@code relation1}.
066 * @return the parsed {@code OsmPrimitiveType}
067 * @throws IllegalArgumentException if the string does not match the pattern
068 */
069 public static SimplePrimitiveId fromString(String s) {
070 final Pattern p = Pattern.compile("((n(ode)?|w(ay)?|r(el(ation)?)?)/?)(\\d+)");
071 final Matcher m = p.matcher(s);
072 if (m.matches()) {
073 return new SimplePrimitiveId(Long.parseLong(m.group(m.groupCount())),
074 s.charAt(0) == 'n' ? OsmPrimitiveType.NODE
075 : s.charAt(0) == 'w' ? OsmPrimitiveType.WAY
076 : OsmPrimitiveType.RELATION);
077 } else {
078 throw new IllegalArgumentException("The string " + s + " does not match the pattern " + p);
079 }
080 }
081 }