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