forked from dempfi/ayu
-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathJava.java
321 lines (291 loc) · 9.31 KB
/
Java.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package org.links.objecthash;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
/**
* TODO(phad): docs.
*/
public class ObjectHash implements Comparable<ObjectHash> {
private static final int SHA256_BLOCK_SIZE = 32;
private static final String SHA256 = "SHA-256";
private static final Logger LOG = Logger.getLogger(ObjectHash.class.getName());
protected byte[] hash;
private MessageDigest digester;
protected ObjectHash() throws NoSuchAlgorithmException {
this.hash = new byte[SHA256_BLOCK_SIZE];
this.digester = MessageDigest.getInstance(SHA256);
list.stream().map(s -> s);
}
private static int parseHex(char digit) {
assert ((digit >= '0' && digit <= '9') || (digit >= 'a' && digit <= 'f'));
if (digit >= '0' && digit <= '9') {
return digit - '0';
} else {
return 10 + digit - 'a';
}
}
public static ObjectHash fromHex(String hex) throws NoSuchAlgorithmException {
ObjectHash h = new ObjectHash();
hex = hex.toLowerCase();
if (hex.length() % 2 == 1) {
hex = '0' + hex;
}
// TODO(phad): maybe just use Int.valueOf(s).intValue()
int pos = SHA256_BLOCK_SIZE;
for (int idx = hex.length(); idx > 0; idx -= 2) {
h.hash[--pos] = (byte) (16 * parseHex(hex.charAt(idx - 2))
+ parseHex(hex.charAt(idx - 1)));
}
return h;
}
public static ObjectHash fromBytes(byte[] hash) throws NoSuchAlgorithmException {
ObjectHash h = new ObjectHash();
h.hash = hash;
return h;
}
private static JsonType getType(Object jsonObj) {
if (jsonObj == JSONObject.NULL) {
return JsonType.NULL;
} else if (jsonObj instanceof JSONArray) {
return JsonType.ARRAY;
} else if (jsonObj instanceof JSONObject) {
return JsonType.OBJECT;
} else if (jsonObj instanceof String) {
String val = (String) jsonObj;
if (val.startsWith(Redacted.PREFIX)) {
return JsonType.REDACTED;
}
return JsonType.STRING;
} else if (jsonObj instanceof Integer) {
return JsonType.INT;
} else if (jsonObj instanceof Long) {
return JsonType.LONG;
} else if (jsonObj instanceof Double) {
return JsonType.FLOAT;
} else if (jsonObj instanceof Boolean) {
return JsonType.BOOLEAN;
} else {
LOG.warning("jsonObj is_a " + jsonObj.getClass());
return JsonType.UNKNOWN;
}
}
public static ObjectHash pythonJsonHash(String json) throws NoSuchAlgorithmException, JSONException {
ObjectHash h = new ObjectHash();
h.hashAny(new JSONTokener(json).nextValue());
return h;
}
private static String toHex(byte[] buffer) {
StringBuffer hexString = new StringBuffer();
for (int idx = 0; idx < buffer.length; ++idx) {
String hex = Integer.toHexString(0xff & buffer[idx]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
static String normalizeFloat(double f) {
// Early out for zero.
if (f == 0.0) {
return "+0:";
}
StringBuffer sb = new StringBuffer();
// Sign
sb.append(f < 0.0 ? '-' : '+');
if (f < 0.0) f = -f;
// Exponent
int e = 0;
while (f > 1) {
f /= 2;
e += 1;
}
while (f < 0.5) {
f *= 2;
e -= 1;
}
sb.append(e);
sb.append(':');
// Mantissa
if (f > 1 || f <= 0.5) {
throw new IllegalStateException("wrong range for mantissa");
}
while (f != 0) {
if (f >= 1) {
sb.append('1');
f -= 1;
} else {
sb.append('0');
}
if (f >= 1) {
throw new IllegalStateException("oops, f is too big");
}
if (sb.length() > 1000) {
throw new IllegalStateException("things have got out of hand");
}
f *= 2;
}
return sb.toString();
}
private void hashAny(Object obj) throws NoSuchAlgorithmException,
JSONException {
digester.reset();
JsonType outerType = getType(obj);
switch (outerType) {
case ARRAY: {
hashList((JSONArray) obj);
break;
}
case OBJECT: {
hashObject((JSONObject) obj);
break;
}
case INT: {
hashDouble(((Integer) obj).doubleValue());
break;
}
case LONG: {
hashDouble(((Long) obj).doubleValue());
break;
}
case STRING: {
hashString((String) obj);
break;
}
case NULL: {
hashNull();
break;
}
case BOOLEAN: {
hashBoolean((Boolean) obj);
break;
}
case FLOAT: {
hashDouble((Double) obj);
break;
}
case REDACTED: {
hash = Redacted.fromString((String) obj).hash();
break;
}
default: {
throw new IllegalArgumentException("Illegal type in JSON: "
+ obj.getClass());
}
}
}
private void hashTaggedBytes(char tag, byte[] bytes) {
digester.reset();
digester.update((byte) tag);
digester.update(bytes);
hash = digester.digest();
}
private void hashString(String str) {
hashTaggedBytes('u', str.getBytes());
}
private void hashInteger(Object value) {
String str = value.toString();
hashTaggedBytes('i', str.getBytes());
}
private void hashDouble(Double value) {
String normalized = normalizeFloat(value);
hashTaggedBytes('f', normalized.getBytes());
}
private void hashNull() {
hashTaggedBytes('n', "".getBytes());
}
private void hashBoolean(boolean bool) {
hashTaggedBytes('b', (bool ? "1" : "0").getBytes());
}
private void hashList(JSONArray list) throws NoSuchAlgorithmException,
JSONException {
digester.reset();
digester.update((byte) ('l'));
for (int n = 0; n < list.length(); ++n) {
ObjectHash innerObject = new ObjectHash();
innerObject.hashAny(list.get(n));
digester.update(innerObject.hash());
}
hash = digester.digest();
}
private String debugString(Iterable<ByteBuffer> buffers) {
StringBuilder sb = new StringBuilder();
for (ByteBuffer buff : buffers) {
sb.append('\n');
sb.append(toHex(buff.array()));
}
return sb.toString();
}
private void hashObject(JSONObject obj) throws NoSuchAlgorithmException,
JSONException {
List<ByteBuffer> buffers = new ArrayList<>();
Comparator<ByteBuffer> ordering = new Comparator<ByteBuffer>() {
@Override
public int compare(ByteBuffer left, ByteBuffer right) {
return toHex(left.array()).compareTo(toHex(right.array()));
}
};
Iterator keys = obj.keys();
while (keys.hasNext()) {
ByteBuffer buff = ByteBuffer.allocate(2 * SHA256_BLOCK_SIZE);
String key = (String) keys.next();
// TODO(phad): would be nice to chain all these calls builder-stylee.
ObjectHash hKey = new ObjectHash();
hKey.hashString(key);
ObjectHash hVal = new ObjectHash();
hVal.hashAny(obj.get(key));
buff.put(hKey.hash());
buff.put(hVal.hash());
buffers.add(buff);
}
buffers.sort(ordering);
digester.reset();
digester.update((byte) 'd');
for (ByteBuffer buff : buffers) {
digester.update(buff.array());
}
hash = digester.digest();
}
@Override
public String toString() {
return this.toHex();
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null) return false;
if (this.getClass() != other.getClass()) return false;
return this.toHex().equals(((ObjectHash) other).toHex());
}
@Override
public int compareTo(ObjectHash other) {
return toHex().compareTo(other.toHex());
}
public byte[] hash() {
return hash;
}
public String toHex() {
return toHex(hash);
}
private enum JsonType {
BOOLEAN,
ARRAY,
OBJECT,
INT,
LONG,
FLOAT,
STRING,
NULL,
UNKNOWN,
REDACTED,;
}
}