Debian Codegraph @

src/org/eclipse/parsson/JsonPatchImpl.java

raw symbols SCIP
1 /*
2 * Copyright (c) 2015, 2023 Oracle and/or its affiliates. All rights reserved.
3 *
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v. 2.0, which is available at
6 * http://www.eclipse.org/legal/epl-2.0.
7 *
8 * This Source Code may also be made available under the following Secondary
9 * Licenses when the conditions for such availability set forth in the
10 * Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
11 * version 2 with the GNU Classpath Exception, which is available at
12 * https://www.gnu.org/software/classpath/license.html.
13 *
14 * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
15 */
16
17 package org.eclipse.parsson;
18
19 import jakarta.json.Json;
20 import jakarta.json.JsonArray;
21 import jakarta.json.JsonException;
22 import jakarta.json.JsonObject;
23 import jakarta.json.JsonPatch;
24 import jakarta.json.JsonPatchBuilder;
25 import jakarta.json.JsonPointer;
26 import jakarta.json.JsonString;
27 import jakarta.json.JsonStructure;
28 import jakarta.json.JsonValue;
29 import jakarta.json.JsonValue.ValueType;
30
31 /**
32 * This class is an immutable representation of a JSON Patch as specified in
33 * <a href="http://tools.ietf.org/html/rfc6902">RFC 6902</a>.
34 * <p>A {@code JsonPatch} can be instantiated with {@link Json#createPatch(JsonArray)}
35 * by specifying the patch operations in a JSON Patch. Alternately, it
36 * can also be constructed with a {@link JsonPatchBuilder}.
37 * </p>
38 * The following illustrates both approaches.
39 * <p>1. Construct a JsonPatch with a JSON Patch.
40 * <pre>{@code
41 * JsonArray contacts = ... // The target to be patched
42 * JsonArray patch = ... ; // JSON Patch
43 * JsonPatch jsonpatch = Json.createPatch(patch);
44 * JsonArray result = jsonpatch.apply(contacts);
45 * } </pre>
46 * 2. Construct a JsonPatch with JsonPatchBuilder.
47 * <pre>{@code
48 * JsonPatchBuilder builder = Json.createPatchBuilder();
49 * JsonArray result = builder.add("/John/phones/office", "1234-567")
50 * .remove("/Amy/age")
51 * .build()
52 * .apply(contacts);
53 * } </pre>
54 *
55 * @since 1.1
56 */
57 public class JsonPatchImpl implements JsonPatch {
58
59 private final JsonArray patch;
60 private final JsonContext jsonContext;
61
62 /**
63 * Constructs a JsonPatchImpl
64 * @param patch the JSON Patch
65 */
66 public JsonPatchImpl(JsonArray patch, JsonContext jsonContext) {
67 this.patch = patch;
68 this.jsonContext = jsonContext;
69 }
70
71 /**
72 * Compares this {@code JsonPatchImpl} with another object.
73 * @param obj the object to compare this {@code JsonPatchImpl} against
74 * @return true if the given object is a {@code JsonPatchImpl} with the same
75 * reference tokens as this one, false otherwise.
76 */
77 @Override
78 public boolean equals(Object obj) {
79 if (this == obj)
80 return true;
81 if (obj == null || obj.getClass() != JsonPatchImpl.class)
82 return false;
83 return patch.equals(((JsonPatchImpl)obj).patch);
84 }
85
86 /**
87 * Returns the hash code value for this {@code JsonPatchImpl}.
88 *
89 * @return the hash code value for this {@code JsonPatchImpl} object
90 */
91 @Override
92 public int hashCode() {
93 return patch.hashCode();
94 }
95
96 /**
97 * Returns the JSON Patch text
98 * @return the JSON Patch text
99 */
100 @Override
101 public String toString() {
102 return patch.toString();
103 }
104
105 /**
106 * Applies the patch operations to the specified {@code target}.
107 * The target is not modified by the patch.
108 *
109 * @param target the target to apply the patch operations
110 * @return the transformed target after the patch
111 * @throws JsonException if the supplied JSON Patch is malformed or if
112 * it contains references to non-existing members
113 */
114 @Override
115 public JsonStructure apply(JsonStructure target) {
116
117 JsonStructure result = target;
118
119 for (JsonValue operation: patch) {
120 if (operation.getValueType() != ValueType.OBJECT) {
121 throw new JsonException(JsonMessages.PATCH_MUST_BE_ARRAY());
122 }
123 result = apply(result, (JsonObject) operation);
124 }
125 return result;
126 }
127
128 @Override
129 public JsonArray toJsonArray() {
130 return patch;
131 }
132
133 /**
134 * Generates a JSON Patch from the source and target {@code JsonStructure}.
135 * The generated JSON Patch need not be unique.
136 * @param source the source
137 * @param target the target, must be the same type as the source
138 * @return a JSON Patch which when applied to the source, yields the target
139 */
140 static JsonArray diff(JsonStructure source, JsonStructure target, JsonContext jsonContext) {
141 return (new DiffGenerator(jsonContext)).diff(source, target);
142 }
143
144 /**
145 * Applies a JSON Patch operation to the target.
146 * @param target the target to apply the operation
147 * @param operation the JSON Patch operation
148 * @return the target after the patch
149 */
150 private JsonStructure apply(JsonStructure target, JsonObject operation) {
151
152 JsonPointer pointer = getPointer(operation, "path");
153 JsonPointer from;
154 JsonString op = operation.getJsonString("op");
155 if (op == null) {
156 throw new JsonException(JsonMessages.PATCH_OPERATION_MISSING());
157 }
158 switch (Operation.fromOperationName(op.getString())) {
159 case ADD:
160 return pointer.add(target, getValue(operation));
161 case REPLACE:
162 return pointer.replace(target, getValue(operation));
163 case REMOVE:
164 return pointer.remove(target);
165 case COPY:
166 from = getPointer(operation, "from");
167 return pointer.add(target, from.getValue(target));
168 case MOVE:
169 // Check if from is a proper prefix of path
170 String dest = operation.getString("path");
171 String src = operation.getString("from");
172 if (dest.startsWith(src) && src.length() < dest.length()) {
173 throw new JsonException(JsonMessages.PATCH_MOVE_PROPER_PREFIX(src, dest));
174 }
175 from = getPointer(operation, "from");
176 // Check if 'from' exists in target object
177 if (!from.containsValue(target)) {
178 throw new JsonException(JsonMessages.PATCH_MOVE_TARGET_NULL(src));
179 }
180 if (pointer.equals(from)) {
181 // nop
182 return target;
183 }
184 return pointer.add(from.remove(target), from.getValue(target));
185 case TEST:
186 if (! getValue(operation).equals(pointer.getValue(target))) {
187 throw new JsonException(JsonMessages.PATCH_TEST_FAILED(operation.getString("path"), getValue(operation).toString()));
188 }
189 return target;
190 default:
191 throw new JsonException(JsonMessages.PATCH_ILLEGAL_OPERATION(operation.getString("op")));
192 }
193 }
194
195 private JsonPointer getPointer(JsonObject operation, String member) {
196 JsonString pointerString = operation.getJsonString(member);
197 if (pointerString == null) {
198 missingMember(operation.getString("op"), member);
199 }
200 return new JsonPointerImpl(pointerString.getString(), jsonContext);
201 }
202
203 private JsonValue getValue(JsonObject operation) {
204 JsonValue value = operation.get("value");
205 if (value == null) {
206 missingMember(operation.getString("op"), "value");
207 }
208 return value;
209 }
210
211 private void missingMember(String op, String member) {
212 throw new JsonException(JsonMessages.PATCH_MEMBER_MISSING(op, member));
213 }
214
215 static class DiffGenerator {
216 private JsonPatchBuilder builder;
217 private final JsonContext jsonContext;
218
219 DiffGenerator(JsonContext jsonContext) {
220 this.jsonContext = jsonContext;
221 }
222
223 JsonArray diff(JsonStructure source, JsonStructure target) {
224 builder = new JsonPatchBuilderImpl(jsonContext);
225 diff("", source, target);
226 return builder.build().toJsonArray();
227 }
228
229 private void diff(String path, JsonValue source, JsonValue target) {
230 if (source.equals(target)) {
231 return;
232 }
233 ValueType s = source.getValueType();
234 ValueType t = target.getValueType();
235 if (s == ValueType.OBJECT && t == ValueType.OBJECT) {
236 diffObject(path, (JsonObject) source, (JsonObject) target);
237 } else if (s == ValueType.ARRAY && t == ValueType.ARRAY) {
238 diffArray(path, (JsonArray) source, (JsonArray) target);
239 } else {
240 builder.replace(path, target);
241 }
242 }
243
244 private void diffObject(String path, JsonObject source, JsonObject target) {
245 source.forEach((key, value) -> {
246 if (target.containsKey(key)) {
247 diff(path + '/' + Json.encodePointer(key), value, target.get(key));
248 } else {
249 builder.remove(path + '/' + Json.encodePointer(key));
250 }
251 });
252 target.forEach((key, value) -> {
253 if (! source.containsKey(key)) {
254 builder.add(path + '/' + Json.encodePointer(key), value);
255 }
256 });
257 }
258
259 /*
260 * For array element diff, find the longest common subsequence, per
261 * http://en.wikipedia.org/wiki/Longest_common_subsequence_problem .
262 * We modify the algorithm to generate a replace if possible.
263 */
264 private void diffArray(String path, JsonArray source, JsonArray target) {
265 /* The array c keeps track of length of the subsequence. To avoid
266 * computing the equality of array elements again, we
267 * left shift its value by 1, and use the low order bit to mark
268 * that two items are equal.
269 */
270 int m = source.size();
271 int n = target.size();
272 int [][] c = new int[m+1][n+1];
273 for (int i = 0; i < m+1; i++)
274 c[i][0] = 0;
275 for (int i = 0; i < n+1; i++)
276 c[0][i] = 0;
277 for (int i = 0; i < m; i++) {
278 for (int j = 0; j < n; j++) {
279 if (source.get(i).equals(target.get(j))) {
280 c[i+1][j+1] = ((c[i][j]) & ~1) + 3;
281 // 3 = (1 << 1) | 1;
282 } else {
283 c[i+1][j+1] = Math.max(c[i+1][j], c[i][j+1]) & ~1;
284 }
285 }
286 }
287
288 emit(path, source, target, c, m, n);
289 }
290
291 private void emit(final String path,
292 final JsonArray source,
293 final JsonArray target,
294 final int[][] c,
295 final int i,
296 final int j) {
297 if (i == 0) {
298 if (j > 0) {
299 emit(path, source, target, c, i, j - 1);
300 builder.add(path + '/' + (j - 1), target.get(j - 1));
301 }
302 } else if (j == 0) {
303 if (i > 0) {
304 builder.remove(path + '/' + (i - 1));
305 emit(path, source, target, c, i - 1, j);
306 }
307 } else if ((c[i][j] & 1) == 1) {
308 emit(path, source, target, c, i - 1, j - 1);
309 } else {
310 final int f = c[i][j-1] >> 1;
311 final int g = c[i-1][j] >> 1;
312 if (f > g) {
313 emit(path, source, target, c, i, j - 1);
314 builder.add(path + '/' + (j - 1), target.get(j - 1));
315 } else if (f < g) {
316 builder.remove(path + '/' + (i - 1));
317 emit(path, source, target, c, i - 1, j);
318 } else { // f == g) {
319 diff(path + '/' + (i - 1), source.get(i - 1),
320 target.get(j - 1));
321 emit(path, source, target, c, i - 1, j - 1);
322 }
323 }
324 }
325 }
326 }
327