75f9bc6e4f5098d5bba29274d74221762814e611
[Sone.git] / src / main / java / net / pterodactylus / sone / data / Id.java
1 package net.pterodactylus.sone.data;
2
3 import com.google.common.base.Charsets;
4 import com.google.common.base.Objects;
5 import com.google.common.hash.HashFunction;
6 import com.google.common.hash.Hashing;
7
8 /**
9  * Container for a combined ID, originally computed from a {@link Sone}’s ID and an element’s ID.
10  *
11  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
12  */
13 public class Id {
14
15         private static final HashFunction sha256 = Hashing.sha256();
16
17         private final String soneId;
18         private final String elementId;
19
20         private Id(String soneId, String elementId) {
21                 this.soneId = soneId;
22                 this.elementId = elementId;
23         }
24
25         public String getSoneId() {
26                 return soneId;
27         }
28
29         public String getElementId() {
30                 return elementId;
31         }
32
33         public String getExternal() {
34                 return sha256.newHasher()
35                                 .putBytes(soneId.getBytes(Charsets.UTF_8))
36                                 .putBytes(elementId.getBytes(Charsets.UTF_8))
37                                 .hash().toString();
38         }
39
40         public static Id from(String soneId, String elementId) {
41                 return new Id(soneId, elementId);
42         }
43
44         @Override
45         public boolean equals(Object o) {
46                 if (o == null || getClass() != o.getClass()) {
47                         return false;
48                 }
49                 Id id = (Id) o;
50                 return Objects.equal(soneId, id.soneId)
51                                 && Objects.equal(elementId, id.elementId);
52         }
53
54         @Override
55         public int hashCode() {
56                 return Objects.hashCode(soneId, elementId);
57         }
58
59         @Override
60         public String toString() {
61                 return getExternal();
62         }
63
64 }