bc875b9bca6b2dd97d510dde7f105025dee6e9f5
[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 new, 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 HASH_FUNCTION = Hashing.sha256();
16         public static final int LENGTH = HASH_FUNCTION.bits() / 4;
17
18         private final HashFunction sha256 = HASH_FUNCTION;
19         private final String soneId;
20         private final String elementId;
21
22         private Id(String soneId, String elementId) {
23                 this.soneId = soneId;
24                 this.elementId = elementId;
25         }
26
27         public String getSoneId() {
28                 return soneId;
29         }
30
31         public String getElementId() {
32                 return elementId;
33         }
34
35         public String getExternal() {
36                 return sha256.newHasher()
37                                 .putBytes(soneId.getBytes(Charsets.UTF_8))
38                                 .putBytes(elementId.getBytes(Charsets.UTF_8))
39                                 .hash().toString();
40         }
41
42         public static Id from(String soneId, String elementId) {
43                 return new Id(soneId, elementId);
44         }
45
46         @Override
47         public boolean equals(Object o) {
48                 if (o == null || getClass() != o.getClass()) {
49                         return false;
50                 }
51                 Id id = (Id) o;
52                 return Objects.equal(soneId, id.soneId)
53                                 && Objects.equal(elementId, id.elementId);
54         }
55
56         @Override
57         public int hashCode() {
58                 return Objects.hashCode(soneId, elementId);
59         }
60
61         @Override
62         public String toString() {
63                 return getExternal();
64         }
65
66 }