-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtilities.java
95 lines (90 loc) · 2.66 KB
/
Utilities.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
package com.senzing.g2.engine;
class Utilities {
/**
* Formats a <code>long</code> integer value as hexadecimal with spaces between each group of for
* hex digits.
*
* @param value The value to format.
* @return The value formatted as a {@link String}.
*/
public static String hexFormat(long value) {
StringBuilder sb = new StringBuilder(20);
long mask = 0xFFFF << 48;
String prefix = "";
for (int index = 0; index < 4; index++) {
long masked = value & mask;
mask = mask >>> 16;
masked = masked >>> ((3 - index) * 16);
sb.append(prefix);
String hex = Long.toUnsignedString(masked, 16);
for (int zero = hex.length(); zero < 4; zero++) {
sb.append("0");
}
sb.append(hex);
prefix = " ";
}
return sb.toString();
}
/**
* Escapes the specified {@link String} into a JSON string with the the surrounding double quotes.
* If the specified {@link String} is <code>null</code> then <code>"null"</code> is returned.
*
* @param string The {@link String} to escape for JSON.
* @return The quoted escaped {@link String} or <code>"null"</code> if the specified parameter is
* <code>null</code>.
*/
public static String jsonEscape(String string) {
if (string == null) return "null";
int escapeCount = 0;
for (int index = 0; index < string.length(); index++) {
char c = string.charAt(index);
escapeCount +=
switch (c) {
case '\b', '\f', '\n', '\r', '\t', '"', '\\':
yield 1;
default:
yield (c < ' ') ? 6 : 0;
};
}
if (escapeCount == 0) return "\"" + string + "\"";
StringBuilder sb = new StringBuilder(string.length() + escapeCount + 2);
sb.append('"');
for (int index = 0; index < string.length(); index++) {
char c = string.charAt(index);
switch (c) {
case '"', '\\':
sb.append('\\').append(c);
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
default:
if (c >= ' ') sb.append(c);
else {
sb.append("\\u00");
String hex = Integer.toHexString(c);
if (hex.length() == 1) {
sb.append("0"); // one more zero if single-digit hex
}
sb.append(hex);
}
}
;
}
sb.append('"');
// return the escaped string
return sb.toString();
}
}