View Javadoc

1   package se.citerus.dddsample.domain.model.location;
2   
3   import org.apache.commons.lang.Validate;
4   import se.citerus.dddsample.domain.shared.ValueObject;
5   
6   import java.util.regex.Pattern;
7   
8   /**
9    * United nations location code.
10   * <p/>
11   * http://www.unece.org/cefact/locode/
12   * http://www.unece.org/cefact/locode/DocColumnDescription.htm#LOCODE
13   */
14  public final class UnLocode implements ValueObject<UnLocode> {
15  
16    private String unlocode;
17  
18    // Country code is exactly two letters.
19    // Location code is usually three letters, but may contain the numbers 2-9 as well
20    private static final Pattern VALID_PATTERN = Pattern.compile("[a-zA-Z]{2}[a-zA-Z2-9]{3}");
21  
22    /**
23     * Constructor.
24     *
25     * @param countryAndLocation Location string.
26     */
27    public UnLocode(final String countryAndLocation) {
28      Validate.notNull(countryAndLocation, "Country and location may not be null");
29      Validate.isTrue(VALID_PATTERN.matcher(countryAndLocation).matches(),
30        countryAndLocation + " is not a valid UN/LOCODE (does not match pattern)");
31  
32      this.unlocode = countryAndLocation.toUpperCase();
33    }
34  
35    /**
36     * @return country code and location code concatenated, always upper case.
37     */
38    public String idString() {
39      return unlocode;
40    }
41  
42    @Override
43    public boolean equals(final Object o) {
44      if (this == o) return true;
45      if (o == null || getClass() != o.getClass()) return false;
46  
47      UnLocode other = (UnLocode) o;
48  
49      return sameValueAs(other);
50    }
51  
52    @Override
53    public int hashCode() {
54      return unlocode.hashCode();
55    }
56  
57    @Override
58    public boolean sameValueAs(UnLocode other) {
59      return other != null && this.unlocode.equals(other.unlocode);
60    }
61  
62    @Override
63    public String toString() {
64      return idString();
65    }
66  
67    UnLocode() {
68      // Needed by Hibernate
69    }
70  
71  }