forked from AlmostReliable/almostunified
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonCompare.java
347 lines (287 loc) · 13.3 KB
/
JsonCompare.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package com.almostreliable.unified.utils;
import com.almostreliable.unified.unification.recipe.RecipeLink;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public final class JsonCompare {
private static final Set<String> SANITIZE_KEYS = Set.of("item", "tag", "id");
private JsonCompare() {}
public static int compare(JsonObject first, JsonObject second, Map<String, Rule> rules) {
for (var entry : rules.entrySet()) {
JsonElement fElement = first.get(entry.getKey());
JsonElement sElement = second.get(entry.getKey());
if (fElement == null && sElement == null) {
continue;
}
int compareIndex = entry.getValue().compare(fElement, sElement);
if (compareIndex != 0) {
return compareIndex;
}
}
return 0;
}
public static JsonObject compare(Map<String, Rule> rules, JsonObject... jsonObjects) {
List<JsonObject> unsorted = Arrays.asList(jsonObjects);
unsorted.sort((f, s) -> compare(f, s, rules));
return unsorted.get(0);
}
@Nullable
public static JsonObject compareShaped(JsonObject first, JsonObject second, CompareContext compareContext) {
if (!matches(first, second, compareContext)) return null;
JsonArray firstPattern = JsonUtils.arrayOrSelf(first.get("pattern"));
JsonArray secondPattern = JsonUtils.arrayOrSelf(second.get("pattern"));
if (firstPattern.size() != secondPattern.size()) {
return null;
}
for (int i = 0; i < firstPattern.size(); i++) {
if (JsonUtils.stringOrSelf(firstPattern.get(i)).length() !=
JsonUtils.stringOrSelf(secondPattern.get(i)).length()) {
return null;
}
}
var firstKeyMap = createShapedKeyMap(first);
var secondKeyMap = createShapedKeyMap(second);
for (int i = 0; i < firstPattern.size(); i++) {
String firstPatternString = JsonUtils.stringOrSelf(firstPattern.get(i));
String secondPatternString = JsonUtils.stringOrSelf(secondPattern.get(i));
for (int j = 0; j < firstPatternString.length(); j++) {
char firstChar = firstPatternString.charAt(j);
char secondChar = secondPatternString.charAt(j);
if (firstChar == ' ' && secondChar == ' ') continue;
if (!firstKeyMap.containsKey(firstChar) || !secondKeyMap.containsKey(secondChar)) {
return null;
}
if (!firstKeyMap.get(firstChar).equals(secondKeyMap.get(secondChar))) {
return null;
}
}
}
return first;
}
private static Map<Character, JsonObject> createShapedKeyMap(JsonObject json) {
JsonObject keys = JsonUtils.objectOrSelf(json.get("key"));
Map<Character, JsonObject> keyMap = new HashMap<>();
for (Map.Entry<String, JsonElement> patterKey : keys.entrySet()) {
char c = patterKey.getKey().charAt(0);
if (c == ' ') continue;
keyMap.put(c, JsonUtils.objectOrSelf(patterKey.getValue()));
}
return keyMap;
}
public static boolean matches(JsonObject first, JsonObject second, CompareContext compareContext) {
CompareSettings compareSettings = compareContext.settings;
if (!compareSettings.hasIgnoredFields() && first.size() != second.size()) {
return false;
}
for (String field : compareContext.compareFields()) {
JsonElement secondElem = second.get(field);
if (secondElem == null) return false;
JsonElement firstElem = first.get(field);
// sanitize elements for implicit counts of 1
if (compareSettings.handleImplicitCounts && needsSanitizing(firstElem, secondElem)) {
firstElem = sanitize(firstElem);
secondElem = sanitize(secondElem);
}
if (!firstElem.equals(secondElem)) {
return false;
}
}
return true;
}
/**
* A check whether the given elements need to be sanitized. The purpose of this check is
* to save performance by skipping pairs that are not affected by sanitizing.
* <p>
* Conditions are both elements being a JSON array with the same size, both elements being
* a JSON object, one element being a JSON object and the other being a JSON primitive.
*
* @param firstElem the first element
* @param secondElem the second element
* @return true if the elements need to be sanitized, false otherwise
*/
private static boolean needsSanitizing(JsonElement firstElem, JsonElement secondElem) {
return (firstElem instanceof JsonArray firstArray && secondElem instanceof JsonArray secondArray &&
firstArray.size() == secondArray.size()) ||
(firstElem instanceof JsonObject && secondElem instanceof JsonObject) ||
(firstElem instanceof JsonPrimitive && secondElem instanceof JsonObject) ||
(firstElem instanceof JsonObject && secondElem instanceof JsonPrimitive);
}
/**
* Creates a sanitized object from the given element with a count of 1 and the
* value from the original object under a dummy key called "au_sanitized".
* <p>
* If the element is not a string primitive, the default object is returned.
*
* @param value The value to sanitize
* @param defaultValue The default value to return if the element is not a string primitive
* @return The sanitized object or the default value
*/
private static JsonElement createSanitizedObjectOrDefault(JsonElement value, JsonElement defaultValue) {
if (value instanceof JsonPrimitive primitive && primitive.isString()) {
var newObject = new JsonObject();
newObject.addProperty("au_sanitized", primitive.getAsString());
newObject.addProperty("count", 1);
return newObject;
}
return defaultValue;
}
/**
* Used to sanitize root level JSON elements to make them comparable when the count of 1 is implicit.
* <p>
* This transforms string primitives, JSON objects and JSON arrays to JSON objects where the
* count of 1 is explicitly set. The transformation is only applied to a dummy object and not to
* the original recipe, so it can be safely used for comparison.
* <p>
* If the object doesn't support this transformation, the original object is returned.
*
* @param element The element to sanitize
* @return The sanitized element or the original element if it can't be sanitized
*/
@SuppressWarnings("ChainOfInstanceofChecks")
private static JsonElement sanitize(JsonElement element) {
if (element instanceof JsonArray jsonArray) {
JsonArray newArray = new JsonArray();
for (JsonElement arrayElement : jsonArray) {
newArray.add(sanitize(arrayElement));
}
return newArray;
}
if (element instanceof JsonObject jsonObject) {
var keySet = jsonObject.keySet();
if (keySet.stream().filter(SANITIZE_KEYS::contains).count() != 1) {
return element;
}
// if it has a count property, it needs to be 1, otherwise it's implicit 1 as well and needs sanitizing
if (keySet.contains("count") && JsonQuery.of(jsonObject, "count").asInt().filter(i -> i == 1).isEmpty()) {
return element;
}
var key = keySet.stream().filter(SANITIZE_KEYS::contains).findFirst().orElseThrow();
var sanitized = createSanitizedObjectOrDefault(jsonObject.get(key), jsonObject);
// ensure the object changed (was sanitized) and that we got a JsonObject
// noinspection ObjectEquality
if (sanitized == jsonObject || !(sanitized instanceof JsonObject sanitizedObject)) {
return jsonObject;
}
mergeRemainingProperties(jsonObject, sanitizedObject);
return sanitizedObject;
}
return createSanitizedObjectOrDefault(element, element);
}
/**
* Merges remaining properties from the original object to the sanitized object.
*
* @param jsonObject The original object
* @param sanitizedObject The sanitized object
*/
private static void mergeRemainingProperties(JsonObject jsonObject, JsonObject sanitizedObject) {
for (var entry : jsonObject.entrySet()) {
if (!SANITIZE_KEYS.contains(entry.getKey()) && !entry.getKey().equals("count")) {
sanitizedObject.add(entry.getKey(), entry.getValue());
}
}
}
public interface Rule {
/**
* Compare two JsonElements. The caller must ensure that at least one element is not null.
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
int compare(@Nullable JsonElement first, @Nullable JsonElement second);
String getName();
}
public static class LowerRule implements Rule {
public static final String NAME = "LowerRule";
@Override
public int compare(@Nullable JsonElement first, @Nullable JsonElement second) {
double firstValue = first instanceof JsonPrimitive fp ? fp.getAsDouble() : 0;
double secondValue = second instanceof JsonPrimitive sp ? sp.getAsDouble() : 0;
return Double.compare(firstValue, secondValue);
}
@Override
public String getName() {
return NAME;
}
}
public static class HigherRule implements Rule {
public static final String NAME = "HigherRule";
@Override
public int compare(@Nullable JsonElement first, @Nullable JsonElement second) {
double firstValue = first instanceof JsonPrimitive fp ? fp.getAsDouble() : 0;
double secondValue = second instanceof JsonPrimitive sp ? sp.getAsDouble() : 0;
return Double.compare(secondValue, firstValue);
}
@Override
public String getName() {
return NAME;
}
}
public record CompareContext(CompareSettings settings, List<String> compareFields) {
public static CompareContext create(CompareSettings settings, RecipeLink curRecipe) {
Set<String> compareFields = curRecipe.getActual().keySet();
if (!settings.ignoredFields.isEmpty()) {
compareFields = new HashSet<>(compareFields);
compareFields.removeAll(settings.ignoredFields);
}
return new CompareContext(settings, List.copyOf(compareFields));
}
}
public static class CompareSettings {
public static final String IGNORED_FIELDS = "ignored_fields";
public static final String RULES = "rules";
public static final String HANDLE_IMPLICIT_COUNTS = "handle_implicit_counts";
private final LinkedHashMap<String, Rule> rules = new LinkedHashMap<>();
private final Set<String> ignoredFields = new HashSet<>();
private boolean handleImplicitCounts;
public void ignoreField(String property) {
ignoredFields.add(property);
}
public void addRule(String key, Rule rule) {
Rule old = rules.put(key, rule);
ignoreField(key);
if (old != null) {
throw new IllegalStateException("multiple rules for key <" + key + "> found");
}
}
public boolean hasIgnoredFields() {
return !ignoredFields.isEmpty();
}
public JsonObject serialize() {
JsonObject result = new JsonObject();
JsonArray ignoredFieldsArray = new JsonArray();
ignoredFields.stream().filter(f -> !rules.containsKey(f)).forEach(ignoredFieldsArray::add);
result.add(IGNORED_FIELDS, ignoredFieldsArray);
JsonObject rulesJson = new JsonObject();
rules.forEach((s, rule) -> {
rulesJson.addProperty(s, rule.getName());
});
result.add(RULES, rulesJson);
result.addProperty(HANDLE_IMPLICIT_COUNTS, handleImplicitCounts);
return result;
}
public void deserialize(JsonObject json) {
json.getAsJsonArray(IGNORED_FIELDS).forEach(e -> {
ignoreField(e.getAsString());
});
json.getAsJsonObject(RULES).entrySet().forEach(e -> {
Rule r = switch (e.getValue().getAsString()) {
case HigherRule.NAME -> new HigherRule();
case LowerRule.NAME -> new LowerRule();
default -> throw new IllegalArgumentException("unknown rule <" + e.getValue().getAsString() + ">");
};
addRule(e.getKey(), r);
});
handleImplicitCounts = json.getAsJsonPrimitive(HANDLE_IMPLICIT_COUNTS).getAsBoolean();
}
public Map<String, Rule> getRules() {
return rules;
}
}
}