├── .github
└── workflows
│ ├── publish.yml
│ └── test.yml
├── .gitignore
├── LICENSE
├── README.md
├── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
├── main
└── java
│ └── com
│ └── deblock
│ └── jsondiff
│ ├── DiffGenerator.java
│ ├── diff
│ ├── JsonArrayDiff.java
│ ├── JsonDiff.java
│ ├── JsonObjectDiff.java
│ ├── MatchedPrimaryDiff.java
│ └── UnMatchedPrimaryDiff.java
│ ├── matcher
│ ├── CompositeJsonMatcher.java
│ ├── JsonMatcher.java
│ ├── LenientJsonArrayPartialMatcher.java
│ ├── LenientJsonObjectPartialMatcher.java
│ ├── LenientNumberPrimitivePartialMatcher.java
│ ├── PartialJsonMatcher.java
│ ├── Path.java
│ ├── StrictJsonArrayPartialMatcher.java
│ ├── StrictJsonObjectPartialMatcher.java
│ └── StrictPrimitivePartialMatcher.java
│ └── viewer
│ ├── JsonDiffViewer.java
│ ├── OnlyErrorDiffViewer.java
│ └── PatchDiffViewer.java
└── test
└── java
└── com
└── deblock
└── jsondiff
├── DiffGeneratorTest.java
├── Sample.java
├── matcher
├── CompositeJsonMatcherTest.java
├── JsonDiffAsserter.java
├── LenientJsonArrayPartialMatcherTest.java
├── LenientJsonObjectPartialMatcherTest.java
├── LenientNumberPrimitivePartialMatcherTest.java
├── PathTest.java
├── StrictJsonArrayPartialMatcherTest.java
├── StrictJsonObjectPartialMatcherTest.java
└── StrictPrimitivePartialMatcherTest.java
└── viewer
├── OnlyErrorDiffViewerTest.java
├── PatchDiffViewerTest.java
├── actual.json
├── expected.json
├── lenientDiff.patch
└── strictDiff.patch
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | name: Publish to OSS Sonatype
2 |
3 | on:
4 | release:
5 | types: [ created ]
6 |
7 | jobs:
8 | publish:
9 |
10 | runs-on: ubuntu-latest
11 | permissions:
12 | contents: read
13 | packages: write
14 |
15 | steps:
16 | - uses: actions/checkout@v3
17 | - name: Set up JDK 11
18 | uses: actions/setup-java@v3
19 | with:
20 | java-version: '11'
21 | distribution: 'temurin'
22 | server-id: github
23 | settings-path: ${{ github.workspace }}
24 | - name: Setup Gradle
25 | uses: gradle/gradle-build-action@v2
26 |
27 | - name: Build with Gradle
28 | uses: gradle/gradle-build-action@67421db6bd0bf253fb4bd25b31ebb98943c375e1
29 | with:
30 | arguments: build
31 |
32 | - name: Publish to maven central
33 | uses: gradle/gradle-build-action@67421db6bd0bf253fb4bd25b31ebb98943c375e1
34 | with:
35 | arguments: publishToSonatype closeAndReleaseSonatypeStagingRepository
36 | env:
37 | ORG_GRADLE_PROJECT_sonatypeUsername: ${{ secrets.SONATYPE_USERNAME }}
38 | ORG_GRADLE_PROJECT_sonatypePassword: ${{ secrets.SONATYPE_PASSWORD }}
39 | ORG_GRADLE_PROJECT_signingKey: ${{ secrets.GPG_PRIVATE_KEY }}
40 | ORG_GRADLE_PROJECT_signingPassword: ${{ secrets.SIGNING_PASSWORD }}
41 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: Test
2 |
3 | on:
4 | pull_request:
5 |
6 | permissions:
7 | contents: read
8 |
9 | jobs:
10 | unit_test:
11 |
12 | runs-on: ubuntu-latest
13 |
14 | steps:
15 | - uses: actions/checkout@v3
16 | - name: Set up JDK 11
17 | uses: actions/setup-java@v3
18 | with:
19 | java-version: '11'
20 | distribution: 'temurin'
21 | - name: Setup gradle
22 | uses: gradle/gradle-build-action@67421db6bd0bf253fb4bd25b31ebb98943c375e1
23 | - name: Build with Gradle
24 | uses: gradle/gradle-build-action@67421db6bd0bf253fb4bd25b31ebb98943c375e1
25 | with:
26 | arguments: build
27 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | target
3 | *.iml
4 | build
5 | .gradle
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Java json-diff
2 |
3 | A customizable lib to perform a json-diff
4 |
5 | ## Why Use json-diff library
6 |
7 | The goal of this library is to provide a readable diff between two json file.
8 |
9 | In addition to the differential, a similarity score is calculated.
10 | This score can be used to compare several json with each other and find the two most similar.
11 |
12 | The way to compare json is completely customisable.
13 |
14 | 2 way to display diff are provided by default (patch file, text file). And you can easily create your own formatter.
15 |
16 | ## Installation
17 |
18 | maven:
19 | ```xml
20 |
21 | io.github.deblockt
22 | json-diff
23 | 0.1.0
24 |
25 | ```
26 |
27 | gradle:
28 | ```gradle
29 | implementation 'io.github.deblockt:json-diff:0.1.0'
30 | ```
31 |
32 | ## Usage
33 |
34 | example:
35 | ```java
36 | final var expectedJson = "{\"additionalProperty\":\"a\", \"foo\": \"bar\", \"bar\": \"bar\", \"numberMatch\": 10.0, \"numberUnmatched\": 10.01, \"arrayMatch\": [{\"b\":\"a\"}], \"arrayUnmatched\": [{\"b\":\"a\"}]}";
37 | final var receivedJson = "{\"foo\": \"foo\", \"bar\": \"bar\", \"numberMatch\": 10, \"numberUnmatched\": 10.02, \"arrayMatch\": [{\"b\":\"a\"}], \"arrayUnmatched\": {\"b\":\"b\"}}";
38 |
39 | // define your matcher
40 | // CompositeJsonMatcher use other matcher to perform matching on objects, list or primitive
41 | final var jsonMatcher = new CompositeJsonMatcher(
42 | new LenientJsonArrayPartialMatcher(), // comparing array using lenient mode (ignore array order and extra items)
43 | new LenientJsonObjectPartialMatcher(), // comparing object using lenient mode (ignoring extra properties)
44 | new LenientNumberPrimitivePartialMatcher(new StrictPrimitivePartialMatcher()) // comparing primitive types and manage numbers (100.00 == 100)
45 | );
46 |
47 | // generate a diff
48 | final var jsondiff = DiffGenerator.diff(expectedJson, receivedJson, jsonMatcher);
49 |
50 | // use the viewer to collect diff data
51 | final var errorsResult= OnlyErrorDiffViewer.from(jsondiff);
52 |
53 | // print the diff result
54 | System.out.println(errorsResult);
55 | // print a similarity ratio between expected and received json (0 <= ratio <= 100)
56 | System.out.println(jsondiff.similarityRate());
57 | ```
58 | Result:
59 | ```
60 | The property "$.additionalProperty" is not found
61 | The property "$.numberUnmatched" didn't match. Expected 10.01, Received: 10.02
62 | The property "$.arrayUnmatched" didn't match. Expected [{"b":"a"}], Received: {"b":"b"}
63 | The property "$.foo" didn't match. Expected "bar", Received: "foo"
64 |
65 | 76.0
66 | ```
67 |
68 | You can also generate a patch file using this viewer:
69 | ```java
70 | final var patch = PatchDiffViewer.from(jsondiff);
71 |
72 | // use the viewer to collect diff data
73 | final var patchFile= PatchDiffViewer.from(jsondiff);
74 |
75 | // print the diff result
76 | System.out.println(patchFile);
77 | ```
78 |
79 | Result:
80 | ``` diff
81 | --- actual
82 | +++ expected
83 | @@ @@
84 | {
85 | + "additionalProperty": "a",
86 | "bar": "bar",
87 | - "numberUnmatched": 10.02,
88 | + "numberUnmatched": 10.01,
89 | - "arrayUnmatched": {"b":"b"},
90 | + "arrayUnmatched": [{"b":"a"}],
91 | - "foo": "foo",
92 | + "foo": "bar",
93 | "numberMatch": 10.0,
94 | "arrayMatch": [
95 | {
96 | "b": "a"
97 | }
98 | ]
99 | }
100 | ```
101 |
102 | ### Comparison mode
103 |
104 | You can use many comparison mode to compare you json:
105 |
106 | If you want compare json using *lenient* comparison:
107 | ```java
108 | final var fullLenient = new CompositeJsonMatcher(
109 | new LenientJsonArrayPartialMatcher(), // comparing array using lenient mode (ignore array order and extra items)
110 | new LenientJsonObjectPartialMatcher(), // comparing object using lenient mode (ignoring extra properties)
111 | new LenientNumberPrimitivePartialMatcher(new StrictPrimitivePartialMatcher()) // comparing primitive types and manage numbers (100.00 == 100)
112 | );
113 | ```
114 |
115 | If you want compare json using *strict* comparison:
116 | ```java
117 | final var strictMatcher = new CompositeJsonMatcher(
118 | new StrictJsonArrayPartialMatcher(), // comparing array using strict mode (object should have same properties/value)
119 | new StrictJsonObjectPartialMatcher(), // comparing object using strict mode (array should have same item on same orders)
120 | new StrictPrimitivePartialMatcher() // comparing primitive types (values should be strictly equals type and value)
121 | );
122 | ```
123 |
124 | You can mix matcher. For example, be lenient on array and strict on object:
125 | ```java
126 | final var matcher = new CompositeJsonMatcher(
127 | new LenientJsonArrayPartialMatcher(), // comparing array using lenient mode (ignore array order and extra items)
128 | new StrictJsonObjectPartialMatcher(), // comparing object using strict mode (array should have same item on same orders)
129 | new StrictPrimitivePartialMatcher() // comparing primitive types (values should be strictly equals type and value)
130 | );
131 | ```
132 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * This file was generated by the Gradle 'init' task.
3 | *
4 | * This project uses @Incubating APIs which are subject to change.
5 | */
6 |
7 | plugins {
8 | id 'io.github.gradle-nexus.publish-plugin' version '1.3.0'
9 | id 'me.qoomon.git-versioning' version '6.4.1'
10 | id 'java'
11 | id 'maven-publish'
12 | id 'signing'
13 | }
14 |
15 | repositories {
16 | mavenLocal()
17 | maven {
18 | url = uri('https://repo.maven.apache.org/maven2/')
19 | }
20 | }
21 |
22 | dependencies {
23 | implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2'
24 | testImplementation 'org.junit.jupiter:junit-jupiter:5.7.1'
25 | testImplementation 'org.mockito:mockito-core:3.8.0'
26 | }
27 |
28 | group = 'io.github.deblockt'
29 | description = 'json-diff'
30 | gitVersioning.apply {
31 | refs {
32 | branch('.+') {
33 | version = '${ref}-SNAPSHOT'
34 | }
35 | tag('(?.*)') {
36 | version = '${ref.version}'
37 | }
38 | }
39 |
40 | rev {
41 | version = '${commit}'
42 | }
43 | }
44 |
45 | repositories {
46 | mavenCentral()
47 | }
48 |
49 | java {
50 | withJavadocJar()
51 | withSourcesJar()
52 |
53 | sourceCompatibility = JavaLanguageVersion.of(11)
54 | targetCompatibility = JavaLanguageVersion.of(11)
55 | }
56 |
57 | test {
58 | useJUnitPlatform()
59 | }
60 |
61 | nexusPublishing {
62 | repositories {
63 | sonatype {
64 | nexusUrl.set(uri('https://s01.oss.sonatype.org/service/local/'))
65 | snapshotRepositoryUrl.set(uri('https://s01.oss.sonatype.org/content/repositories/snapshots/'))
66 | }
67 | }
68 | }
69 |
70 | publishing {
71 | publications {
72 | mavenJava(MavenPublication) {
73 | artifactId = 'json-diff'
74 | groupId = 'io.github.deblockt'
75 |
76 | from components.java
77 | pom {
78 | name = 'json-diff'
79 | description = 'A customizable lib to perform a json-diff'
80 | url = 'https://github.com/deblockt/json-diff'
81 |
82 | licenses {
83 | license {
84 | name = 'The Apache License, Version 2.0'
85 | url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
86 | }
87 | }
88 |
89 | developers {
90 | developer {
91 | id = 'deblockt'
92 | name = 'Thomas Deblock'
93 | email = 'deblock.thomas.62@gmail.com'
94 | url = 'https://github.com/deblockt'
95 | }
96 | }
97 |
98 | scm {
99 | connection = 'https://github.com/deblockt/json-diff.git'
100 | developerConnection = 'https://github.com/deblockt/json-diff.git'
101 | url = 'https://github.com/deblockt/json-diff'
102 | }
103 | }
104 | }
105 | }
106 |
107 | signing {
108 | def signingKey = findProperty("signingKey")
109 | def signingPassword = findProperty("signingPassword")
110 | if (signingKey !== null && signingPassword != null) {
111 | useInMemoryPgpKeys(signingKey, signingPassword)
112 | }
113 |
114 | sign publishing.publications.mavenJava
115 | }
116 | }
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/deblockt/json-diff/56a38af36423027e254c56a59903064bf5440535/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip
4 | networkTimeout=10000
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | # This is normally unused
84 | # shellcheck disable=SC2034
85 | APP_BASE_NAME=${0##*/}
86 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
147 | # shellcheck disable=SC3045
148 | MAX_FD=$( ulimit -H -n ) ||
149 | warn "Could not query maximum file descriptor limit"
150 | esac
151 | case $MAX_FD in #(
152 | '' | soft) :;; #(
153 | *)
154 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
155 | # shellcheck disable=SC3045
156 | ulimit -n "$MAX_FD" ||
157 | warn "Could not set maximum file descriptor limit to $MAX_FD"
158 | esac
159 | fi
160 |
161 | # Collect all arguments for the java command, stacking in reverse order:
162 | # * args from the command line
163 | # * the main class name
164 | # * -classpath
165 | # * -D...appname settings
166 | # * --module-path (only if needed)
167 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
168 |
169 | # For Cygwin or MSYS, switch paths to Windows format before running java
170 | if "$cygwin" || "$msys" ; then
171 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
172 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
173 |
174 | JAVACMD=$( cygpath --unix "$JAVACMD" )
175 |
176 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
177 | for arg do
178 | if
179 | case $arg in #(
180 | -*) false ;; # don't mess with options #(
181 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
182 | [ -e "$t" ] ;; #(
183 | *) false ;;
184 | esac
185 | then
186 | arg=$( cygpath --path --ignore --mixed "$arg" )
187 | fi
188 | # Roll the args list around exactly as many times as the number of
189 | # args, so each arg winds up back in the position where it started, but
190 | # possibly modified.
191 | #
192 | # NB: a `for` loop captures its iteration list before it begins, so
193 | # changing the positional parameters here affects neither the number of
194 | # iterations, nor the values presented in `arg`.
195 | shift # remove old arg
196 | set -- "$@" "$arg" # push replacement arg
197 | done
198 | fi
199 |
200 | # Collect all arguments for the java command;
201 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
202 | # shell script including quotes and variable substitutions, so put them in
203 | # double quotes to make sure that they get re-expanded; and
204 | # * put everything else in single quotes, so that it's not re-expanded.
205 |
206 | set -- \
207 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
208 | -classpath "$CLASSPATH" \
209 | org.gradle.wrapper.GradleWrapperMain \
210 | "$@"
211 |
212 | # Stop when "xargs" is not available.
213 | if ! command -v xargs >/dev/null 2>&1
214 | then
215 | die "xargs is not available"
216 | fi
217 |
218 | # Use "xargs" to parse quoted args.
219 | #
220 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
221 | #
222 | # In Bash we could simply go:
223 | #
224 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
225 | # set -- "${ARGS[@]}" "$@"
226 | #
227 | # but POSIX shell has neither arrays nor command substitution, so instead we
228 | # post-process each arg (as a line of input to sed) to backslash-escape any
229 | # character that might be a shell metacharacter, then use eval to reverse
230 | # that process (while maintaining the separation between arguments), and wrap
231 | # the whole thing up as a single "set" statement.
232 | #
233 | # This will of course break if any of these variables contains a newline or
234 | # an unmatched quote.
235 | #
236 |
237 | eval "set -- $(
238 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
239 | xargs -n1 |
240 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
241 | tr '\n' ' '
242 | )" '"$@"'
243 |
244 | exec "$JAVACMD" "$@"
245 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%"=="" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%"=="" set DIRNAME=.
29 | @rem This is normally unused
30 | set APP_BASE_NAME=%~n0
31 | set APP_HOME=%DIRNAME%
32 |
33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
35 |
36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
38 |
39 | @rem Find java.exe
40 | if defined JAVA_HOME goto findJavaFromJavaHome
41 |
42 | set JAVA_EXE=java.exe
43 | %JAVA_EXE% -version >NUL 2>&1
44 | if %ERRORLEVEL% equ 0 goto execute
45 |
46 | echo.
47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
48 | echo.
49 | echo Please set the JAVA_HOME variable in your environment to match the
50 | echo location of your Java installation.
51 |
52 | goto fail
53 |
54 | :findJavaFromJavaHome
55 | set JAVA_HOME=%JAVA_HOME:"=%
56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
57 |
58 | if exist "%JAVA_EXE%" goto execute
59 |
60 | echo.
61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
62 | echo.
63 | echo Please set the JAVA_HOME variable in your environment to match the
64 | echo location of your Java installation.
65 |
66 | goto fail
67 |
68 | :execute
69 | @rem Setup the command line
70 |
71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
72 |
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if %ERRORLEVEL% equ 0 goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | set EXIT_CODE=%ERRORLEVEL%
85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
87 | exit /b %EXIT_CODE%
88 |
89 | :mainEnd
90 | if "%OS%"=="Windows_NT" endlocal
91 |
92 | :omega
93 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * This file was generated by the Gradle 'init' task.
3 | *
4 | * This project uses @Incubating APIs which are subject to change.
5 | */
6 |
7 | rootProject.name = 'json-diff'
8 |
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/DiffGenerator.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff;
2 |
3 | import com.deblock.jsondiff.diff.JsonDiff;
4 | import com.deblock.jsondiff.matcher.JsonMatcher;
5 | import com.deblock.jsondiff.matcher.Path;
6 | import com.fasterxml.jackson.core.JsonProcessingException;
7 | import com.fasterxml.jackson.databind.JsonNode;
8 | import com.fasterxml.jackson.databind.ObjectMapper;
9 |
10 | import java.util.List;
11 | import java.util.stream.Collectors;
12 |
13 | public class DiffGenerator {
14 | private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
15 |
16 | public static JsonDiff diff(String expected, String actual, JsonMatcher jsonMatcher) {
17 | return jsonMatcher.diff(Path.ROOT, read(expected), read(actual));
18 | }
19 |
20 | public static List diff(String expected, List actualValues, JsonMatcher jsonMatcher) {
21 | final var expectedObject = read(expected);
22 | return actualValues.stream()
23 | .map(actual -> jsonMatcher.diff(Path.ROOT, expectedObject, read(actual)))
24 | .collect(Collectors.toList());
25 | }
26 |
27 | private static JsonNode read(String json) {
28 | try {
29 | return OBJECT_MAPPER.readTree(json);
30 | } catch (JsonProcessingException e) {
31 | throw new JsonReadException(e);
32 | }
33 | }
34 |
35 | public static class JsonReadException extends RuntimeException {
36 |
37 | public JsonReadException(Throwable e) {
38 | super(e);
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/diff/JsonArrayDiff.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.diff;
2 |
3 | import com.deblock.jsondiff.matcher.Path;
4 | import com.deblock.jsondiff.viewer.JsonDiffViewer;
5 | import com.fasterxml.jackson.databind.JsonNode;
6 |
7 | import java.util.HashMap;
8 | import java.util.Map;
9 |
10 | public class JsonArrayDiff implements JsonDiff {
11 | private final Map valuesWithoutMatch = new HashMap<>();
12 | private final Map valuesWithMatch = new HashMap<>();
13 | private final Map extraValues = new HashMap<>();
14 | private final Path path;
15 |
16 | public JsonArrayDiff(Path path) {
17 | this.path = path;
18 | }
19 |
20 | public void addNoMatch(int index, JsonNode expectedValue) {
21 | this.valuesWithoutMatch.put(index, expectedValue);
22 | }
23 |
24 | public void addDiff(int index, JsonDiff jsonDiff) {
25 | this.valuesWithMatch.put(index, jsonDiff);
26 | }
27 |
28 | public void addExtraItem(int index, JsonNode extraReceivedValue) {
29 | this.extraValues.put(index, extraReceivedValue);
30 | }
31 |
32 | @Override
33 | public double similarityRate() {
34 | final var totalArraySize = valuesWithoutMatch.size() + valuesWithMatch.size() + extraValues.size();
35 | if (totalArraySize == 0) {
36 | return 100.0;
37 | }
38 | final var totalSimilarityRate = valuesWithMatch.values().stream()
39 | .mapToDouble(JsonDiff::similarityRate)
40 | .sum();
41 |
42 | return totalSimilarityRate / totalArraySize;
43 | }
44 |
45 | @Override
46 | public void display(JsonDiffViewer viewer) {
47 | for (final var valuesWithMatch : valuesWithMatch.entrySet()) {
48 | if (valuesWithMatch.getValue().similarityRate() == 100) {
49 | viewer.matchingProperty(path().add(Path.PathItem.of(valuesWithMatch.getKey())), valuesWithMatch.getValue());
50 | } else {
51 | viewer.nonMatchingProperty(path().add(Path.PathItem.of(valuesWithMatch.getKey())), valuesWithMatch.getValue());
52 | }
53 | }
54 |
55 | for (final var valuesWithoutMatch : valuesWithoutMatch.entrySet()) {
56 | viewer.missingProperty(path().add(Path.PathItem.of(valuesWithoutMatch.getKey())), valuesWithoutMatch.getValue());
57 | }
58 |
59 | for (final var extraItem: extraValues.entrySet()) {
60 | viewer.extraProperty(path().add(Path.PathItem.of(extraItem.getKey())), extraItem.getValue());
61 | }
62 | }
63 |
64 | @Override
65 | public Path path() {
66 | return this.path;
67 | }
68 | }
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/diff/JsonDiff.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.diff;
2 |
3 | import com.deblock.jsondiff.matcher.Path;
4 | import com.deblock.jsondiff.viewer.JsonDiffViewer;
5 |
6 | public interface JsonDiff {
7 | /**
8 | * @return the similarity rate (min: 0, max: 100)
9 | */
10 | double similarityRate();
11 |
12 | void display(JsonDiffViewer viewer);
13 |
14 | Path path();
15 | }
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/diff/JsonObjectDiff.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.diff;
2 |
3 | import com.deblock.jsondiff.matcher.Path;
4 | import com.deblock.jsondiff.viewer.JsonDiffViewer;
5 | import com.fasterxml.jackson.databind.JsonNode;
6 | import com.fasterxml.jackson.databind.node.ObjectNode;
7 |
8 | import java.util.HashMap;
9 | import java.util.Map;
10 |
11 | public class JsonObjectDiff implements JsonDiff {
12 | private static final int STRUCTURE_MAX_RATIO = 60;
13 | private static final int VALUE_MAX_RATIO = 40;
14 |
15 | private final Map propertiesDiff = new HashMap<>();
16 | private final Map notFoundProperties = new HashMap<>();
17 | private final Map extraProperties = new HashMap<>();
18 |
19 | private final Path path;
20 |
21 | public JsonObjectDiff(Path path) {
22 | this.path = path;
23 | }
24 |
25 | public void addNotFoundProperty(String propertyName, JsonNode value) {
26 | notFoundProperties.put(propertyName, value);
27 | }
28 |
29 | public void addExtraProperty(String propertyName, JsonNode value) {
30 | extraProperties.put(propertyName, value);
31 | }
32 |
33 | public void addPropertyDiff(String propertyName, JsonDiff diff) {
34 | propertiesDiff.put(propertyName, diff);
35 | }
36 |
37 |
38 | @Override
39 | public double similarityRate() {
40 | final var notFoundPropertiesCount = notFoundProperties.keySet().size();
41 | final var unexpectedPropertiesCount = extraProperties.keySet().size();
42 |
43 | final var totalPropertiesCount = propertiesDiff.keySet().size() + notFoundPropertiesCount + unexpectedPropertiesCount;
44 |
45 | if (totalPropertiesCount == 0) {
46 | return 100;
47 | }
48 |
49 | final var propertiesSimilarityRate = propertiesDiff.values().stream()
50 | .mapToDouble(JsonDiff::similarityRate)
51 | .sum();
52 |
53 | final var structureRatio = (totalPropertiesCount - notFoundPropertiesCount - unexpectedPropertiesCount) * STRUCTURE_MAX_RATIO / totalPropertiesCount;
54 | final double equalityRatio;
55 | if (propertiesDiff.isEmpty()) {
56 | equalityRatio = 0;
57 | } else {
58 | equalityRatio = propertiesSimilarityRate * VALUE_MAX_RATIO / (totalPropertiesCount * 100);
59 | }
60 | return structureRatio + equalityRatio;
61 | }
62 |
63 | @Override
64 | public void display(JsonDiffViewer viewer) {
65 | for (final var entry : notFoundProperties.entrySet()) {
66 | viewer.missingProperty(this.path.add(Path.PathItem.of(entry.getKey())), entry.getValue());
67 | }
68 | for (final var entry : propertiesDiff.entrySet()) {
69 | if (entry.getValue().similarityRate() >= 100) {
70 | viewer.matchingProperty(path().add(Path.PathItem.of(entry.getKey())), entry.getValue());
71 | } else {
72 | viewer.nonMatchingProperty(path().add(Path.PathItem.of(entry.getKey())), entry.getValue());
73 | }
74 | }
75 | for (final var entry: extraProperties.entrySet()) {
76 | viewer.extraProperty(path().add(Path.PathItem.of(entry.getKey())), entry.getValue());
77 | }
78 | final var isEmptyObject = notFoundProperties.isEmpty() && propertiesDiff.isEmpty() && extraProperties.isEmpty();
79 | if (isEmptyObject) {
80 | viewer.primaryMatching(path(), new ObjectNode(null));
81 | }
82 | }
83 |
84 | @Override
85 | public Path path() {
86 | return this.path;
87 | }
88 |
89 | }
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/diff/MatchedPrimaryDiff.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.diff;
2 |
3 | import com.deblock.jsondiff.matcher.Path;
4 | import com.deblock.jsondiff.viewer.JsonDiffViewer;
5 | import com.fasterxml.jackson.databind.JsonNode;
6 |
7 | public class MatchedPrimaryDiff implements JsonDiff {
8 | private final JsonNode value;
9 | private final Path path;
10 |
11 | public MatchedPrimaryDiff(Path path, JsonNode value) {
12 | this.value = value;
13 | this.path = path;
14 | }
15 |
16 | @Override
17 | public double similarityRate() {
18 | return 100;
19 | }
20 |
21 | @Override
22 | public void display(JsonDiffViewer viewer) {
23 | viewer.primaryMatching(path, value);
24 | }
25 |
26 | @Override
27 | public Path path() {
28 | return path;
29 | }
30 | }
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/diff/UnMatchedPrimaryDiff.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.diff;
2 |
3 | import com.deblock.jsondiff.matcher.Path;
4 | import com.deblock.jsondiff.viewer.JsonDiffViewer;
5 | import com.fasterxml.jackson.databind.JsonNode;
6 |
7 | public class UnMatchedPrimaryDiff implements JsonDiff {
8 | private final JsonNode expectedValue;
9 | private final JsonNode receivedValue;
10 | private final Path path;
11 |
12 | public UnMatchedPrimaryDiff(Path path, JsonNode expectedValue, JsonNode receivedValue) {
13 | this.expectedValue = expectedValue;
14 | this.receivedValue = receivedValue;
15 | this.path = path;
16 | }
17 |
18 | @Override
19 | public double similarityRate() {
20 | return 0;
21 | }
22 |
23 | @Override
24 | public void display(JsonDiffViewer viewer) {
25 | viewer.primaryNonMatching(path(), expectedValue, receivedValue);
26 | }
27 |
28 | @Override
29 | public Path path() {
30 | return this.path;
31 | }
32 | }
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/matcher/CompositeJsonMatcher.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.matcher;
2 |
3 | import com.deblock.jsondiff.diff.*;
4 | import com.fasterxml.jackson.databind.JsonNode;
5 | import com.fasterxml.jackson.databind.node.ArrayNode;
6 | import com.fasterxml.jackson.databind.node.ObjectNode;
7 | import com.fasterxml.jackson.databind.node.ValueNode;
8 |
9 | public class CompositeJsonMatcher implements JsonMatcher {
10 | private final PartialJsonMatcher jsonArrayPartialMatcher;
11 | private final PartialJsonMatcher jsonObjectPartialMatcher;
12 | private final PartialJsonMatcher primitivePartialMatcher;
13 |
14 | public CompositeJsonMatcher(
15 | PartialJsonMatcher jsonArrayPartialMatcher,
16 | PartialJsonMatcher jsonObjectPartialMatcher,
17 | PartialJsonMatcher primitivePartialMatcher
18 | ) {
19 | this.jsonArrayPartialMatcher = jsonArrayPartialMatcher;
20 | this.jsonObjectPartialMatcher = jsonObjectPartialMatcher;
21 | this.primitivePartialMatcher = primitivePartialMatcher;
22 | }
23 |
24 | @Override
25 | public JsonDiff diff(Path path, JsonNode expected, JsonNode received) {
26 | if (expected instanceof ObjectNode && received instanceof ObjectNode) {
27 | return this.jsonObjectPartialMatcher.jsonDiff(path, (ObjectNode) expected, (ObjectNode) received, this);
28 | } else if (expected instanceof ArrayNode && received instanceof ArrayNode) {
29 | return this.jsonArrayPartialMatcher.jsonDiff(path, (ArrayNode) expected, (ArrayNode) received, this);
30 | } else if (expected instanceof ValueNode && received instanceof ValueNode){
31 | return this.primitivePartialMatcher.jsonDiff(path, (ValueNode) expected, (ValueNode) received, this);
32 | } else {
33 | return new UnMatchedPrimaryDiff(path, expected, received);
34 | }
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/matcher/JsonMatcher.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.matcher;
2 |
3 | import com.deblock.jsondiff.diff.*;
4 | import com.fasterxml.jackson.databind.JsonNode;
5 |
6 | public interface JsonMatcher {
7 |
8 | JsonDiff diff(Path path, JsonNode expected, JsonNode received);
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/matcher/LenientJsonArrayPartialMatcher.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.matcher;
2 |
3 | import com.deblock.jsondiff.diff.JsonArrayDiff;
4 | import com.deblock.jsondiff.diff.JsonDiff;
5 | import com.fasterxml.jackson.databind.JsonNode;
6 | import com.fasterxml.jackson.databind.node.ArrayNode;
7 |
8 | import java.util.ArrayList;
9 | import java.util.Comparator;
10 | import java.util.HashMap;
11 | import java.util.HashSet;
12 | import java.util.Iterator;
13 | import java.util.List;
14 | import java.util.Map;
15 | import java.util.stream.Collectors;
16 |
17 | public class LenientJsonArrayPartialMatcher implements PartialJsonMatcher {
18 | @Override
19 | public JsonDiff jsonDiff(Path path, ArrayNode expectedArrayNode, ArrayNode recievedArrayNode, JsonMatcher jsonMatcher) {
20 | final var diff = new JsonArrayDiff(path);
21 | var mismatches = processMatchingArrayNodesAndReportMismatches(expectedArrayNode, recievedArrayNode, diff, path, jsonMatcher);
22 | if (!mismatches.expectedMissing.isEmpty() || !mismatches.actualMissing.isEmpty()) {
23 | final var diffMap = new HashMap>();
24 | for (var expectedMissing: mismatches.expectedMissing) {
25 | final var map = new HashMap();
26 | for (var actualMissing: mismatches.actualMissing) {
27 | map.put(
28 | actualMissing.index,
29 | jsonMatcher.diff(
30 | path.add(Path.PathItem.of(expectedMissing.index)), expectedMissing.jsonNode, actualMissing.jsonNode
31 | )
32 | );
33 | }
34 | diffMap.put(expectedMissing.index, map);
35 | }
36 |
37 | final var entrySortedByBestMatch =
38 | diffMap.entrySet().stream()
39 | .sorted(Comparator.comparingDouble(this::maxSimilarityRate).reversed())
40 | .toList();
41 | final var alreadyMatchedIndex = new HashSet();
42 |
43 | for (final var entry : entrySortedByBestMatch) {
44 | final var matchedItem = entry.getValue().entrySet().stream()
45 | .filter(e -> !alreadyMatchedIndex.contains(e.getKey()))
46 | .max(Comparator.comparingDouble(e -> e.getValue().similarityRate()));
47 |
48 | if (matchedItem.isEmpty()) {
49 | diff.addNoMatch(entry.getKey(), expectedArrayNode.get(entry.getKey()));
50 | } else {
51 | diff.addDiff(entry.getKey(), matchedItem.get().getValue());
52 | alreadyMatchedIndex.add(matchedItem.get().getKey());
53 | }
54 | }
55 |
56 | if (alreadyMatchedIndex.size() < recievedArrayNode.size()) {
57 | final var receivedIndex = mismatches.actualMissing.stream().map(it -> it.index).collect(Collectors.toList());
58 | receivedIndex.removeAll(alreadyMatchedIndex);
59 | receivedIndex.forEach(index -> diff.addExtraItem(index, recievedArrayNode.get(index)));
60 | }
61 | }
62 |
63 | return diff;
64 | }
65 |
66 | private double maxSimilarityRate(Map.Entry> entry) {
67 | return entry.getValue().values().stream().mapToDouble(JsonDiff::similarityRate).max().orElse(0);
68 | }
69 |
70 | private MismatchPair, List> processMatchingArrayNodesAndReportMismatches(ArrayNode expectedArrayNode, ArrayNode actualArrayNode, JsonArrayDiff diff, Path path, JsonMatcher jsonMatcher) {
71 | if (actualArrayNode.equals(expectedArrayNode)) {
72 | for (int i = 0; i < expectedArrayNode.size(); i++) {
73 | diff.addDiff(i, jsonMatcher.diff(path.add(Path.PathItem.of(i)), expectedArrayNode.get(i), expectedArrayNode.get(i)));
74 | }
75 | return new MismatchPair<>(List.of(), List.of());
76 | }
77 | List expectedMissing = new ArrayList<>();
78 | List actualMissing = new ArrayList<>();
79 | NodeCounter expectedNodeCounter = getElementsWithCount(expectedArrayNode.elements());
80 | NodeCounter actualNodeCounter = getElementsWithCount(actualArrayNode.elements());
81 |
82 | for (int i = 0; i < expectedArrayNode.size(); i++) {
83 | var expectedElement = expectedArrayNode.get(i);
84 | if (actualNodeCounter.containsNode(expectedElement)) {
85 | actualNodeCounter.removeNode(expectedElement);
86 | diff.addDiff(i, jsonMatcher.diff(path.add(Path.PathItem.of(i)), expectedElement, expectedElement));
87 | } else {
88 | expectedMissing.add(new IndexedJsonNode(i, expectedArrayNode.get(i)));
89 | }
90 | }
91 | for (int i = 0; i < actualArrayNode.size(); i++) {
92 | var actualElement = actualArrayNode.get(i);
93 | if (expectedNodeCounter.containsNode(actualElement)) {
94 | expectedNodeCounter.removeNode(actualElement);
95 | } else {
96 | actualMissing.add(new IndexedJsonNode(i, actualArrayNode.get(i)));
97 | }
98 | }
99 | return new MismatchPair<>(expectedMissing, actualMissing);
100 | }
101 |
102 | private NodeCounter getElementsWithCount(Iterator elements) {
103 | var nodeCounter = new NodeCounter();
104 | elements.forEachRemaining(nodeCounter::addNode);
105 | return nodeCounter;
106 | }
107 |
108 | private static class MismatchPair {
109 | private final K expectedMissing;
110 | private final V actualMissing;
111 |
112 | public MismatchPair(K expectedMissing, V actualMissing) {
113 | this.expectedMissing = expectedMissing;
114 | this.actualMissing = actualMissing;
115 | }
116 | }
117 |
118 | private static class IndexedJsonNode {
119 | private final int index;
120 | private final JsonNode jsonNode;
121 |
122 | public IndexedJsonNode(int index, JsonNode jsonNode) {
123 | this.index = index;
124 | this.jsonNode = jsonNode;
125 | }
126 | }
127 |
128 | private static class NodeCounter {
129 | private Map nodeCounter = new HashMap<>();
130 |
131 | public void addNode(JsonNode node) {
132 | nodeCounter.compute(node, (key, prevValue) -> (prevValue == null ? 0 : prevValue) + 1);
133 | }
134 |
135 | public void removeNode(JsonNode node) {
136 | nodeCounter.put(node, nodeCounter.get(node) - 1);
137 | if (nodeCounter.get(node) == 0) {
138 | nodeCounter.remove(node);
139 | }
140 | }
141 |
142 | public boolean containsNode(JsonNode node) {
143 | return nodeCounter.containsKey(node);
144 | }
145 | }
146 | }
147 |
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/matcher/LenientJsonObjectPartialMatcher.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.matcher;
2 |
3 | import com.deblock.jsondiff.diff.JsonDiff;
4 | import com.deblock.jsondiff.diff.JsonObjectDiff;
5 | import com.fasterxml.jackson.databind.node.ObjectNode;
6 |
7 | public class LenientJsonObjectPartialMatcher implements PartialJsonMatcher {
8 |
9 | @Override
10 | public JsonDiff jsonDiff(Path path, ObjectNode expectedJson, ObjectNode receivedJson, JsonMatcher jsonMatcher) {
11 | final var jsonDiff = new JsonObjectDiff(path);
12 |
13 | expectedJson.fields()
14 | .forEachRemaining(entry -> {
15 | final var expectedPropertyName = entry.getKey();
16 | final var expectedValue = entry.getValue();
17 | final var receivedValue = receivedJson.get(expectedPropertyName);
18 |
19 | if (receivedValue == null) {
20 | jsonDiff.addNotFoundProperty(expectedPropertyName, expectedValue);
21 | } else {
22 | final var diff = jsonMatcher.diff(path.add(Path.PathItem.of(expectedPropertyName)), expectedValue, receivedValue);
23 | jsonDiff.addPropertyDiff(expectedPropertyName, diff);
24 | }
25 | });
26 |
27 | return jsonDiff;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/matcher/LenientNumberPrimitivePartialMatcher.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.matcher;
2 |
3 | import com.deblock.jsondiff.diff.JsonDiff;
4 | import com.deblock.jsondiff.diff.MatchedPrimaryDiff;
5 | import com.deblock.jsondiff.diff.UnMatchedPrimaryDiff;
6 | import com.fasterxml.jackson.databind.node.NumericNode;
7 | import com.fasterxml.jackson.databind.node.ValueNode;
8 |
9 | public class LenientNumberPrimitivePartialMatcher implements PartialJsonMatcher {
10 | private final PartialJsonMatcher delegated;
11 |
12 | public LenientNumberPrimitivePartialMatcher(PartialJsonMatcher delegated) {
13 | this.delegated = delegated;
14 | }
15 |
16 | @Override
17 | public JsonDiff jsonDiff(Path path, ValueNode expectedValue, ValueNode receivedValue, JsonMatcher jsonMatcher) {
18 | if (expectedValue instanceof NumericNode && receivedValue instanceof NumericNode) {
19 | final var expectedIntValue = expectedValue.intValue();
20 | final var actualIntValue = receivedValue.intValue();
21 | final var expectedDecimalValue = receivedValue.doubleValue() % 1;
22 | final var actualDecimalValue = expectedValue.doubleValue() % 1;
23 |
24 | if (expectedIntValue != actualIntValue || expectedDecimalValue != actualDecimalValue) {
25 | return new UnMatchedPrimaryDiff(path, expectedValue, receivedValue);
26 | } else {
27 | return new MatchedPrimaryDiff(path, expectedValue);
28 | }
29 | }
30 |
31 | return delegated.jsonDiff(path, expectedValue, receivedValue, jsonMatcher);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/matcher/PartialJsonMatcher.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.matcher;
2 |
3 | import com.deblock.jsondiff.diff.JsonDiff;
4 | import com.fasterxml.jackson.databind.JsonNode;
5 |
6 | public interface PartialJsonMatcher {
7 | JsonDiff jsonDiff(Path path, T expectedJson, T receivedJson, JsonMatcher jsonMatcher);
8 | }
9 |
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/matcher/Path.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.matcher;
2 |
3 | import java.util.Objects;
4 |
5 | public class Path {
6 | public static final Path ROOT = new Path();
7 |
8 | public final PathItem property;
9 | public final Path next;
10 |
11 | public Path() {
12 | this(null, null);
13 | }
14 |
15 | private Path(PathItem property, Path next) {
16 | this.property = property;
17 | this.next = next;
18 | }
19 |
20 | private Path(PathItem property) {
21 | this.property = property;
22 | this.next = null;
23 | }
24 |
25 | public Path add(PathItem item) {
26 | if (this.next == null) {
27 | return new Path(this.property, new Path(item));
28 | } else {
29 | return new Path(this.property, this.next.add(item));
30 | }
31 | }
32 |
33 | public String toString() {
34 | return ((this.property == null) ? "$" : this.property) +
35 | ((this.next == null) ? "" : "." + this.next);
36 | }
37 |
38 | @Override
39 | public boolean equals(Object o) {
40 | if (this == o) return true;
41 | if (o == null || getClass() != o.getClass()) return false;
42 | Path path = (Path) o;
43 | return Objects.equals(property, path.property) && Objects.equals(next, path.next);
44 | }
45 |
46 | @Override
47 | public int hashCode() {
48 | return Objects.hash(property, next);
49 | }
50 |
51 | public interface PathItem {
52 | static PathItem of(String property) {
53 | return new ObjectProperty(property);
54 | }
55 |
56 | static PathItem of(Integer index) {
57 | return new ArrayIndex(index);
58 | }
59 |
60 | class ArrayIndex implements PathItem {
61 | public final int index;
62 |
63 | public ArrayIndex(int index) {
64 | this.index = index;
65 | }
66 |
67 | @Override
68 | public String toString() {
69 | return String.valueOf(index);
70 | }
71 |
72 | @Override
73 | public boolean equals(Object o) {
74 | if (this == o) return true;
75 | if (o == null || getClass() != o.getClass()) return false;
76 | ArrayIndex that = (ArrayIndex) o;
77 | return index == that.index;
78 | }
79 |
80 | @Override
81 | public int hashCode() {
82 | return Objects.hash(index);
83 | }
84 | }
85 |
86 | class ObjectProperty implements PathItem {
87 | public final String property;
88 |
89 | public ObjectProperty(String property) {
90 | this.property = property;
91 | }
92 |
93 | @Override
94 | public String toString() {
95 | return this.property;
96 | }
97 |
98 | @Override
99 | public boolean equals(Object o) {
100 | if (this == o) return true;
101 | if (o == null || getClass() != o.getClass()) return false;
102 | ObjectProperty that = (ObjectProperty) o;
103 | return Objects.equals(property, that.property);
104 | }
105 |
106 | @Override
107 | public int hashCode() {
108 | return Objects.hash(property);
109 | }
110 | }
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/matcher/StrictJsonArrayPartialMatcher.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.matcher;
2 |
3 | import com.deblock.jsondiff.diff.JsonArrayDiff;
4 | import com.deblock.jsondiff.diff.JsonDiff;
5 | import com.fasterxml.jackson.databind.node.ArrayNode;
6 |
7 | import java.util.Comparator;
8 | import java.util.HashMap;
9 | import java.util.HashSet;
10 | import java.util.Map;
11 | import java.util.stream.Collectors;
12 | import java.util.stream.IntStream;
13 |
14 | public class StrictJsonArrayPartialMatcher implements PartialJsonMatcher {
15 | @Override
16 | public JsonDiff jsonDiff(Path path, ArrayNode expectedValues, ArrayNode receivedValues, JsonMatcher jsonMatcher) {
17 | final var diff = new JsonArrayDiff(path);
18 |
19 | for (int i = 0; i < expectedValues.size() && i < receivedValues.size(); i++) {
20 | final var expectedValue = expectedValues.get(i);
21 | final var receivedValue = receivedValues.get(i);
22 |
23 | final var valueDiff = jsonMatcher.diff(path.add(Path.PathItem.of(i)), expectedValue, receivedValue);
24 | diff.addDiff(i, valueDiff);
25 | }
26 |
27 | if (expectedValues.size() > receivedValues.size()) {
28 | for (int i = receivedValues.size(); i < expectedValues.size(); i++) {
29 | diff.addNoMatch(i, expectedValues.get(i));
30 | }
31 | } else if (expectedValues.size() < receivedValues.size()) {
32 | for (int i = expectedValues.size(); i < receivedValues.size(); i++) {
33 | diff.addExtraItem(i, receivedValues.get(i));
34 | }
35 | }
36 | return diff;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/matcher/StrictJsonObjectPartialMatcher.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.matcher;
2 |
3 | import com.deblock.jsondiff.diff.JsonDiff;
4 | import com.deblock.jsondiff.diff.JsonObjectDiff;
5 | import com.fasterxml.jackson.databind.node.ObjectNode;
6 |
7 | import java.util.stream.Collectors;
8 | import java.util.stream.StreamSupport;
9 |
10 | public class StrictJsonObjectPartialMatcher implements PartialJsonMatcher {
11 |
12 | @Override
13 | public JsonDiff jsonDiff(Path path, ObjectNode expectedJson, ObjectNode receivedJson, JsonMatcher jsonMatcher) {
14 | final var jsonDiff = new JsonObjectDiff(path);
15 | final var receivedJsonFields = StreamSupport.stream(((Iterable) receivedJson::fieldNames).spliterator(), false).collect(Collectors.toSet());
16 |
17 | expectedJson.fields()
18 | .forEachRemaining(entry -> {
19 | final var expectedPropertyName = entry.getKey();
20 | final var expectedValue = entry.getValue();
21 | final var receivedValue = receivedJson.get(expectedPropertyName);
22 |
23 | if (receivedValue == null) {
24 | jsonDiff.addNotFoundProperty(expectedPropertyName, expectedValue);
25 | } else {
26 | final var diff = jsonMatcher.diff(path.add(Path.PathItem.of(expectedPropertyName)), expectedValue, receivedValue);
27 | jsonDiff.addPropertyDiff(expectedPropertyName, diff);
28 | }
29 | receivedJsonFields.remove(expectedPropertyName);
30 | });
31 |
32 |
33 | receivedJson.fields()
34 | .forEachRemaining(entry -> {
35 | final var receivedPropertyName = entry.getKey();
36 | final var receivedPropertyValue = entry.getValue();
37 | final var expectedValue = expectedJson.get(receivedPropertyName);
38 |
39 | if (expectedValue == null) {
40 | jsonDiff.addExtraProperty(receivedPropertyName, receivedPropertyValue);
41 | }
42 | });
43 |
44 | return jsonDiff;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/matcher/StrictPrimitivePartialMatcher.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.matcher;
2 |
3 | import com.deblock.jsondiff.diff.JsonDiff;
4 | import com.deblock.jsondiff.diff.MatchedPrimaryDiff;
5 | import com.deblock.jsondiff.diff.UnMatchedPrimaryDiff;
6 | import com.fasterxml.jackson.databind.node.ValueNode;
7 |
8 | import java.util.Objects;
9 |
10 | public class StrictPrimitivePartialMatcher implements PartialJsonMatcher {
11 |
12 | @Override
13 | public JsonDiff jsonDiff(Path path, ValueNode expectedValue, ValueNode receivedValue, JsonMatcher jsonMatcher) {
14 | if (Objects.equals(expectedValue, receivedValue)) {
15 | return new MatchedPrimaryDiff(path, expectedValue);
16 | } else {
17 | return new UnMatchedPrimaryDiff(path, expectedValue, receivedValue);
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/viewer/JsonDiffViewer.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.viewer;
2 |
3 | import com.deblock.jsondiff.diff.JsonDiff;
4 | import com.deblock.jsondiff.matcher.Path;
5 | import com.fasterxml.jackson.databind.JsonNode;
6 |
7 | public interface JsonDiffViewer {
8 |
9 | void matchingProperty(Path path, JsonDiff diff);
10 |
11 | void nonMatchingProperty(Path path, JsonDiff diff);
12 |
13 | void missingProperty(Path path, JsonNode value);
14 |
15 | void extraProperty(Path path, JsonNode extraReceivedValue);
16 |
17 | void primaryNonMatching(Path path, JsonNode expected, JsonNode value);
18 |
19 | void primaryMatching(Path path, JsonNode value);
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/viewer/OnlyErrorDiffViewer.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.viewer;
2 |
3 | import com.deblock.jsondiff.diff.JsonDiff;
4 | import com.deblock.jsondiff.matcher.Path;
5 | import com.fasterxml.jackson.databind.JsonNode;
6 |
7 | /**
8 | * List all error on a string
9 | * call .toString to get the error string
10 | */
11 | public class OnlyErrorDiffViewer implements JsonDiffViewer {
12 | private final StringBuilder stringBuilder = new StringBuilder();
13 |
14 | @Override
15 | public void matchingProperty(Path path, JsonDiff value) { }
16 |
17 | @Override
18 | public void primaryMatching(Path path, JsonNode value) {
19 |
20 | }
21 |
22 | @Override
23 | public void nonMatchingProperty(Path path, JsonDiff diff) {
24 | diff.display(this);
25 | }
26 |
27 | @Override
28 | public void missingProperty(Path path, JsonNode value) {
29 | stringBuilder
30 | .append("The property \"")
31 | .append(path)
32 | .append("\" in the expected json is not found\n");
33 | }
34 |
35 | @Override
36 | public void extraProperty(Path path, JsonNode extraReceivedValue) {
37 | stringBuilder
38 | .append("The property \"")
39 | .append(path)
40 | .append("\" in the received json is not expected\n");
41 | }
42 |
43 | @Override
44 | public void primaryNonMatching(Path path, JsonNode expected, JsonNode value) {
45 | stringBuilder
46 | .append("The property \"").append(path)
47 | .append("\" didn't match. Expected ").append(expected)
48 | .append(", Received: ").append(value)
49 | .append("\n");
50 | }
51 |
52 | public String toString() {
53 | return stringBuilder.toString();
54 | }
55 |
56 | public static JsonDiffViewer from(JsonDiff jsonDiff) {
57 | final var result = new OnlyErrorDiffViewer();
58 | jsonDiff.display(result);
59 | return result;
60 | }
61 | }
--------------------------------------------------------------------------------
/src/main/java/com/deblock/jsondiff/viewer/PatchDiffViewer.java:
--------------------------------------------------------------------------------
1 | package com.deblock.jsondiff.viewer;
2 |
3 | import com.deblock.jsondiff.diff.JsonDiff;
4 | import com.deblock.jsondiff.matcher.Path;
5 | import com.fasterxml.jackson.databind.JsonNode;
6 |
7 | import java.util.ArrayList;
8 | import java.util.HashMap;
9 | import java.util.List;
10 | import java.util.Map;
11 | import java.util.stream.Collectors;
12 | import java.util.stream.Stream;
13 |
14 | /**
15 | * This is an experimental feature
16 | *
17 | * create a patch file from a json diff
18 | * call .toString to get the patch string
19 | */
20 | public class PatchDiffViewer implements JsonDiffViewer {
21 | private Object diff = null;
22 |
23 | @Override
24 | public void matchingProperty(Path path, JsonDiff value) {
25 | value.display(this);
26 | }
27 |
28 | @Override
29 | public void primaryMatching(Path path, JsonNode value) {
30 | this.diff = this.addPath(diff, path, new DiffValue.MatchingProperty(value));
31 | }
32 |
33 | @Override
34 | public void nonMatchingProperty(Path path, JsonDiff diff) {
35 | diff.display(this);
36 | }
37 |
38 | @Override
39 | public void missingProperty(Path path, JsonNode value) {
40 | this.diff = this.addPath(diff, path, new DiffValue.MissingProperty(value));
41 | }
42 |
43 | @Override
44 | public void extraProperty(Path path, JsonNode extraReceivedValue) {
45 | this.diff = this.addPath(diff, path, new DiffValue.ExtraProperty(extraReceivedValue));
46 | }
47 |
48 | @Override
49 | public void primaryNonMatching(Path path, JsonNode expected, JsonNode value) {
50 | this.diff = this.addPath(diff, path, new DiffValue.NonMatchingProperty(expected, value));
51 | }
52 |
53 | public Object addPath(Object root, Path path, DiffValue diffValue) {
54 | if (path == null) {
55 | return diffValue;
56 | } else if (path.property instanceof Path.PathItem.ArrayIndex) {
57 | final var index = ((Path.PathItem.ArrayIndex) path.property).index;
58 | if (root == null) {
59 | final var newRoot = new DiffValue.ArrayDiff();
60 | newRoot.set(index, this.addPath(null, path.next, diffValue));
61 | return newRoot;
62 | } else if (root instanceof DiffValue.ArrayDiff) {
63 | final var array = (DiffValue.ArrayDiff) root;
64 | if (array.hasIndex(index) && !(diffValue instanceof DiffValue.ExtraProperty)) {
65 | this.addPath(array.get(index), path.next, diffValue);
66 | } else {
67 | array.set(index, this.addPath(array.get(index), path.next, diffValue));
68 | }
69 | return array;
70 | } else {
71 | throw new IllegalArgumentException("The path " + path + " is not an array");
72 | }
73 | } else if (path.property instanceof Path.PathItem.ObjectProperty) {
74 | final var propertyName = ((Path.PathItem.ObjectProperty) path.property).property;
75 | if (root == null) {
76 | final var newRoot = new HashMap();
77 | newRoot.put(propertyName, this.addPath(null, path.next, diffValue));
78 | return newRoot;
79 | } else if (root instanceof Map) {
80 | final var map = (Map) root;
81 | map.put(propertyName, this.addPath(map.get(propertyName), path.next, diffValue));
82 | return map;
83 | } else {
84 | throw new IllegalArgumentException("The path " + path + " is not an object");
85 | }
86 | } else if (path.property == null) {
87 | if (path.next != null) {
88 | return this.addPath(root, path.next, diffValue);
89 | } else {
90 | return diff;
91 | }
92 | } else {
93 | throw new IllegalArgumentException("Unsupported path type " + path.property.getClass());
94 | }
95 | }
96 |
97 | public String toString() {
98 | return "--- actual\n+++ expected\n@@ @@\n" + toDiff(this.diff, "", "", "", "");
99 | }
100 |
101 | private String toDiff(Object diff, String indent, String startOfLine, String endOfLineExpected, String endOfLineActual) {
102 | if (diff instanceof DiffValue.ArrayDiff) {
103 | final var arrayContent = new StringBuilder();
104 | final var allObjects = ((DiffValue.ArrayDiff) diff).allObjects();
105 | for (int i = 0; i < allObjects.size(); ++i) {
106 | final var object = allObjects.get(i);
107 | arrayContent
108 | .append(toDiff(
109 | object,
110 | indent + " ",
111 | indent + " ",
112 | commaIfHasNextExpectedProperty(i + 1, allObjects),
113 | commaIfHasNextActualProperty(i + 1, allObjects)
114 | ))
115 | .append("\n");
116 | }
117 | return startOfLine + " [\n" + arrayContent + indent + " ]" + endOfLineExpected;
118 | } else if (diff instanceof Map) {
119 | final var objectContent = new StringBuilder();
120 | final var diffObject = (Map) diff;
121 | final var keys = new ArrayList<>(diffObject.keySet());
122 | for (int i = 0; i < keys.size(); ++i) {
123 | final var object = diffObject.get(keys.get(i));
124 | final var isObjectNotADiff = object instanceof DiffValue.ArrayDiff || object instanceof Map;
125 | final var propertyPrefix = indent + " \"" + keys.get(i) + "\":" + ((isObjectNotADiff) ? "" : " ");
126 | objectContent
127 | .append(isObjectNotADiff ? " " + propertyPrefix : "")
128 | .append(toDiff(
129 | object,
130 | isObjectNotADiff ? indent + " " : propertyPrefix,
131 | "",
132 | commaIfHasNextExpectedProperty(i + 1, diffObject, keys),
133 | commaIfHasNextActualProperty(i + 1, diffObject, keys)
134 | ))
135 | .append("\n");
136 | }
137 | return startOfLine + " {\n" + objectContent + indent + " }" + endOfLineExpected;
138 | } else if (diff instanceof DiffValue.MatchingProperty) {
139 | if (endOfLineActual.equals(endOfLineExpected)) {
140 | return " " + indent + ((DiffValue.MatchingProperty) diff).value.toString() + endOfLineActual;
141 | } else {
142 | return "-" + indent + ((DiffValue.MatchingProperty) diff).value.toString() + endOfLineActual + "\n" +
143 | "+" + indent + ((DiffValue.MatchingProperty) diff).value.toString() + endOfLineExpected;
144 | }
145 | } else if (diff instanceof DiffValue.MissingProperty) {
146 | return "+" + indent + ((DiffValue.MissingProperty) diff).value.toString() + endOfLineExpected;
147 | } else if (diff instanceof DiffValue.ExtraProperty) {
148 | return "-" + indent + ((DiffValue.ExtraProperty) diff).value.toString() + endOfLineActual;
149 | } else if (diff instanceof DiffValue.NonMatchingProperty) {
150 | final var value = ((DiffValue.NonMatchingProperty) diff);
151 | return "-" + indent + value.value.toString() + endOfLineActual + "\n+" + indent + value.expected.toString() + endOfLineExpected;
152 | } else {
153 | throw new IllegalArgumentException("Unsupported diff type " + diff.getClass());
154 | }
155 | }
156 |
157 |
158 | private String commaIfHasNextExpectedProperty(int index, Map diffObject, ArrayList keys) {
159 | for (int i = index; i < keys.size(); ++i) {
160 | if (isExpectedPart(diffObject.get(keys.get(i)))) {
161 | return ",";
162 | }
163 | }
164 | return "";
165 | }
166 |
167 | private String commaIfHasNextActualProperty(int index, Map diffObject, ArrayList keys) {
168 | for (int i = index; i < keys.size(); ++i) {
169 | if (isActualPart(diffObject.get(keys.get(i)))) {
170 | return ",";
171 | }
172 | }
173 | return "";
174 | }
175 |
176 | private String commaIfHasNextExpectedProperty(int index, List