2828import com .github .fge .jackson .NodeType ;
2929import com .github .fge .jackson .jsonpointer .JsonPointer ;
3030import com .github .fge .jsonpatch .JsonPatch ;
31+ import com .github .fge .jsonpatch .JsonPatchMessages ;
32+ import com .github .fge .msgsimple .bundle .MessageBundle ;
33+ import com .github .fge .msgsimple .load .MessageBundles ;
3134import com .google .common .annotations .VisibleForTesting ;
3235import com .google .common .base .Equivalence ;
3336import com .google .common .collect .Maps ;
5053 * patch for any other source/target combination than the one used to generate
5154 * the patch.</p>
5255 *
56+ * <p>This class always performs operations in the following order: removals,
57+ * additions and replacements. It then factors removal/addition pairs into
58+ * move operations, or copy operations if a common element exists, at the same
59+ * {@link JsonPointer pointer}, in both the source and destination.</p>
60+ *
61+ * <p>You can obtain a diff either as a {@link JsonPatch} directly or, for
62+ * backwards compatibility, as a {@link JsonNode}.</p>
63+ *
5364 * @since 1.2
5465 */
5566@ ParametersAreNonnullByDefault
5667public final class JsonDiff
5768{
69+ private static final MessageBundle BUNDLE
70+ = MessageBundles .getBundle (JsonPatchMessages .class );
5871 private static final ObjectMapper MAPPER = JacksonUtils .newMapper ();
5972
6073 private static final Equivalence <JsonNode > EQUIVALENCE
@@ -77,6 +90,8 @@ private JsonDiff()
7790 public static JsonPatch asJsonPatch (final JsonNode source ,
7891 final JsonNode target )
7992 {
93+ BUNDLE .checkNotNull (source , "common.nullArgument" );
94+ BUNDLE .checkNotNull (target , "common.nullArgument" );
8095 final Map <JsonPointer , JsonNode > unchanged
8196 = getUnchangedValues (source , target );
8297 final DiffProcessor processor = new DiffProcessor (unchanged );
@@ -172,17 +187,17 @@ private static void generateArrayDiffs(final DiffProcessor processor,
172187 final int secondSize = target .size ();
173188 final int size = Math .min (firstSize , secondSize );
174189
175- for (int index = 0 ; index < size ; index ++)
176- generateDiffs (processor , pointer .append (index ), source .get (index ),
177- target .get (index ));
178-
179190 /*
180191 * Source array is larger; in this case, elements are removed from the
181192 * target; the index of removal is always the original arrays's length.
182193 */
183194 for (int index = size ; index < firstSize ; index ++)
184195 processor .valueRemoved (pointer .append (size ), source .get (index ));
185196
197+ for (int index = 0 ; index < size ; index ++)
198+ generateDiffs (processor , pointer .append (index ), source .get (index ),
199+ target .get (index ));
200+
186201 // Deal with the destination array being larger...
187202 for (int index = size ; index < secondSize ; index ++)
188203 processor .valueAdded (pointer .append ("-" ), target .get (index ));
0 commit comments