├── .idea ├── .gitignore ├── migrations.xml └── codeStyles ├── convention-plugins ├── settings.gradle.kts ├── build.gradle.kts └── src │ └── main │ └── kotlin │ └── maven-publish.conventions.gradle.kts ├── gradle ├── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties └── libs.versions.toml ├── kotlin-json-patch ├── src │ ├── commonMain │ │ └── kotlin │ │ │ └── com │ │ │ └── reidsync │ │ │ └── kxjsonpatch │ │ │ ├── Constants.kt │ │ │ ├── NodeType.kt │ │ │ ├── ApplyProcessor.kt │ │ │ ├── CompatibilityFlags.kt │ │ │ ├── InvalidJsonPatchException.kt │ │ │ ├── JsonPatchApplicationException.kt │ │ │ ├── JsonPatchProcessor.kt │ │ │ ├── JsonPatchEditingContext.kt │ │ │ ├── Operations.kt │ │ │ ├── NoopProcessor.kt │ │ │ ├── Diff.kt │ │ │ ├── JsonPatchApplyProcessor.kt │ │ │ ├── lcs │ │ │ ├── Equator.kt │ │ │ ├── DeleteCommand.kt │ │ │ ├── InsertCommand.kt │ │ │ ├── KeepCommand.kt │ │ │ ├── ListUtils.kt │ │ │ ├── EditCommand.kt │ │ │ ├── DefaultEquator.kt │ │ │ ├── EditScript.kt │ │ │ ├── CommandVisitor.kt │ │ │ └── SequencesComparator.kt │ │ │ ├── JsonElementExtensions.kt │ │ │ ├── JsonPatch.kt │ │ │ ├── JsonPatchEditingContextImpl.kt │ │ │ └── JsonDiff.kt │ └── commonTest │ │ └── kotlin │ │ ├── resources │ │ ├── debug.json.kt │ │ ├── remove-unsupported.json.kt │ │ ├── replace-unsupported.json.kt │ │ ├── move-unsupported.json.kt │ │ ├── diff-unsupported.json.kt │ │ ├── remove.json.kt │ │ ├── add-unsupported.json.kt │ │ ├── replace.json.kt │ │ ├── rfc6902-samples-unsupported.json.kt │ │ ├── move.json.kt │ │ ├── add.json.kt │ │ ├── js-libs-samples-unsupported.json.kt │ │ ├── diff.kt │ │ ├── rfc6902-samples.json.kt │ │ └── js-libs-samples.json.kt │ │ └── com │ │ └── reidsync │ │ └── kxjsonpatch │ │ ├── utils │ │ ├── IOUtils.kt │ │ └── GsonObjectMapper.kt │ │ ├── AddOperationTest.kt │ │ ├── RemoveOperationTest.kt │ │ ├── ReplaceOperationTest.kt │ │ ├── Rfc6902SamplesTest.kt │ │ ├── JsLibSamplesTest.kt │ │ ├── JsonDiffTest2.kt │ │ ├── PatchTestCase.kt │ │ ├── AbstractTest.kt │ │ ├── MoveOperationTest.kt │ │ ├── CompatibilityTest.kt │ │ ├── ApiTest.kt │ │ ├── TestDataGenerator.kt │ │ └── JsonDiffTest.kt └── build.gradle.kts ├── gradle.properties ├── settings.gradle.kts ├── .circleci └── config.yml ├── gradlew.bat ├── README.md ├── .gitignore ├── gradlew └── LICENSE /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /convention-plugins/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "convention-plugins" -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReidSync/kotlin-json-patch/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /convention-plugins/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | `kotlin-dsl` // Is needed to turn our build logic written in Kotlin into Gralde Plugin 3 | } 4 | 5 | repositories { 6 | gradlePluginPortal() // To use 'maven-publish' and 'signing' plugins in our own plugin 7 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/Constants.kt: -------------------------------------------------------------------------------- 1 | package com.reidsync.kxjsonpatch 2 | 3 | open class Constants { 4 | open val OP = "op" 5 | open val VALUE = "value" 6 | open val PATH = "path" 7 | open val FROM = "from" 8 | } 9 | -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/resources/debug.json.kt: -------------------------------------------------------------------------------- 1 | package resources.testdata 2 | 3 | const val TestData_DEBUG: String = """ 4 | [ 5 | { 6 | "first":{"compare":{"":"a"},"tags":{}}, 7 | "second":{"compare":{"":"b"},"tags":{"a":"b"}} 8 | } 9 | ] 10 | """ -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /.idea/migrations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 10 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | #Gradle 2 | org.gradle.jvmargs=-Xmx2048M -Dfile.encoding=UTF-8 -Dkotlin.daemon.jvm.options\="-Xmx2048M" 3 | org.gradle.caching=true 4 | org.gradle.configuration-cache=true 5 | 6 | #Kotlin 7 | kotlin.code.style=official 8 | 9 | #Android 10 | android.useAndroidX=true 11 | android.nonTransitiveRClass=true -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/utils/IOUtils.kt: -------------------------------------------------------------------------------- 1 | package com.reidsync.kxjsonpatch.utils 2 | 3 | object IOUtils { 4 | //see http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string 5 | fun toString(fileName: String): String { 6 | return fileName 7 | } 8 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/resources/remove-unsupported.json.kt: -------------------------------------------------------------------------------- 1 | package resources.testdata 2 | 3 | const val TestData_REMOVE_UNSUPPORTED: String = """ 4 | { 5 | "errors": [ 6 | { 7 | "op": [{ "op": "remove", "path": "/x/y" }], 8 | "node": { "x": {} }, 9 | "message": "jsonPatch.noSuchPath" 10 | } 11 | ], 12 | "ops": [ 13 | ] 14 | } 15 | """ -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/resources/replace-unsupported.json.kt: -------------------------------------------------------------------------------- 1 | package resources.testdata 2 | 3 | const val TestData_REPLACE_UNSUPPORTED: String = """ 4 | { 5 | "errors": [ 6 | { 7 | "op": [{ "op": "replace", "path": "/x/y", "value": 42 }], 8 | "node": { "x": {} }, 9 | "message": "jsonPatch.noSuchPath" 10 | } 11 | ], 12 | "ops": [ 13 | ] 14 | } 15 | """ -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS") 2 | pluginManagement { 3 | repositories { 4 | google() 5 | gradlePluginPortal() 6 | mavenCentral() 7 | } 8 | } 9 | 10 | dependencyResolutionManagement { 11 | repositories { 12 | google() 13 | mavenCentral() 14 | } 15 | } 16 | 17 | rootProject.name = "Kotlin-Json-Patching-Library" 18 | include(":kotlin-json-patch") 19 | includeBuild("convention-plugins") -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/utils/GsonObjectMapper.kt: -------------------------------------------------------------------------------- 1 | package com.reidsync.kxjsonpatch.utils 2 | 3 | import kotlinx.serialization.json.Json 4 | import kotlinx.serialization.json.JsonElement 5 | import kotlinx.serialization.json.JsonNull 6 | 7 | class GsonObjectMapper { 8 | fun readTree(jsondata: String?): JsonElement { 9 | if (jsondata != null) { 10 | return Json.parseToJsonElement(jsondata) 11 | } 12 | else { 13 | return JsonNull 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/NodeType.kt: -------------------------------------------------------------------------------- 1 | package com.reidsync.kxjsonpatch 2 | 3 | import kotlinx.serialization.json.* 4 | 5 | 6 | internal object NodeType { 7 | val ARRAY = 1 8 | val OBJECT = 2 9 | // static final int NULL=3; 10 | val PRIMITIVE_OR_NULL = 3 11 | 12 | fun getNodeType(node: JsonElement): Int { 13 | if (node is JsonArray) return ARRAY 14 | if (node is JsonObject) return OBJECT 15 | // if(node.isJsonNull()) return NULL; 16 | return PRIMITIVE_OR_NULL 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/resources/move-unsupported.json.kt: -------------------------------------------------------------------------------- 1 | package resources.testdata 2 | 3 | const val TestData_MOVE_UNSUPPORTED: String = """ 4 | { 5 | "errors": [ 6 | { 7 | "op": [{ "op": "move", "from": "/a", "path": "/a/b" }], 8 | "node": {}, 9 | "message": "jsonPatch.noSuchPath" 10 | }, 11 | { 12 | "op": [{ "op": "move", "from": "/a", "path": "/b/c" }], 13 | "node": { "a": "b" }, 14 | "message": "jsonPatch.noSuchParent" 15 | } 16 | ], 17 | "ops": [ 18 | ] 19 | } 20 | """ -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/resources/diff-unsupported.json.kt: -------------------------------------------------------------------------------- 1 | package resources.testdata 2 | 3 | const val TestData_DIFF_UNSUPPORTED: String = """ 4 | [ 5 | { 6 | "message": "similar element is copied instead of added", 7 | "first": { 8 | "a": "c" 9 | }, 10 | "second": { 11 | "a": "c", 12 | "d": "c" 13 | }, 14 | "patch": [ 15 | { "op": "copy", "path": "/d", "from": "/a" } 16 | ] 17 | }, 18 | { 19 | "message": "similar element removed then added is moved instead", 20 | "first": { "a": "b" }, 21 | "second": { "c": "b" }, 22 | "patch": [ 23 | { "op": "move", "path": "/c", "from": "/a" } 24 | ] 25 | } 26 | ] 27 | """ -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/ApplyProcessor.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.reidsync.kxjsonpatch 18 | import kotlinx.serialization.json.* 19 | 20 | class ApplyProcessor(private val target: JsonElement) : JsonPatchApplyProcessor(target.deepCopy()) { 21 | fun result(): JsonElement = targetSource 22 | } 23 | 24 | -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/resources/remove.json.kt: -------------------------------------------------------------------------------- 1 | package resources.testdata 2 | 3 | const val TestData_REMOVE: String = """ 4 | { 5 | "errors": [ 6 | { 7 | "op": [{ "op": "remove", "path": "/x/y" }], 8 | "node": { "x": "just a string" } 9 | }, 10 | { 11 | "op": [{ "op": "remove", "path": "/x/1" }], 12 | "node": { "x": [ "single" ] } 13 | } 14 | ], 15 | "ops": [ 16 | { 17 | "op": [{ "op": "remove", "path": "/x/y" }], 18 | "node": { "x": { "a": "b", "y": {} } }, 19 | "expected": { "x": { "a": "b" } } 20 | }, 21 | { 22 | "op": [{ "op": "remove", "path": "/0/2" }], 23 | "node": [ [ "a", "b", "c"], "d", "e" ], 24 | "expected": [ [ "a", "b" ], "d", "e" ] 25 | }, 26 | { 27 | "op": [{ "op": "remove", "path": "/x/0" }], 28 | "node": { "x": [ "y", "z" ], "foo": "bar" }, 29 | "expected": { "x": [ "z" ], "foo": "bar" } 30 | } 31 | ] 32 | } 33 | """ -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/CompatibilityFlags.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.reidsync.kxjsonpatch 18 | 19 | /** 20 | * Created by tomerga on 04/09/2016. 21 | */ 22 | enum class CompatibilityFlags { 23 | MISSING_VALUES_AS_NULLS; 24 | 25 | 26 | companion object { 27 | fun defaults(): Set { 28 | return setOf(CompatibilityFlags.MISSING_VALUES_AS_NULLS) 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/InvalidJsonPatchException.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.reidsync.kxjsonpatch 18 | 19 | /** 20 | * User: holograph 21 | * Date: 03/08/16 22 | */ 23 | class InvalidJsonPatchException : JsonPatchApplicationException { 24 | constructor(message: String) : super(message) {} 25 | 26 | constructor(message: String, cause: Throwable) : super(message, cause) {} 27 | 28 | constructor(cause: Throwable) : super(cause) {} 29 | } 30 | -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/JsonPatchApplicationException.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.reidsync.kxjsonpatch 18 | 19 | /** 20 | * User: holograph 21 | * Date: 03/08/16 22 | */ 23 | open class JsonPatchApplicationException : RuntimeException { 24 | constructor(message: String) : super(message) {} 25 | 26 | constructor(message: String, cause: Throwable) : super(message, cause) {} 27 | 28 | constructor(cause: Throwable) : super(cause) {} 29 | } 30 | -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/AddOperationTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.reidsync.kxjsonpatch 17 | 18 | import resources.testdata.TestData_ADD 19 | import kotlin.test.Test 20 | 21 | class AddOperationTest : AbstractTest() { 22 | //@org.junit.runners.Parameterized.Parameters 23 | override fun data(): Collection { 24 | return PatchTestCase.load(TestData_ADD) 25 | } 26 | 27 | @Test 28 | fun childTest() { 29 | test() 30 | } 31 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/resources/add-unsupported.json.kt: -------------------------------------------------------------------------------- 1 | package resources.testdata 2 | 3 | const val TestData_ADD_UNSUPPORTED: String = """ 4 | { 5 | "errors": [ 6 | { 7 | "op": [{ "op": "add", "path": "/a/b/c", "value": 1 }], 8 | "node": { "a": "b" }, 9 | "message": "jsonPatch.noSuchParent" 10 | }, 11 | { 12 | "op": [{ "op": "add", "path": "/~1", "value": 1 }], 13 | "node": [], 14 | "message": "jsonPatch.notAnIndex" 15 | }, 16 | { 17 | "op": [{ "op": "add", "path": "/3", "value": 1 }], 18 | "node": [ 1, 2 ], 19 | "message": "jsonPatch.noSuchIndex" 20 | }, 21 | { 22 | "op": [{ "op": "add", "path": "/-2", "value": 1 }], 23 | "node": [ 1, 2 ], 24 | "message": "jsonPatch.noSuchIndex" 25 | }, 26 | { 27 | "op": [{ "op": "add", "path": "/foo/f", "value": "bar" }], 28 | "node": { "foo": "bar" }, 29 | "message": "jsonPatch.parentNotContainer" 30 | } 31 | 32 | ], 33 | "ops": [ 34 | { 35 | "op": [{ "op": "add", "path": "", "value": null }], 36 | "node": {}, 37 | "expected": null 38 | } 39 | ] 40 | } 41 | """ -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/JsonPatchProcessor.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.reidsync.kxjsonpatch; 18 | 19 | 20 | import kotlinx.serialization.json.* 21 | 22 | interface JsonPatchProcessor { 23 | fun remove(path: List) 24 | fun replace(path: List, value: JsonElement) 25 | fun add(path: List, value: JsonElement) 26 | fun move(fromPath: List, toPath: List) 27 | fun copy(fromPath: List, toPath: List) 28 | fun test(path: List, value: JsonElement) 29 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/JsonPatchEditingContext.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.reidsync.kxjsonpatch; 18 | 19 | 20 | import kotlinx.serialization.json.* 21 | 22 | interface JsonPatchEditingContext { 23 | fun remove(path: List) 24 | fun replace(path: List, value: JsonElement) 25 | fun add(path: List, value: JsonElement) 26 | fun move(fromPath: List, toPath: List) 27 | fun copy(fromPath: List, toPath: List) 28 | fun test(path: List, value: JsonElement) 29 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/RemoveOperationTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.reidsync.kxjsonpatch 17 | 18 | import resources.testdata.TestData_REMOVE 19 | import kotlin.test.Test 20 | 21 | /** 22 | * @author ctranxuan (streamdata.io). 23 | */ 24 | class RemoveOperationTest : AbstractTest() { 25 | // @org.junit.runners.Parameterized.Parameters 26 | override fun data(): Collection { 27 | return PatchTestCase.load(TestData_REMOVE) 28 | } 29 | 30 | @Test 31 | fun childTest() { 32 | test() 33 | } 34 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/ReplaceOperationTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.reidsync.kxjsonpatch 17 | 18 | import resources.testdata.TestData_REPLACE 19 | import kotlin.test.Test 20 | 21 | /** 22 | * @author ctranxuan (streamdata.io). 23 | */ 24 | class ReplaceOperationTest : AbstractTest() { 25 | // @org.junit.runners.Parameterized.Parameters 26 | override fun data(): Collection { 27 | return PatchTestCase.load(TestData_REPLACE) 28 | } 29 | 30 | @Test 31 | fun childTest() { 32 | test() 33 | } 34 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/Rfc6902SamplesTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.reidsync.kxjsonpatch 17 | 18 | import resources.testdata.TestData_RFC6902_SAMPLES 19 | import kotlin.test.Test 20 | 21 | /** 22 | * @author ctranxuan (streamdata.io). 23 | */ 24 | class Rfc6902SamplesTest : AbstractTest() { 25 | // @org.junit.runners.Parameterized.Parameters 26 | override fun data(): Collection { 27 | return PatchTestCase.load(TestData_RFC6902_SAMPLES) 28 | } 29 | 30 | @Test 31 | fun childTest() { 32 | test() 33 | } 34 | } -------------------------------------------------------------------------------- /kotlin-json-patch/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | alias(libs.plugins.kotlinMultiplatform) 3 | alias(libs.plugins.androidLibrary) 4 | id("maven-publish.conventions") 5 | } 6 | 7 | group = "io.github.reidsync" 8 | version = "1.0.0" 9 | 10 | kotlin { 11 | jvm { 12 | // … 13 | } 14 | js(IR) { 15 | // … 16 | } 17 | ios() 18 | androidTarget { 19 | compilations.all { 20 | kotlinOptions { 21 | jvmTarget = "1.8" 22 | } 23 | } 24 | publishLibraryVariants("release", "debug") 25 | } 26 | 27 | listOf( 28 | iosX64(), 29 | iosArm64(), 30 | iosSimulatorArm64() 31 | ).forEach { 32 | it.binaries.framework { 33 | baseName = "sharedKotlinJsonPatch" 34 | isStatic = true 35 | } 36 | } 37 | 38 | sourceSets { 39 | commonMain.dependencies { 40 | //put your multiplatform dependencies here 41 | implementation(libs.kotlinx.serialization.json) 42 | } 43 | commonTest.dependencies { 44 | implementation(libs.kotlin.test) 45 | } 46 | } 47 | } 48 | 49 | android { 50 | namespace = "com.reidsync.kxjsonpatch" 51 | compileSdk = 34 52 | defaultConfig { 53 | minSdk = 23 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/resources/replace.json.kt: -------------------------------------------------------------------------------- 1 | package resources.testdata 2 | 3 | const val TestData_REPLACE: String = """ 4 | { 5 | "errors": [ 6 | { 7 | "op": [{ "op": "replace", "path": "/a" }], 8 | "node": { "a": 0 }, 9 | "message": "Missing value field" 10 | }, 11 | { 12 | "op": [{ "op": "replace", "path": "/x/y", "value": false }], 13 | "node": { "x": "a" } 14 | } 15 | ], 16 | "ops": [ 17 | { 18 | "op": [{ "op": "replace", "path": "", "value": false }], 19 | "node": { "x": { "a": "b", "y": {} } }, 20 | "expected": false 21 | }, 22 | { 23 | "op": [{ "op": "replace", "path": "/x/y", "value": "hello" }], 24 | "node": { "x": { "a": "b", "y": {} } }, 25 | "expected": { "x": { "a": "b", "y": "hello" } } 26 | }, 27 | { 28 | "op": [{ "op": "replace", "path": "/0/2", "value": "x" }], 29 | "node": [ [ "a", "b", "c"], "d", "e" ], 30 | "expected": [ [ "a", "b", "x" ], "d", "e" ] 31 | }, 32 | { 33 | "op": [{ "op": "replace", "path": "/x/0", "value": null }], 34 | "node": { "x": [ "y", "z" ], "foo": "bar" }, 35 | "expected": { "x": [ null, "z" ], "foo": "bar" } 36 | } 37 | ] 38 | } 39 | """ -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/resources/rfc6902-samples-unsupported.json.kt: -------------------------------------------------------------------------------- 1 | package resources.testdata 2 | 3 | const val TestData_RFC6902_SAMPLES_UNSUPPORTED: String = """ 4 | { 5 | "errors": [ 6 | { 7 | "message": "A.9. Testing a Value: Error", 8 | "op": [{ "op": "test", "path": "/baz", "value": "bar" }], 9 | "node": { "baz": "qux" } 10 | }, 11 | { 12 | "message": "A.15. Comparing Strings and Numbers", 13 | "op": [{"op": "test", "path": "/~01", "value": "10"}], 14 | "node": { 15 | "/": 9, 16 | "~1": 10 17 | } 18 | } 19 | ], 20 | "ops": [ 21 | { 22 | "message": "A.8. Testing a Value: Success", 23 | "op": [{ "op": "test", "path": "/baz", "value": "qux" }, 24 | { "op": "test", "path": "/foo/1", "value": 2 }], 25 | "node": { 26 | "baz": "qux", 27 | "foo": [ "a", 2, "c" ] 28 | } 29 | }, 30 | { 31 | "message": "A.14. ~ Escape Ordering", 32 | "op": [{"op": "test", "path": "/~01", "value": 10}], 33 | "node": { 34 | "/": 9, 35 | "~1": 10 36 | }, 37 | "expected": { 38 | "/": 9, 39 | "~1": 10 40 | } 41 | } 42 | ] 43 | } 44 | """ -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/JsLibSamplesTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.reidsync.kxjsonpatch 17 | 18 | import resources.testdata.TestData_JS_LIB_SAMPLES 19 | import kotlin.test.Test 20 | 21 | /** 22 | * @author ctranxuan (streamdata.io). 23 | * 24 | * These tests comes from JS JSON-Patch libraries ( 25 | * https://github.com/Starcounter-Jack/JSON-Patch/blob/master/test/spec/json-patch-tests/tests.json 26 | * https://github.com/cujojs/jiff/blob/master/test/json-patch-tests/tests.json) 27 | */ 28 | class JsLibSamplesTest : AbstractTest() { 29 | //@org.junit.runners.Parameterized.Parameters 30 | override fun data(): Collection { 31 | return PatchTestCase.load(TestData_JS_LIB_SAMPLES) 32 | } 33 | 34 | @Test 35 | fun childTest() { 36 | test() 37 | } 38 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/Operations.kt: -------------------------------------------------------------------------------- 1 | package com.reidsync.kxjsonpatch 2 | 3 | internal open class Operations { 4 | val ADD: Int = 0 5 | val REMOVE: Int = 1 6 | val REPLACE: Int = 2 7 | val MOVE: Int = 3 8 | val COPY: Int = 4 9 | val TEST: Int = 5 10 | 11 | open val ADD_name = "add" 12 | open val REMOVE_name = "remove" 13 | open val REPLACE_name = "replace" 14 | open val MOVE_name = "move" 15 | open val COPY_name = "copy" 16 | open val TEST_name = "test" 17 | private val OPS = mapOf( 18 | ADD_name to ADD, 19 | REMOVE_name to REMOVE, 20 | REPLACE_name to REPLACE, 21 | MOVE_name to MOVE, 22 | COPY_name to COPY, 23 | TEST_name to TEST) 24 | private val NAMES = mapOf( 25 | ADD to ADD_name, 26 | REMOVE to REMOVE_name, 27 | REPLACE to REPLACE_name, 28 | MOVE to MOVE_name, 29 | COPY to COPY_name, 30 | TEST to TEST_name) 31 | 32 | fun opFromName(rfcName: String): Int { 33 | val res=OPS.get(rfcName.toLowerCase()) 34 | if(res==null) throw InvalidJsonPatchException("unknown / unsupported operation $rfcName") 35 | return res 36 | } 37 | 38 | fun nameFromOp(operation: Int): String { 39 | val res= NAMES.get(operation) 40 | if(res==null) throw InvalidJsonPatchException("unknown / unsupported operation $operation") 41 | return res 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | agp = "8.2.0" 3 | kotlin = "1.9.20" 4 | compose = "1.5.4" 5 | compose-compiler = "1.5.4" 6 | compose-material3 = "1.1.2" 7 | androidx-activityCompose = "1.8.0" 8 | kotlinxSerializationJson = "1.5.1" 9 | 10 | [libraries] 11 | kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" } 12 | androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activityCompose" } 13 | compose-ui = { module = "androidx.compose.ui:ui", version.ref = "compose" } 14 | compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling", version.ref = "compose" } 15 | compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview", version.ref = "compose" } 16 | compose-foundation = { module = "androidx.compose.foundation:foundation", version.ref = "compose" } 17 | compose-material3 = { module = "androidx.compose.material3:material3", version.ref = "compose-material3" } 18 | kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinxSerializationJson" } 19 | 20 | [plugins] 21 | androidApplication = { id = "com.android.application", version.ref = "agp" } 22 | androidLibrary = { id = "com.android.library", version.ref = "agp" } 23 | kotlinAndroid = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } 24 | kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } 25 | kotlinCocoapods = { id = "org.jetbrains.kotlin.native.cocoapods", version.ref = "kotlin" } 26 | -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/NoopProcessor.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.reidsync.kxjsonpatch 18 | 19 | import kotlinx.serialization.json.JsonElement 20 | 21 | /** A JSON patch processor that does nothing, intended for testing and validation. */ 22 | class NoopProcessor : JsonPatchApplyProcessor() { 23 | companion object { 24 | val INSTANCE: NoopProcessor = NoopProcessor() 25 | } 26 | } 27 | 28 | class JsonPatchEditingContextTestImpl(var source: JsonElement): JsonPatchEditingContext { 29 | override fun remove(path: List) {} 30 | override fun replace(path: List, value: JsonElement) {} 31 | override fun add(path: List, value: JsonElement) {} 32 | override fun move(fromPath: List, toPath: List) {} 33 | override fun copy(fromPath: List, toPath: List) {} 34 | override fun test(path: List, value: JsonElement) {} 35 | } -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Use the latest 2.1 version of CircleCI pipeline process engine. 2 | # See: https://circleci.com/docs/configuration-reference 3 | version: 2.1 4 | executors: 5 | java17: 6 | docker: 7 | - image: 'cimg/android:2023.11' 8 | orbs: 9 | android: circleci/android@1.0.3 10 | 11 | # Define a job to be invoked later in a workflow. 12 | # See: https://circleci.com/docs/configuration-reference/#jobs 13 | jobs: 14 | build-android: 15 | executor: java17 16 | 17 | steps: 18 | - checkout 19 | - android/restore-build-cache 20 | - android/restore-gradle-cache 21 | - run: 22 | name: Run Android tests 23 | command: | 24 | java -version 25 | ./gradlew :kotlin-json-patch:cleanTestDebugUnitTest :kotlin-json-patch:testDebugUnitTest --tests "com.reidsync.kxjsonpatch.*" 26 | ./gradlew :kotlin-json-patch:cleanTestReleaseUnitTest :kotlin-json-patch:testReleaseUnitTest --tests "com.reidsync.kxjsonpatch.*" 27 | - android/save-gradle-cache 28 | - android/save-build-cache 29 | 30 | build-ios: 31 | macos: 32 | xcode: 15.0.0 33 | steps: 34 | - checkout 35 | - run: 36 | name: Run iOS tests 37 | command: ./gradlew :kotlin-json-patch:cleanIosSimulatorArm64Test :kotlin-json-patch:iosSimulatorArm64Test --tests "com.reidsync.kxjsonpatch.*" 38 | 39 | # Orchestrate jobs using workflows 40 | # See: https://circleci.com/docs/configuration-reference/#workflows 41 | workflows: 42 | build-all: 43 | jobs: 44 | - build-android 45 | - build-ios 46 | -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/resources/move.json.kt: -------------------------------------------------------------------------------- 1 | package resources.testdata 2 | 3 | const val TestData_MOVE: String = """ 4 | { 5 | "errors": [ 6 | { 7 | "op": [{ "op": "move", "from": "/a", "path": "/a/b" }], 8 | "node": {}, 9 | "message": "jsonPatch.noSuchPath" 10 | }, 11 | { 12 | "op": [{ "op": "move", "from": "/a", "path": "/b/c" }], 13 | "node": { "a": "b" }, 14 | "message": "jsonPatch.noSuchParent" 15 | }, 16 | { 17 | "op": [{ "op": "move", "path": "/b/c" }], 18 | "node": { "a": "b" }, 19 | "message": "Missing from field" 20 | } 21 | ], 22 | "ops": [ 23 | { 24 | "op": [{ "op": "move", "from": "/x/a", "path": "/x/b" }], 25 | "node": { "x": { "a": "helo" } }, 26 | "expected": { "x": { "b": "helo" } } 27 | }, 28 | { 29 | "op": [{ "op": "move", "from": "/x/a", "path": "/x/a" }], 30 | "node": { "x": { "a": "helo" } }, 31 | "expected": { "x": { "a": "helo" } } 32 | }, 33 | { 34 | "op": [{ "op": "move", "from": "/0", "path": "/0/x" }], 35 | "node": [ "victim", {}, {} ], 36 | "expected": [ { "x": "victim" }, {} ] 37 | }, 38 | { 39 | "op": [{ "op": "move", "from": "/0", "path": "/-" }], 40 | "node": [ 0, 1, 2 ], 41 | "expected": [ 1, 2, 0 ] 42 | }, 43 | { 44 | "op": [{ "op": "move", "from": "/a", "path": "/b/2" }], 45 | "node": { "a": "helo", "b": [ 1, 2, 3, 4 ] }, 46 | "expected": { "b": [ 1, 2, "helo", 3, 4 ] } 47 | } 48 | ] 49 | } 50 | """ -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/Diff.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.reidsync.kxjsonpatch 18 | 19 | import kotlinx.serialization.json.JsonElement 20 | import kotlinx.serialization.json.JsonNull 21 | import kotlin.jvm.JvmStatic 22 | 23 | internal class Diff { 24 | val operation: Int 25 | val path: MutableList 26 | val value: JsonElement 27 | val toPath: List //only to be used in move operation 28 | 29 | constructor(operation: Int, path: List, value: JsonElement) { 30 | this.operation = operation 31 | this.path = path.toMutableList() 32 | this.toPath= listOf() 33 | this.value = value 34 | } 35 | 36 | constructor(operation: Int, fromPath: List, toPath: List) { 37 | this.operation = operation 38 | this.path = fromPath.toMutableList() 39 | this.toPath = toPath 40 | this.value = JsonNull 41 | } 42 | 43 | companion object { 44 | 45 | @JvmStatic 46 | fun generateDiff(replace: Int, path: List, target: JsonElement): Diff { 47 | return Diff(replace, path, target) 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/JsonPatchApplyProcessor.kt: -------------------------------------------------------------------------------- 1 | package com.reidsync.kxjsonpatch 2 | 3 | import kotlinx.serialization.json.JsonElement 4 | import kotlinx.serialization.json.JsonNull 5 | 6 | /* 7 | * Copyright 2023 Reid Byun. 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | abstract class JsonPatchApplyProcessor(private val source: JsonElement = JsonNull) { 23 | var targetSource: JsonElement = source 24 | private set 25 | 26 | open fun setSource(changedSource: JsonElement) { 27 | targetSource = changedSource 28 | } 29 | } 30 | // 31 | //fun JsonPatchApplyProcessor.edit(actions: JsonPatchEditingContext.()->Unit) { 32 | // val context = JsonPatchEditingContextImpl(source = this.targetSource) 33 | // context.actions() 34 | // 35 | // this.setSource(context.source) 36 | //} 37 | 38 | fun JsonPatchApplyProcessor.edit(actions: JsonPatchEditingContext.()->Unit) { 39 | if (this is NoopProcessor) { // for test 40 | val context = JsonPatchEditingContextTestImpl(source = this.targetSource) 41 | context.actions() 42 | this.setSource(context.source) 43 | } 44 | else { 45 | val context = JsonPatchEditingContextImpl(source = this.targetSource) 46 | context.actions() 47 | this.setSource(context.source) 48 | } 49 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/JsonDiffTest2.kt: -------------------------------------------------------------------------------- 1 | package com.reidsync.kxjsonpatch 2 | 3 | import com.reidsync.kxjsonpatch.utils.GsonObjectMapper 4 | import kotlinx.serialization.json.JsonArray 5 | import kotlinx.serialization.json.JsonElement 6 | import kotlinx.serialization.json.jsonArray 7 | import kotlinx.serialization.json.jsonObject 8 | import resources.testdata.TestData_DIFF 9 | import kotlin.test.BeforeTest 10 | import kotlin.test.Test 11 | import kotlin.test.assertEquals 12 | 13 | /* 14 | * Copyright 2016 flipkart.com kjsonpatch. 15 | * 16 | * Licensed under the Apache License, Version 2.0 (the "License"); 17 | * you may not use this file except in compliance with the License. 18 | * You may obtain a copy of the License at 19 | * 20 | * http://www.apache.org/licenses/LICENSE-2.0 21 | * 22 | * Unless required by applicable law or agreed to in writing, software 23 | * distributed under the License is distributed on an "AS IS" BASIS, 24 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 25 | * See the License for the specific language governing permissions and 26 | * limitations under the License. 27 | */ /** 28 | * @author ctranxuan (streamdata.io). 29 | */ 30 | class JsonDiffTest2 { 31 | var objectMapper = GsonObjectMapper() 32 | lateinit var jsonNode: JsonArray 33 | @BeforeTest 34 | fun setUp() { 35 | jsonNode = objectMapper.readTree(TestData_DIFF).jsonArray 36 | } 37 | 38 | @Test 39 | fun testPatchAppliedCleanly() { 40 | for (i in 0 until jsonNode.size) { 41 | val first: JsonElement = jsonNode.get(i).jsonObject.get("first")!! 42 | val second: JsonElement = jsonNode.get(i).jsonObject.get("second")!! 43 | val patch: JsonArray = jsonNode.get(i).jsonObject.get("patch")!!.jsonArray 44 | val message: String = jsonNode.get(i).jsonObject.get("message").toString() 45 | println("Test # $i") 46 | println(first) 47 | println(second) 48 | println(patch) 49 | val secondPrime: JsonElement = JsonPatch.apply(patch, first) 50 | println(secondPrime) 51 | assertEquals(secondPrime, second, message) 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/Equator.kt: -------------------------------------------------------------------------------- 1 | package com.reidsync.kxjsonpatch.lcs 2 | /* 3 | * Licensed to the Apache Software Foundation (ASF) under one or more contributor license 4 | * agreements. See the NOTICE file distributed with this work for additional information regarding 5 | * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the 6 | * "License"); you may not use this file except in compliance with the License. You may obtain a 7 | * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable 8 | * law or agreed to in writing, software distributed under the License is distributed on an "AS IS" 9 | * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License 10 | * for the specific language governing permissions and limitations under the License. 11 | */ /** 12 | * An equation function, which determines equality between objects of type T. 13 | * 14 | * 15 | * It is the functional sibling of [java.util.Comparator]; [Equator] is to 16 | * [Object] as [java.util.Comparator] is to [java.lang.Comparable]. 17 | * 18 | * @param the types of object this [Equator] can evaluate. 19 | * @since 4.0 20 | * @version $Id: Equator.java 1540567 2013-11-10 22:19:29Z tn $ 21 | */ 22 | interface Equator { 23 | /** 24 | * Evaluates the two arguments for their equality. 25 | * 26 | * @param o1 the first object to be equated. 27 | * @param o2 the second object to be equated. 28 | * @return whether the two objects are equal. 29 | */ 30 | fun equate(o1: T, o2: T): Boolean 31 | 32 | /** 33 | * Calculates the hash for the object, based on the method of equality used in the equate 34 | * method. This is used for classes that delegate their [equals(Object)][Object.equals] method to an 35 | * Equator (and so must also delegate their [hashCode()][Object.hashCode] method), or for implementations 36 | * of org.apache.commons.collections4.map.HashedMap that use an Equator for the key objects. 37 | * 38 | * @param o the object to calculate the hash for. 39 | * @return the hash of the object. 40 | */ 41 | fun hash(o: T): Int 42 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/PatchTestCase.kt: -------------------------------------------------------------------------------- 1 | package com.reidsync.kxjsonpatch 2 | 3 | import com.reidsync.kxjsonpatch.utils.GsonObjectMapper 4 | import kotlinx.serialization.json.* 5 | 6 | /* 7 | * Copyright 2016 flipkart.com kjsonpatch. 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | class PatchTestCase private constructor( 22 | val isOperation: Boolean, 23 | node: JsonObject 24 | ) { 25 | private val node: JsonObject 26 | fun getNode(): JsonObject { 27 | return node 28 | } 29 | 30 | init { 31 | this.node = node 32 | } 33 | 34 | companion object { 35 | private val MAPPER = GsonObjectMapper() 36 | //fun load(fileName: String): Collection { 37 | fun load(testData: String): Collection { 38 | val tree: JsonElement = MAPPER.readTree(testData) 39 | val result: MutableList = ArrayList() 40 | for (node in tree.jsonObject.get("errors")!!.jsonArray) { 41 | if (isEnabled(node)) { 42 | result.add(PatchTestCase(false, node.jsonObject)) 43 | } 44 | } 45 | for (node in tree.jsonObject.get("ops")!!.jsonArray) { 46 | if (isEnabled(node)) { 47 | result.add(PatchTestCase(true, node.jsonObject)) 48 | } 49 | } 50 | return result 51 | } 52 | 53 | private fun isEnabled(node: JsonElement): Boolean { 54 | val disabled: JsonElement? = node.jsonObject.get("disabled") 55 | return (disabled == null || !disabled.jsonPrimitive.boolean) 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/DeleteCommand.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.reidsync.kxjsonpatch.lcs 18 | 19 | /** 20 | * Command representing the deletion of one object of the first sequence. 21 | * 22 | * 23 | * When one object of the first sequence has no corresponding object in the 24 | * second sequence at the right place, the [edit script][EditScript] 25 | * transforming the first sequence into the second sequence uses an instance of 26 | * this class to represent the deletion of this object. The objects embedded in 27 | * these type of commands always come from the first sequence. 28 | * 29 | * @see SequencesComparator 30 | * 31 | * @see EditScript 32 | * 33 | * 34 | * @since 4.0 35 | * @version $Id: DeleteCommand.java 1477760 2013-04-30 18:34:03Z tn $ 36 | */ 37 | class DeleteCommand 38 | /** 39 | * Simple constructor. Creates a new instance of [DeleteCommand]. 40 | * 41 | * @param object the object of the first sequence that should be deleted 42 | */ 43 | (`object`: T) : EditCommand(`object`) { 44 | /** 45 | * Accept a visitor. When a `DeleteCommand` accepts a visitor, it calls 46 | * its [visitDeleteCommand][CommandVisitor.visitDeleteCommand] method. 47 | * 48 | * @param visitor the visitor to be accepted 49 | */ 50 | override fun accept(visitor: CommandVisitor?) { 51 | visitor?.visitDeleteCommand(`object`) 52 | } 53 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/InsertCommand.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.reidsync.kxjsonpatch.lcs 18 | 19 | /** 20 | * Command representing the insertion of one object of the second sequence. 21 | * 22 | * 23 | * When one object of the second sequence has no corresponding object in the 24 | * first sequence at the right place, the [edit script][EditScript] 25 | * transforming the first sequence into the second sequence uses an instance of 26 | * this class to represent the insertion of this object. The objects embedded in 27 | * these type of commands always come from the second sequence. 28 | * 29 | * @see SequencesComparator 30 | * 31 | * @see EditScript 32 | * 33 | * 34 | * @since 4.0 35 | * @version $Id: InsertCommand.java 1477760 2013-04-30 18:34:03Z tn $ 36 | */ 37 | class InsertCommand 38 | /** 39 | * Simple constructor. Creates a new instance of InsertCommand 40 | * 41 | * @param object the object of the second sequence that should be inserted 42 | */ 43 | (`object`: T) : EditCommand(`object`) { 44 | /** 45 | * Accept a visitor. When an `InsertCommand` accepts a visitor, 46 | * it calls its [visitInsertCommand][CommandVisitor.visitInsertCommand] 47 | * method. 48 | * 49 | * @param visitor the visitor to be accepted 50 | */ 51 | 52 | override fun accept(visitor: CommandVisitor?) { 53 | visitor?.visitInsertCommand(`object`) 54 | } 55 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/KeepCommand.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.reidsync.kxjsonpatch.lcs 18 | 19 | /** 20 | * Command representing the keeping of one object present in both sequences. 21 | * 22 | * 23 | * When one object of the first sequence `equals` another objects in 24 | * the second sequence at the right place, the [edit script][EditScript] 25 | * transforming the first sequence into the second sequence uses an instance of 26 | * this class to represent the keeping of this object. The objects embedded in 27 | * these type of commands always come from the first sequence. 28 | * 29 | * @see SequencesComparator 30 | * 31 | * @see EditScript 32 | * 33 | * 34 | * @since 4.0 35 | * @version $Id: KeepCommand.java 1477760 2013-04-30 18:34:03Z tn $ 36 | */ 37 | class KeepCommand 38 | /** 39 | * Simple constructor. Creates a new instance of KeepCommand 40 | * 41 | * @param object the object belonging to both sequences (the object is a 42 | * reference to the instance in the first sequence which is known 43 | * to be equal to an instance in the second sequence) 44 | */ 45 | (`object`: T) : EditCommand(`object`) { 46 | /** 47 | * Accept a visitor. When a `KeepCommand` accepts a visitor, it 48 | * calls its [visitKeepCommand][CommandVisitor.visitKeepCommand] method. 49 | * 50 | * @param visitor the visitor to be accepted 51 | */ 52 | 53 | override fun accept(visitor: CommandVisitor?) { 54 | visitor?.visitKeepCommand(`object`) 55 | } 56 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/AbstractTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.reidsync.kxjsonpatch 17 | 18 | import kotlinx.serialization.json.JsonElement 19 | import kotlinx.serialization.json.JsonObject 20 | import kotlinx.serialization.json.jsonArray 21 | import kotlin.test.DefaultAsserter.fail 22 | import kotlin.test.Test 23 | import kotlin.test.assertEquals 24 | import kotlin.test.assertFails 25 | 26 | //@org.junit.runner.RunWith(org.junit.runners.Parameterized::class) 27 | abstract class AbstractTest { 28 | abstract fun data(): Collection 29 | 30 | @Test 31 | fun test() { 32 | val testData = data() 33 | for (p in testData) { 34 | if (p.isOperation) { 35 | testOpertaion(p) 36 | } else { 37 | testError(p) 38 | } 39 | } 40 | } 41 | 42 | private fun testOpertaion(p: PatchTestCase) { 43 | val node: JsonObject = p.getNode() 44 | val first: JsonElement = node.get("node")!! 45 | val second: JsonElement = node.get("expected")!! 46 | val patch: JsonElement = node.get("op")!! 47 | val message = if (node.containsKey("message")) node.get("message").toString() else "" 48 | val secondPrime: JsonElement = 49 | JsonPatch.apply(patch.jsonArray, first) 50 | assertEquals(secondPrime, second, message) 51 | } 52 | 53 | private fun testError(p:PatchTestCase) { 54 | val node: JsonObject = p.getNode() 55 | val first: JsonElement = node.get("node")!! 56 | val patch: JsonElement = node.get("op")!! 57 | try { 58 | JsonPatch.apply(patch.jsonArray, first) 59 | assertFails { 60 | fail("Failure expected: " + node.get("message")) 61 | } 62 | } 63 | catch (e: Exception) { 64 | println("-> AssertFails with: ${e.message}") 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/resources/add.json.kt: -------------------------------------------------------------------------------- 1 | package resources.testdata 2 | 3 | const val TestData_ADD: String = """ 4 | { 5 | "errors": [ 6 | { 7 | "op": [{ "op": "add", "path": "/a" }], 8 | "node": {}, 9 | "message": "Missing value field on add operation" 10 | } 11 | ], 12 | "ops": [ 13 | { 14 | "op": [{ "op": "add", "path": "/a", "value": "b" }], 15 | "node": {}, 16 | "expected": { "a": "b" } 17 | }, 18 | { 19 | "op": [{ "op": "add", "path": "/a", "value": 1 }], 20 | "node": { "a": "b" }, 21 | "expected": { "a": 1 } 22 | }, 23 | { 24 | "op": [{ "op": "add", "path": "/array/-", "value": 1 }], 25 | "node": { "array": [ 2, null, {}, 1 ] }, 26 | "expected": { "array": [ 2, null, {}, 1, 1 ] } 27 | }, 28 | { 29 | "op": [{ "op": "add", "path": "/array/2", "value": "hello" }], 30 | "node": { "array": [ 2, null, {}, 1] }, 31 | "expected": { "array": [ 2, null, "hello", {}, 1 ] } 32 | }, 33 | { 34 | "op": [{ "op": "add", "path": "/obj/inner/b", "value": [ 1, 2 ] }], 35 | "node": { 36 | "obj": { 37 | "inner": { 38 | "a": "hello" 39 | } 40 | } 41 | }, 42 | "expected": { 43 | "obj": { 44 | "inner": { 45 | "a": "hello", 46 | "b": [ 1, 2 ] 47 | } 48 | } 49 | } 50 | }, 51 | { 52 | "op": [{ "op": "add", "path": "/obj/inner/b", "value": [ 1, 2 ] }], 53 | "node": { 54 | "obj": { 55 | "inner": { 56 | "a": "hello", 57 | "b": "world" 58 | } 59 | } 60 | }, 61 | "expected": { 62 | "obj": { 63 | "inner": { 64 | "a": "hello", 65 | "b": [ 1, 2 ] 66 | } 67 | } 68 | } 69 | }, 70 | { 71 | "message": "support of path with /", 72 | "op": [{ "op": "add", "path": "/b~1c~1d/3", "value": 4 }], 73 | "node": { "b/c/d": [1, 2, 3] }, 74 | "expected": { "b/c/d": [1, 2, 3, 4] } 75 | } 76 | ] 77 | } 78 | """ -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/ListUtils.kt: -------------------------------------------------------------------------------- 1 | package com.reidsync.kxjsonpatch.lcs 2 | 3 | /** 4 | * code extracted from Apache Commons Collections 4.1 5 | * Created by daely on 7/22/2016. 6 | */ 7 | object ListUtils { 8 | //----------------------------------------------------------------------- 9 | /** 10 | * Returns the longest common subsequence (LCS) of two sequences (lists). 11 | * 12 | * @param the element type 13 | * @param a the first list 14 | * @param b the second list 15 | * @return the longest common subsequence 16 | * @throws NullPointerException if either list is `null` 17 | * @since 4.0 18 | */ 19 | fun longestCommonSubsequence(a: List?, b: List?): List { 20 | return longestCommonSubsequence(a, b, DefaultEquator.defaultEquator()) 21 | } 22 | 23 | /** 24 | * Returns the longest common subsequence (LCS) of two sequences (lists). 25 | * 26 | * @param the element type 27 | * @param a the first list 28 | * @param b the second list 29 | * @param equator the equator used to test object equality 30 | * @return the longest common subsequence 31 | * @throws NullPointerException if either list or the equator is `null` 32 | * @since 4.0 33 | */ 34 | fun longestCommonSubsequence( 35 | a: List?, b: List?, 36 | equator: Equator? 37 | ): List { 38 | if (a == null || b == null) { 39 | throw NullPointerException("List must not be null") 40 | } 41 | if (equator == null) { 42 | throw NullPointerException("Equator must not be null") 43 | } 44 | val comparator: SequencesComparator = 45 | SequencesComparator(a, b, equator) 46 | val script: EditScript = comparator.getScript() 47 | val visitor = LcsVisitor() 48 | script.visit(visitor) 49 | return visitor.subSequence 50 | } 51 | 52 | /** 53 | * A helper class used to construct the longest common subsequence. 54 | */ 55 | private class LcsVisitor : CommandVisitor { 56 | private val sequence: ArrayList 57 | 58 | init { 59 | sequence = ArrayList() 60 | } 61 | 62 | override fun visitInsertCommand(`object`: E) {} 63 | override fun visitDeleteCommand(`object`: E) {} 64 | override fun visitKeepCommand(`object`: E) { 65 | sequence.add(`object`) 66 | } 67 | 68 | val subSequence: List 69 | get() = sequence 70 | } 71 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/MoveOperationTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.reidsync.kxjsonpatch 17 | 18 | import com.reidsync.kxjsonpatch.utils.GsonObjectMapper 19 | import kotlinx.serialization.json.JsonElement 20 | import resources.testdata.TestData_MOVE 21 | import kotlin.test.Test 22 | import kotlin.test.assertEquals 23 | 24 | /** 25 | * @author ctranxuan (streamdata.io). 26 | */ 27 | class MoveOperationTest : AbstractTest() { 28 | private val MAPPER = GsonObjectMapper() 29 | //@org.junit.runners.Parameterized.Parameters 30 | override fun data(): Collection { 31 | return PatchTestCase.load(TestData_MOVE) 32 | } 33 | 34 | @Test 35 | fun testMoveValueGeneratedHasNoValue() { 36 | val jsonNode1: JsonElement = 37 | MAPPER.readTree("{ \"foo\": { \"bar\": \"baz\", \"waldo\": \"fred\" }, \"qux\": { \"corge\": \"grault\" } }") 38 | val jsonNode2: JsonElement = 39 | MAPPER.readTree("{ \"foo\": { \"bar\": \"baz\" }, \"qux\": { \"corge\": \"grault\", \"thud\": \"fred\" } }") 40 | val patch: JsonElement = 41 | MAPPER.readTree("[{\"op\":\"move\",\"from\":\"/foo/waldo\",\"path\":\"/qux/thud\"}]") 42 | val diff: JsonElement = JsonDiff.asJson(jsonNode1, jsonNode2) 43 | assertEquals(diff, patch) 44 | } 45 | 46 | 47 | @Test 48 | fun testMoveArrayGeneratedHasNoValue() { 49 | val jsonNode1: JsonElement = 50 | MAPPER.readTree("{ \"foo\": [ \"all\", \"grass\", \"cows\", \"eat\" ] }") 51 | val jsonNode2: JsonElement = 52 | MAPPER.readTree("{ \"foo\": [ \"all\", \"cows\", \"eat\", \"grass\" ] }") 53 | val patch: JsonElement = 54 | MAPPER.readTree("[{\"op\":\"move\",\"from\":\"/foo/1\",\"path\":\"/foo/3\"}]") 55 | val diff: JsonElement = JsonDiff.asJson(jsonNode1, jsonNode2) 56 | assertEquals(diff, patch) 57 | // assertEquals( 58 | // diff, 59 | // org.hamcrest.CoreMatchers.equalTo(patch) 60 | // ) 61 | } 62 | 63 | @Test 64 | fun childTest() { 65 | test() 66 | } 67 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/CompatibilityTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.reidsync.kxjsonpatch 17 | 18 | import com.reidsync.kxjsonpatch.utils.GsonObjectMapper 19 | import kotlinx.serialization.json.JsonElement 20 | import kotlinx.serialization.json.JsonObject 21 | import kotlin.test.BeforeTest 22 | import kotlin.test.Test 23 | import kotlin.test.assertEquals 24 | 25 | class CompatibilityTest { 26 | var mapper: GsonObjectMapper = GsonObjectMapper() 27 | var addNodeWithMissingValue: JsonElement = mapper.readTree("[{\"op\":\"add\",\"path\":\"a\"}]") 28 | var replaceNodeWithMissingValue: JsonElement = mapper.readTree("[{\"op\":\"replace\",\"path\":\"a\"}]") 29 | 30 | @BeforeTest 31 | fun setUp() { 32 | mapper = GsonObjectMapper() 33 | addNodeWithMissingValue = mapper.readTree("[{\"op\":\"add\",\"path\":\"a\"}]") 34 | replaceNodeWithMissingValue = mapper.readTree("[{\"op\":\"replace\",\"path\":\"a\"}]") 35 | } 36 | 37 | @Test 38 | fun withFlagAddShouldTreatMissingValuesAsNulls() { 39 | val expected: JsonElement = mapper.readTree("{\"a\":null}") 40 | val result: JsonElement = JsonPatch.apply( 41 | addNodeWithMissingValue, 42 | JsonObject(emptyMap()), 43 | setOf(CompatibilityFlags.MISSING_VALUES_AS_NULLS) 44 | ) 45 | assertEquals(result, expected) 46 | } 47 | 48 | @Test 49 | fun withFlagAddNodeWithMissingValueShouldValidateCorrectly() { 50 | JsonPatch.validate( 51 | addNodeWithMissingValue, 52 | setOf(CompatibilityFlags.MISSING_VALUES_AS_NULLS) 53 | ) 54 | } 55 | 56 | @Test 57 | fun withFlagReplaceShouldTreatMissingValuesAsNull() { 58 | val source: JsonElement = mapper.readTree("{\"a\":\"test\"}") 59 | val expected: JsonElement = mapper.readTree("{\"a\":null}") 60 | val result: JsonElement = JsonPatch.apply( 61 | replaceNodeWithMissingValue, 62 | source, 63 | setOf(CompatibilityFlags.MISSING_VALUES_AS_NULLS) 64 | ) 65 | assertEquals( 66 | result, 67 | expected 68 | ) 69 | } 70 | 71 | @Test 72 | fun withFlagReplaceNodeWithMissingValueShouldValidateCorrectly() { 73 | JsonPatch.validate( 74 | addNodeWithMissingValue, 75 | setOf(CompatibilityFlags.MISSING_VALUES_AS_NULLS) 76 | ) 77 | } 78 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/ApiTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.reidsync.kxjsonpatch 17 | 18 | import com.reidsync.kxjsonpatch.utils.GsonObjectMapper 19 | import kotlinx.serialization.json.JsonElement 20 | import kotlinx.serialization.json.jsonArray 21 | import kotlin.test.Test 22 | import kotlin.test.assertFailsWith 23 | 24 | class ApiTest { 25 | @Test 26 | fun applyingNonArrayPatchShouldThrowAnException() { 27 | assertFailsWith { 28 | val objectMapper = GsonObjectMapper() 29 | val invalid: JsonElement = objectMapper.readTree("[{\"not\": \"a patch\"}]") 30 | val to: JsonElement = objectMapper.readTree("{\"a\":1}") 31 | JsonPatch.apply(invalid.jsonArray, to) 32 | } 33 | } 34 | 35 | @Test 36 | fun applyingAnInvalidArrayShouldThrowAnException() { 37 | assertFailsWith { 38 | val objectMapper = GsonObjectMapper() 39 | val invalid: JsonElement = objectMapper.readTree("[1, 2, 3, 4, 5]") 40 | val to: JsonElement = objectMapper.readTree("{\"a\":1}") 41 | JsonPatch.apply(invalid.jsonArray, to) 42 | } 43 | } 44 | 45 | @Test 46 | fun applyingAPatchWithAnInvalidOperationShouldThrowAnException() { 47 | assertFailsWith { 48 | val objectMapper = GsonObjectMapper() 49 | val invalid: JsonElement = objectMapper.readTree("[{\"op\": \"what\"}]") 50 | val to: JsonElement = objectMapper.readTree("{\"a\":1}") 51 | JsonPatch.apply(invalid.jsonArray, to) 52 | } 53 | } 54 | 55 | @Test 56 | fun validatingNonArrayPatchShouldThrowAnException() { 57 | assertFailsWith { 58 | val objectMapper = GsonObjectMapper() 59 | val invalid: JsonElement = objectMapper.readTree("{\"not\": \"a patch\"}") 60 | JsonPatch.validate(invalid) 61 | } 62 | } 63 | 64 | @Test 65 | fun validatingAnInvalidArrayShouldThrowAnException() { 66 | assertFailsWith { 67 | val objectMapper = GsonObjectMapper() 68 | val invalid: JsonElement = objectMapper.readTree("[1, 2, 3, 4, 5]") 69 | JsonPatch.validate(invalid) 70 | } 71 | } 72 | 73 | @Test 74 | fun validatingAPatchWithAnInvalidOperationShouldThrowAnException() { 75 | assertFailsWith { 76 | val objectMapper = GsonObjectMapper() 77 | val invalid: JsonElement = objectMapper.readTree("[{\"op\": \"what\"}]") 78 | JsonPatch.validate(invalid) 79 | } 80 | } 81 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/EditCommand.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.reidsync.kxjsonpatch.lcs 18 | 19 | /** 20 | * Abstract base class for all commands used to transform an objects sequence 21 | * into another one. 22 | * 23 | * 24 | * When two objects sequences are compared through the 25 | * [SequencesComparator.getScript] method, 26 | * the result is provided has a [script][EditScript] containing the commands 27 | * that progressively transform the first sequence into the second one. 28 | * 29 | * 30 | * There are only three types of commands, all of which are subclasses of this 31 | * abstract class. Each command is associated with one object belonging to at 32 | * least one of the sequences. These commands are [ InsertCommand][InsertCommand] which correspond to an object of the second sequence being 33 | * inserted into the first sequence, [DeleteCommand] which 34 | * correspond to an object of the first sequence being removed and 35 | * [KeepCommand] which correspond to an object of the first 36 | * sequence which `equals` an object in the second sequence. It is 37 | * guaranteed that comparison is always performed this way (i.e. the 38 | * `equals` method of the object from the first sequence is used and 39 | * the object passed as an argument comes from the second sequence) ; this can 40 | * be important if subclassing is used for some elements in the first sequence 41 | * and the `equals` method is specialized. 42 | * 43 | * @see SequencesComparator 44 | * 45 | * @see EditScript 46 | * 47 | * 48 | * @since 4.0 49 | * @version $Id: EditCommand.java 1477760 2013-04-30 18:34:03Z tn $ 50 | */ 51 | abstract class EditCommand 52 | /** 53 | * Simple constructor. Creates a new instance of EditCommand 54 | * 55 | * @param object reference to the object associated with this command, this 56 | * refers to an element of one of the sequences being compared 57 | */ protected constructor( 58 | /** Object on which the command should be applied. */ 59 | protected val `object`: T 60 | ) { 61 | /** 62 | * Returns the object associated with this command. 63 | * 64 | * @return the object on which the command is applied 65 | */ 66 | 67 | /** 68 | * Accept a visitor. 69 | * 70 | * 71 | * This method is invoked for each commands belonging to 72 | * an [EditScript], in order to implement the visitor design pattern 73 | * 74 | * @param visitor the visitor to be accepted 75 | */ 76 | abstract fun accept(visitor: CommandVisitor?) 77 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/DefaultEquator.kt: -------------------------------------------------------------------------------- 1 | package com.reidsync.kxjsonpatch.lcs 2 | 3 | 4 | /* 5 | * Licensed to the Apache Software Foundation (ASF) under one or more 6 | * contributor license agreements. See the NOTICE file distributed with 7 | * this work for additional information regarding copyright ownership. 8 | * The ASF licenses this file to You under the Apache License, Version 2.0 9 | * (the "License"); you may not use this file except in compliance with 10 | * the License. You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | 22 | /* 23 | * Licensed to the Apache Software Foundation (ASF) under one or more 24 | * contributor license agreements. See the NOTICE file distributed with 25 | * this work for additional information regarding copyright ownership. 26 | * The ASF licenses this file to You under the Apache License, Version 2.0 27 | * (the "License"); you may not use this file except in compliance with 28 | * the License. You may obtain a copy of the License at 29 | * 30 | * http://www.apache.org/licenses/LICENSE-2.0 31 | * 32 | * Unless required by applicable law or agreed to in writing, software 33 | * distributed under the License is distributed on an "AS IS" BASIS, 34 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 35 | * See the License for the specific language governing permissions and 36 | * limitations under the License. 37 | */ 38 | /** 39 | * Default [Equator] implementation. 40 | * 41 | * @param the types of object this [Equator] can evaluate. 42 | * @since 4.0 43 | * @version $Id: DefaultEquator.java 1543950 2013-11-20 21:13:35Z tn $ 44 | */ 45 | class DefaultEquator 46 | /** 47 | * Restricted constructor. 48 | */ 49 | private constructor() : Equator { 50 | /** 51 | * {@inheritDoc} Delegates to [Object.equals]. 52 | */ 53 | override fun equate(o1: T, o2: T): Boolean { 54 | return o1 === o2 || o1 != null && o1 == o2 55 | } 56 | 57 | /** 58 | * {@inheritDoc} 59 | * 60 | * @return `o.hashCode()` if `o` is non- 61 | * `null`, else [.HASHCODE_NULL]. 62 | */ 63 | override fun hash(o: T): Int { 64 | return o?.hashCode() ?: HASHCODE_NULL 65 | } 66 | 67 | private fun readResolve(): Any { 68 | return INSTANCE 69 | } 70 | 71 | companion object { 72 | /** Serial version UID */ 73 | private const val serialVersionUID = 825802648423525485L 74 | 75 | /** Static instance */ 76 | // the static instance works for all types 77 | val INSTANCE: DefaultEquator<*> = DefaultEquator() 78 | 79 | /** 80 | * Hashcode used for `null` objects. 81 | */ 82 | const val HASHCODE_NULL = -1 83 | 84 | /** 85 | * Factory returning the typed singleton instance. 86 | * 87 | * @param the object type 88 | * @return the singleton instance 89 | */ 90 | // the static instance works for all types 91 | fun defaultEquator(): DefaultEquator { 92 | return INSTANCE as DefaultEquator 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/TestDataGenerator.kt: -------------------------------------------------------------------------------- 1 | package com.reidsync.kxjsonpatch 2 | 3 | import kotlinx.serialization.json.JsonArray 4 | import kotlinx.serialization.json.JsonElement 5 | import kotlinx.serialization.json.JsonObject 6 | import kotlinx.serialization.json.JsonPrimitive 7 | import kotlin.random.Random 8 | 9 | /* 10 | * Copyright 2016 flipkart.com kjsonpatch. 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | */ /** 24 | * User: gopi.vishwakarma 25 | * Date: 05/08/14 26 | */ 27 | object TestDataGenerator { 28 | private val random = Random(Int.MAX_VALUE) 29 | private val name: List = arrayListOf("summers", "winters", "autumn", "spring", "rainy") 30 | private val age: List = arrayListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) 31 | private val gender: List = arrayListOf("male", "female") 32 | private val country: List = arrayListOf( 33 | "india", 34 | "aus", 35 | "nz", 36 | "sl", 37 | "rsa", 38 | "wi", 39 | "eng", 40 | "bang", 41 | "pak" 42 | ) 43 | private val friends: List = arrayListOf( 44 | "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", 45 | "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", 46 | "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" 47 | ) 48 | 49 | fun generate(count: Int): JsonElement { 50 | var jsonNode: JsonArray = JsonArray(emptyList()) 51 | for (i in 0 until count) { 52 | var objectNode: JsonObject = JsonObject(emptyMap()) 53 | objectNode.addProperty( 54 | "name", 55 | name[random.nextInt(name.size)] 56 | ) 57 | objectNode.addProperty( 58 | "age", 59 | age[random.nextInt(age.size)] 60 | ) 61 | objectNode.addProperty( 62 | "gender", 63 | gender[random.nextInt(gender.size)] 64 | ) 65 | val countryNode: JsonArray = getArrayNode( 66 | country.subList( 67 | random.nextInt( 68 | country.size / 2 69 | ), country.size / 2 + random.nextInt(country.size / 2) 70 | ) 71 | ) 72 | objectNode = objectNode.add("country", countryNode) 73 | val friendNode: JsonArray = getArrayNode( 74 | friends.subList( 75 | random.nextInt( 76 | friends.size / 2 77 | ), friends.size / 2 + random.nextInt(friends.size / 2) 78 | ) 79 | ) 80 | objectNode = objectNode.add("friends", friendNode) 81 | jsonNode = jsonNode.add(objectNode) 82 | } 83 | return jsonNode 84 | } 85 | 86 | 87 | private fun getArrayNode(args: List): JsonArray { 88 | val countryNode: JsonArray = JsonArray(emptyList()) 89 | for (arg in args) { 90 | countryNode.add(JsonPrimitive(arg)) 91 | } 92 | return countryNode 93 | } 94 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/resources/js-libs-samples-unsupported.json.kt: -------------------------------------------------------------------------------- 1 | package resources.testdata 2 | 3 | const val TestData_JS_LIB_SAMPLES_UNSUPPORTED: String = """ 4 | { 5 | "errors": [ 6 | { "node": ["foo", "bar"], 7 | "op": [{"op": "test", "path": "/1e0", "value": "bar"}], 8 | "message": "test op shouldn't get array element 1" }, 9 | 10 | { "node": {"foo": {"bar": [1, 2, 5, 4]}}, 11 | "op": [{"op": "test", "path": "/foo", "value": [1, 2]}], 12 | "message": "test op should fail" } 13 | 14 | ], 15 | "ops": [ 16 | { "message": "test against implementation-specific numeric parsing", 17 | "node": {"1e0": "foo"}, 18 | "op": [{"op": "test", "path": "/1e0", "value": "foo"}], 19 | "expected": {"1e0": "foo"} }, 20 | 21 | { "message": "spurious patch properties", 22 | "node": {"foo": 1}, 23 | "op": [{"op": "test", "path": "/foo", "value": 1, "spurious": 1}], 24 | "expected": {"foo": 1} }, 25 | 26 | { "node": {"foo": null}, 27 | "op": [{"op": "test", "path": "/foo", "value": null}], 28 | "message": "null value should be valid obj property" }, 29 | 30 | { "node": {"foo": null}, 31 | "op": [{"op": "move", "from": "/foo", "path": "/bar"}], 32 | "expected": {"bar": null}, 33 | "message": "null value should be valid obj property to be moved" }, 34 | 35 | { "node": {"foo": null}, 36 | "op": [{"op": "copy", "from": "/foo", "path": "/bar"}], 37 | "expected": {"foo": null, "bar": null}, 38 | "message": "null value should be valid obj property to be copied" }, 39 | 40 | { "node": {"foo": {"foo": 1, "bar": 2}}, 41 | "op": [{"op": "test", "path": "/foo", "value": {"bar": 2, "foo": 1}}], 42 | "message": "test should pass despite rearrangement" }, 43 | 44 | { "node": {"foo": [{"foo": 1, "bar": 2}]}, 45 | "op": [{"op": "test", "path": "/foo", "value": [{"bar": 2, "foo": 1}]}], 46 | "message": "test should pass despite (nested) rearrangement" }, 47 | 48 | { "node": {"foo": {"bar": [1, 2, 5, 4]}}, 49 | "op": [{"op": "test", "path": "/foo", "value": {"bar": [1, 2, 5, 4]}}], 50 | "message": "test should pass - no error" }, 51 | 52 | { "message": "Whole document", 53 | "node": { "foo": 1 }, 54 | "op": [{"op": "test", "path": "", "value": {"foo": 1}}], 55 | "disabled": true }, 56 | 57 | { "message": "Empty-string element", 58 | "node": { "": 1 }, 59 | "op": [{"op": "test", "path": "/", "value": 1}] }, 60 | 61 | { "node": { 62 | "foo": ["bar", "baz"], 63 | "": 0, 64 | "a/b": 1, 65 | "c%d": 2, 66 | "e^f": 3, 67 | "g|h": 4, 68 | "i\\j": 5, 69 | "k\"l": 6, 70 | " ": 7, 71 | "m~n": 8 72 | }, 73 | "op": [{"op": "test", "path": "/foo", "value": ["bar", "baz"]}, 74 | {"op": "test", "path": "/foo/0", "value": "bar"}, 75 | {"op": "test", "path": "/", "value": 0}, 76 | {"op": "test", "path": "/a~1b", "value": 1}, 77 | {"op": "test", "path": "/c%d", "value": 2}, 78 | {"op": "test", "path": "/e^f", "value": 3}, 79 | {"op": "test", "path": "/g|h", "value": 4}, 80 | {"op": "test", "path": "/i\\j", "value": 5}, 81 | {"op": "test", "path": "/k\"l", "value": 6}, 82 | {"op": "test", "path": "/ ", "value": 7}, 83 | {"op": "test", "path": "/m~0n", "value": 8}] }, 84 | 85 | { "node": {"baz": [{"qux": "hello"}], "bar": 1}, 86 | "op": [{"op": "copy", "from": "/baz/0", "path": "/boo"}], 87 | "expected": {"baz":[{"qux":"hello"}],"bar":1,"boo":{"qux":"hello"}} }, 88 | 89 | { "message": "replacing the root of the document is possible with add", 90 | "node": {"foo": "bar"}, 91 | "op": [{"op": "add", "path": "", "value": {"baz": "qux"}}], 92 | "expected": {"baz":"qux"}}, 93 | ] 94 | } 95 | """ -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/JsonElementExtensions.kt: -------------------------------------------------------------------------------- 1 | package com.reidsync.kxjsonpatch 2 | 3 | import kotlinx.serialization.json.* 4 | 5 | /* 6 | * Copyright 2023 Reid Byun. 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /* 22 | * JsonElement Extensions 23 | * */ 24 | 25 | fun JsonElement.apply(patch: JsonElement): JsonElement { 26 | return JsonPatch.apply(patch, this) 27 | } 28 | 29 | fun JsonElement.generatePatch(with: JsonElement): JsonElement { 30 | return JsonDiff.asJson(this, with) 31 | } 32 | 33 | internal fun JsonElement.isContainerNode(): Boolean { 34 | return this is JsonArray || this is JsonObject 35 | } 36 | 37 | internal fun JsonElement.deepCopy(): JsonElement { 38 | return when(this) { 39 | is JsonArray -> this.jsonArray.copy {} 40 | is JsonObject -> this.jsonObject.copy {} 41 | is JsonNull -> JsonNull // An order of checking type between JsonNull and JsonPrimitive makes difference. 42 | is JsonPrimitive -> this /* Todo check */ 43 | else -> this /* Todo check */ 44 | } 45 | } 46 | 47 | /* 48 | * JsonArray Extensions 49 | * */ 50 | internal fun JsonArray.add(value_: JsonElement?): JsonArray { 51 | val value=value_ ?: JsonNull 52 | return copy { add(value) } 53 | } 54 | 55 | internal fun JsonArray.insert(index: Int, value_: JsonElement?): JsonArray { 56 | val value=value_ ?: JsonNull 57 | return if(index>=size) { 58 | this.add(value) 59 | } 60 | else if(index<0) { 61 | this.copy { add(0, value)} 62 | } 63 | else { 64 | this.copy { add(index, value) } 65 | } 66 | } 67 | 68 | internal fun JsonArray.set(index: Int, value_: JsonElement?): JsonArray { 69 | val value=value_ ?: JsonNull 70 | if(index>=size) { 71 | throw IndexOutOfBoundsException("") 72 | } 73 | return copy { this[index] = value } 74 | } 75 | 76 | internal fun JsonArray.remove(index:Int): JsonArray { 77 | return copy { removeAt(index) } 78 | } 79 | 80 | private inline fun JsonArray.copy(mutatorBlock: MutableList.() -> Unit): JsonArray { 81 | return JsonArray(this.toMutableList().apply(mutatorBlock)) 82 | } 83 | 84 | 85 | /* 86 | * JsonObject Extensions 87 | * */ 88 | internal fun JsonObject.add(key: String, value_: JsonElement?): JsonObject { 89 | val value=value_ ?: JsonNull 90 | return copy { 91 | this[key] = value 92 | } 93 | } 94 | 95 | internal fun JsonObject.remove(key: String): JsonObject { 96 | return copy { remove(key) } 97 | } 98 | 99 | internal fun JsonObject.set(key: String, value_: JsonElement?): JsonObject { 100 | val value=value_ ?: JsonNull 101 | if(!this.containsKey(key)) { 102 | throw IndexOutOfBoundsException("Key[$key] doesn't exist") 103 | } 104 | return copy { 105 | this[key] = value 106 | } 107 | } 108 | 109 | internal fun JsonObject.addProperty(key: String, value: String): JsonObject { 110 | return this.copy { 111 | this[key] = JsonPrimitive(value) 112 | } 113 | } 114 | 115 | internal fun JsonObject.addProperty(key: String, value: Number): JsonObject { 116 | return this.copy { 117 | this[key] = JsonPrimitive(value) 118 | } 119 | } 120 | 121 | private inline fun JsonObject.copy(mutatorBlock: MutableMap.() -> Unit): JsonObject { 122 | return JsonObject(this.toMutableMap().apply(mutatorBlock)) 123 | } -------------------------------------------------------------------------------- /convention-plugins/src/main/kotlin/maven-publish.conventions.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.gradle.api.publish.maven.MavenPublication 2 | import org.gradle.api.tasks.bundling.Jar 3 | import org.gradle.kotlin.dsl.`maven-publish` 4 | import org.gradle.kotlin.dsl.signing 5 | import java.util.* 6 | 7 | plugins { 8 | `maven-publish` 9 | signing 10 | } 11 | 12 | // Stub secrets to let the project sync and build without the publication values set up 13 | ext["signing.keyId"] = null 14 | ext["signing.password"] = null 15 | ext["signing.secretKeyRingFile"] = null 16 | ext["ossrhUsername"] = null 17 | ext["ossrhPassword"] = null 18 | 19 | // Grabbing secrets from local.properties file or from environment variables, which could be used on CI 20 | val secretPropsFile = project.rootProject.file("local.properties") 21 | if (secretPropsFile.exists()) { 22 | secretPropsFile.reader().use { 23 | Properties().apply { 24 | load(it) 25 | } 26 | }.onEach { (name, value) -> 27 | ext[name.toString()] = value 28 | } 29 | } else { 30 | ext["signing.keyId"] = System.getenv("SIGNING_KEY_ID") 31 | ext["signing.password"] = System.getenv("SIGNING_PASSWORD") 32 | ext["signing.secretKeyRingFile"] = System.getenv("SIGNING_SECRET_KEY_RING_FILE") 33 | ext["ossrhUsername"] = System.getenv("OSSRH_USERNAME") 34 | ext["ossrhPassword"] = System.getenv("OSSRH_PASSWORD") 35 | } 36 | 37 | val javadocJar by tasks.registering(Jar::class) { 38 | archiveClassifier.set("javadoc") 39 | } 40 | 41 | fun getExtraString(name: String) = ext[name]?.toString() 42 | 43 | publishing { 44 | // Configure maven central repository 45 | repositories { 46 | maven { 47 | name = "sonatype" 48 | setUrl("https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/") 49 | credentials { 50 | username = getExtraString("ossrhUsername") 51 | password = getExtraString("ossrhPassword") 52 | } 53 | } 54 | } 55 | 56 | // Configure all publications 57 | publications.withType { 58 | 59 | // Stub javadoc.jar artifact 60 | artifact(javadocJar.get()) 61 | 62 | // Provide artifacts information requited by Maven Central 63 | pom { 64 | name.set("kotlin-json-patch") 65 | description.set("JSON Patch library written exclusively in Kotlin") 66 | url.set("https://github.com/ReidSync/kotlin-json-patch") 67 | 68 | licenses { 69 | license { 70 | name.set("The Apache Software License, Version 2.0") 71 | url.set("http://www.apache.org/licenses/LICENSE-2.0.txt") 72 | } 73 | } 74 | developers { 75 | developer { 76 | id.set("ReidSync") 77 | name.set("Reid Byun") 78 | email.set("temphee@gmail.com") 79 | } 80 | } 81 | scm { 82 | connection.set("scm:git:github.com/ReidSync/kotlin-json-patch.git") 83 | developerConnection.set("scm:git:ssh://github.com/ReidSync/kotlin-json-patch.git") 84 | url.set("https://github.com/ReidSync/kotlin-json-patch/tree/main") 85 | } 86 | 87 | } 88 | } 89 | } 90 | 91 | // Signing artifacts. Signing.* extra properties values will be used 92 | 93 | signing { 94 | sign(publishing.publications) 95 | } 96 | 97 | //region Fix Gradle warning about signing tasks using publishing task outputs without explicit dependencies 98 | // 99 | tasks.withType().configureEach { 100 | val signingTasks = tasks.withType() 101 | mustRunAfter(signingTasks) 102 | } 103 | //endregion -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/resources/diff.kt: -------------------------------------------------------------------------------- 1 | package resources.testdata 2 | 3 | const val TestData_DIFF: String = """ 4 | [ 5 | { 6 | "message": "empty patch if no changes", 7 | "first": "hello", 8 | "second": "hello", 9 | "patch": [] 10 | }, 11 | { 12 | "message": "array members appended use special end-of-array pointer", 13 | "first": [ 1, 2, 3 ], 14 | "second": [ 1, 2, 3, 4, 5 ], 15 | "patch": [ 16 | { "op": "add", "path": "/-", "value": 4 }, 17 | { "op": "add", "path": "/-", "value": 5 } 18 | ] 19 | }, 20 | { 21 | "message": "array members are correctly deleted", 22 | "first": [ 1, 2, 3 ], 23 | "second": [ 1 ], 24 | "patch": [ 25 | { "op": "remove", "path": "/1" }, 26 | { "op": "remove", "path": "/1" } 27 | ] 28 | }, 29 | { 30 | "message": "single object member is deleted", 31 | "first": { "a": "b", "c": "d" }, 32 | "second": { "a": "b" }, 33 | "patch": [ 34 | { "op": "remove", "path": "/c" } 35 | ] 36 | }, 37 | { 38 | "message": "added object members are in natural order", 39 | "first": { "a": 1 }, 40 | "second": { "a": 1, "c": 2, "b": 3, "d": 4 }, 41 | "patch": [ 42 | { "op": "add", "path": "/b", "value": 3 }, 43 | { "op": "add", "path": "/c", "value": 2 }, 44 | { "op": "add", "path": "/d", "value": 4 } 45 | ] 46 | }, 47 | { 48 | "message": "single object value change is replaced", 49 | "first": { "a": null }, 50 | "second": { "a": 6 }, 51 | "patch": [ 52 | { "op": "replace", "path": "/a", "value": 6 } 53 | ] 54 | }, 55 | { 56 | "message": "full value replacement is accounted for", 57 | "first": [ 1, 2, 3 ], 58 | "second": { "hello": "world" }, 59 | "patch": [ 60 | { "op": "replace", "path": "", "value": { "hello": "world" } } 61 | ] 62 | }, 63 | { 64 | "message": "embedded object addition/replacement works", 65 | "first": { 66 | "a": "b", 67 | "c": { 68 | "d": "e" 69 | } 70 | }, 71 | "second": { 72 | "a": "b", 73 | "c": { 74 | "d": 1, 75 | "e": "f" 76 | } 77 | }, 78 | "patch": [ 79 | { "op": "add", "path": "/c/e", "value": "f" }, 80 | { "op": "replace", "path": "/c/d", "value": 1 } 81 | ] 82 | }, 83 | { 84 | "message": "embedded array addition/replacement works", 85 | "first": { 86 | "a": [ 1, 2, 3 ] 87 | }, 88 | "second": { 89 | "a": [ "b", 2, 3, 4 ] 90 | }, 91 | "patch": [ 92 | { "op": "replace", "path": "/a/0", "value": "b" }, 93 | { "op": "add", "path": "/a/-", "value": 4 } 94 | ] 95 | }, 96 | { 97 | "message": "embedded object addition/replacement works (#2)", 98 | "first": [ { "a": "b" }, "foo", { "bar": null } ], 99 | "second": [ { "a": "b", "c": "d" }, "foo", { "bar": "baz" } ], 100 | "patch": [ 101 | { "op": "add", "path": "/0/c", "value": "d" }, 102 | { "op": "replace", "path": "/2/bar", "value": "baz" } 103 | ] 104 | }, 105 | { 106 | "message": "embedded array addition/replacement works (#2)", 107 | "first": [ 1, [ 2, 3 ], 4 ], 108 | "second": [ "x", [ 2, 3, "y" ], 4 ], 109 | "patch": [ 110 | { "op": "replace", "path": "/0", "value": "x" }, 111 | { "op": "add", "path": "/1/-", "value": "y" } 112 | ] 113 | } 114 | ] 115 | """ -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/resources/rfc6902-samples.json.kt: -------------------------------------------------------------------------------- 1 | package resources.testdata 2 | 3 | const val TestData_RFC6902_SAMPLES: String = """ 4 | { 5 | "errors": [ 6 | { 7 | "message": "A.13. Invalid JSON Patch Document", 8 | "op": [{ "op": "add", "path": "/baz", "value": "qux", "op": "remove" }], 9 | "node": { "foo": "bar" }, 10 | "disabled": true 11 | }, 12 | { 13 | "message": "A.12. Adding to a Nonexistent Target", 14 | "op": [{ "op": "add", "path": "/baz/bat", "value": "qux" }], 15 | "node": { "foo": "bar" } 16 | } 17 | ], 18 | "ops": [ 19 | { 20 | "message": "A.1. Adding an Object Member", 21 | "op": [{ "op": "add", "path": "/baz", "value": "qux" }], 22 | "node": { "foo": "bar" }, 23 | "expected": { 24 | "baz": "qux", 25 | "foo": "bar" 26 | } 27 | }, 28 | { 29 | "message": "A.2. Adding an Array Element", 30 | "op": [{ "op": "add", "path": "/foo/1", "value": "qux" }], 31 | "node": { "foo": [ "bar", "baz" ] }, 32 | "expected": { "foo": [ "bar", "qux", "baz" ] } 33 | }, 34 | { 35 | "message": "A.3. Removing an Object Member", 36 | "op": [ { "op": "remove", "path": "/baz" }], 37 | "node": { 38 | "baz": "qux", 39 | "foo": "bar" 40 | }, 41 | "expected": { "foo": "bar" } 42 | }, 43 | { 44 | "message": "A.4. Removing an Array Element", 45 | "op": [{ "op": "remove", "path": "/foo/1" }], 46 | "node": { "foo": [ "bar", "qux", "baz" ] }, 47 | "expected": { "foo": [ "bar", "baz" ] } 48 | }, 49 | { 50 | "message": "A.5. Replacing a Value", 51 | "op": [{ "op": "replace", "path": "/baz", "value": "boo" }], 52 | "node": { 53 | "baz": "qux", 54 | "foo": "bar" 55 | }, 56 | "expected": { 57 | "baz": "boo", 58 | "foo": "bar" 59 | } 60 | }, 61 | { 62 | "message": "A.6. Moving a Value", 63 | "op": [{ "op": "move", "from": "/foo/waldo", "path": "/qux/thud" }], 64 | "node": { 65 | "foo": { 66 | "bar": "baz", 67 | "waldo": "fred" 68 | }, 69 | "qux": { 70 | "corge": "grault" 71 | } 72 | }, 73 | "expected": { 74 | "foo": { 75 | "bar": "baz" 76 | }, 77 | "qux": { 78 | "corge": "grault", 79 | "thud": "fred" 80 | } 81 | } 82 | }, 83 | { 84 | "message": "A.7. Moving an Array Element", 85 | "op": [{ "op": "move", "from": "/foo/1", "path": "/foo/3" }], 86 | "node": { "foo": [ "all", "grass", "cows", "eat" ] }, 87 | "expected": { "foo": [ "all", "cows", "eat", "grass" ] } 88 | }, 89 | { 90 | "message": "A.10. Adding a Nested Member Object", 91 | "op": [{ "op": "add", "path": "/child", "value": { "grandchild": { } } }], 92 | "node": { "foo": "bar" }, 93 | "expected": { 94 | "foo": "bar", 95 | "child": { 96 | "grandchild": { 97 | } 98 | } 99 | } 100 | }, 101 | { 102 | "message": "A.11. Ignoring Unrecognized Elements", 103 | "op": [{ "op": "add", "path": "/baz", "value": "qux", "xyz": 123 }], 104 | "node": { "foo": "bar" }, 105 | "expected": { 106 | "foo": "bar", 107 | "baz": "qux" 108 | } 109 | }, 110 | { 111 | "message": "A.16. Adding an Array Value", 112 | "op": [{ "op": "add", "path": "/foo/-", "value": ["abc", "def"] }], 113 | "node": { "foo": ["bar"] }, 114 | "expected": { "foo": ["bar", ["abc", "def"]] } 115 | } 116 | ] 117 | } 118 | """ -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/EditScript.kt: -------------------------------------------------------------------------------- 1 | package com.reidsync.kxjsonpatch.lcs 2 | /* 3 | * Licensed to the Apache Software Foundation (ASF) under one or more 4 | * contributor license agreements. See the NOTICE file distributed with 5 | * this work for additional information regarding copyright ownership. 6 | * The ASF licenses this file to You under the Apache License, Version 2.0 7 | * (the "License"); you may not use this file except in compliance with 8 | * the License. You may obtain a copy of the License at 9 | * 10 | * http://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 | * This class gathers all the [commands][EditCommand] needed to transform 19 | * one objects sequence into another objects sequence. 20 | * 21 | * 22 | * An edit script is the most general view of the differences between two 23 | * sequences. It is built as the result of the comparison between two sequences 24 | * by the [SequencesComparator] class. The user can 25 | * walk through it using the *visitor* design pattern. 26 | * 27 | * 28 | * It is guaranteed that the objects embedded in the [insert][InsertCommand] come from the second sequence and that the objects embedded in 29 | * either the [delete commands][DeleteCommand] or [keep][KeepCommand] come from the first sequence. This can be important if subclassing 30 | * is used for some elements in the first sequence and the `equals` 31 | * method is specialized. 32 | * 33 | * @see SequencesComparator 34 | * 35 | * @see EditCommand 36 | * 37 | * @see CommandVisitor 38 | * 39 | * 40 | * @since 4.0 41 | * @version $Id: EditScript.java 1477760 2013-04-30 18:34:03Z tn $ 42 | */ 43 | class EditScript { 44 | /** Container for the commands. */ 45 | private val commands: MutableList> 46 | /** 47 | * Get the length of the Longest Common Subsequence (LCS). The length of the 48 | * longest common subsequence is the number of [keep][KeepCommand] in the script. 49 | * 50 | * @return length of the Longest Common Subsequence 51 | */ 52 | /** Length of the longest common subsequence. */ 53 | var lCSLength: Int 54 | private set 55 | /** 56 | * Get the number of effective modifications. The number of effective 57 | * modification is the number of [delete][DeleteCommand] and 58 | * [insert][InsertCommand] commands in the script. 59 | * 60 | * @return number of effective modifications 61 | */ 62 | /** Number of modifications. */ 63 | var modifications: Int 64 | private set 65 | 66 | /** 67 | * Simple constructor. Creates a new empty script. 68 | */ 69 | init { 70 | commands = ArrayList>() 71 | lCSLength = 0 72 | modifications = 0 73 | } 74 | 75 | /** 76 | * Add a keep command to the script. 77 | * 78 | * @param command command to add 79 | */ 80 | fun append(command: KeepCommand) { 81 | commands.add(command) 82 | ++lCSLength 83 | } 84 | 85 | /** 86 | * Add an insert command to the script. 87 | * 88 | * @param command command to add 89 | */ 90 | fun append(command: InsertCommand) { 91 | commands.add(command) 92 | ++modifications 93 | } 94 | 95 | /** 96 | * Add a delete command to the script. 97 | * 98 | * @param command command to add 99 | */ 100 | fun append(command: DeleteCommand) { 101 | commands.add(command) 102 | ++modifications 103 | } 104 | 105 | /** 106 | * Visit the script. The script implements the *visitor* design 107 | * pattern, this method is the entry point to which the user supplies its 108 | * own visitor, the script will be responsible to drive it through the 109 | * commands in order and call the appropriate method as each command is 110 | * encountered. 111 | * 112 | * @param visitor the visitor that will visit all commands in turn 113 | */ 114 | fun visit(visitor: CommandVisitor) { 115 | for (command in commands) { 116 | command.accept(visitor) 117 | } 118 | } 119 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/JsonDiffTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.reidsync.kxjsonpatch 17 | 18 | import com.reidsync.kxjsonpatch.utils.GsonObjectMapper 19 | import kotlinx.serialization.json.JsonArray 20 | import kotlinx.serialization.json.JsonElement 21 | import kotlinx.serialization.json.JsonObject 22 | import kotlinx.serialization.json.JsonPrimitive 23 | import kotlinx.serialization.json.jsonArray 24 | import kotlinx.serialization.json.jsonObject 25 | import resources.testdata.TestData_SAMPLE 26 | import kotlin.test.BeforeTest 27 | import kotlin.test.Test 28 | import kotlin.test.assertEquals 29 | 30 | /** 31 | * Unit test 32 | */ 33 | class JsonDiffTest { 34 | var objectMapper = GsonObjectMapper() 35 | lateinit var jsonNode: JsonArray 36 | 37 | @BeforeTest 38 | fun setUp() { 39 | jsonNode = objectMapper.readTree(TestData_SAMPLE).jsonArray 40 | } 41 | 42 | @Test 43 | fun testSampleJsonDiff() { 44 | for (i in 0 until jsonNode.size) { 45 | val first: JsonElement = jsonNode.get(i).jsonObject.get("first")!! 46 | val second: JsonElement = jsonNode.get(i).jsonObject.get("second")!! 47 | println("Test # $i") 48 | println(first) 49 | println(second) 50 | val actualPatch: JsonElement = JsonDiff.asJson(first, second) 51 | println(actualPatch) 52 | val secondPrime: JsonElement = JsonPatch.apply(actualPatch, first) 53 | println(secondPrime) 54 | assertEquals(second, secondPrime) 55 | } 56 | } 57 | 58 | @Test 59 | fun testGeneratedJsonDiff() { 60 | for (i in 0..999) { 61 | val first: JsonElement = TestDataGenerator.generate((0..10).random()) 62 | val second: JsonElement = TestDataGenerator.generate((0..10).random()) 63 | val actualPatch: JsonElement = JsonDiff.asJson(first, second) 64 | println("Test # $i") 65 | println(first) 66 | println(second) 67 | println(actualPatch) 68 | val secondPrime: JsonElement = JsonPatch.apply(actualPatch, first) 69 | println(secondPrime) 70 | assertEquals(second, secondPrime) 71 | } 72 | } 73 | 74 | /** 75 | * REMOVE operation did result in JsonPatch generated with value field present. 76 | * That should not happen. 77 | */ 78 | @Test 79 | fun testNoValueShouldBePresentInRemoveOperation() { 80 | val first = JsonObject(mapOf("key" to JsonPrimitive("value"))) 81 | val second = JsonObject(emptyMap()) 82 | val patch: JsonElement = JsonDiff.asJson(first, second) 83 | println(first) 84 | println(second) 85 | println(patch) 86 | val expectedPatch = JsonArray( 87 | content = 88 | listOf( 89 | JsonObject( 90 | mapOf( 91 | "op" to JsonPrimitive("remove"), 92 | "path" to JsonPrimitive("/key"), 93 | ) 94 | ) 95 | ) 96 | ) 97 | assertEquals(expectedPatch, patch) 98 | } 99 | 100 | @Test 101 | fun testValueShouldBePresentInOtherOperation() { 102 | val first = JsonObject(emptyMap()) 103 | val second = JsonObject(mapOf("key" to JsonPrimitive("value"))) 104 | val patch: JsonElement = JsonDiff.asJson(first, second) 105 | println(first) 106 | println(second) 107 | println(patch) 108 | val expectedPatch = JsonArray( 109 | content = 110 | listOf( 111 | JsonObject( 112 | mapOf( 113 | "op" to JsonPrimitive("add"), 114 | "path" to JsonPrimitive("/key"), 115 | "value" to JsonPrimitive("value"), 116 | ) 117 | ) 118 | ) 119 | ) 120 | assertEquals(expectedPatch, patch) 121 | } 122 | 123 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/CommandVisitor.kt: -------------------------------------------------------------------------------- 1 | package com.reidsync.kxjsonpatch.lcs 2 | /* 3 | * Licensed to the Apache Software Foundation (ASF) under one or more 4 | * contributor license agreements. See the NOTICE file distributed with 5 | * this work for additional information regarding copyright ownership. 6 | * The ASF licenses this file to You under the Apache License, Version 2.0 7 | * (the "License"); you may not use this file except in compliance with 8 | * the License. You may obtain a copy of the License at 9 | * 10 | * http://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 | * This interface should be implemented by user object to walk 21 | * through [EditScript] objects. 22 | * 23 | * 24 | * Users should implement this interface in order to walk through 25 | * the [EditScript] object created by the comparison 26 | * of two sequences. This is a direct application of the visitor 27 | * design pattern. The [EditScript.visit] 28 | * method takes an object implementing this interface as an argument, 29 | * it will perform the loop over all commands in the script and the 30 | * proper methods of the user class will be called as the commands are 31 | * encountered. 32 | * 33 | * 34 | * The implementation of the user visitor class will depend on the 35 | * need. Here are two examples. 36 | * 37 | * 38 | * The first example is a visitor that build the longest common 39 | * subsequence: 40 | *
 41 |  * import org.apache.commons.collections4.comparators.sequence.CommandVisitor;
 42 |  *
 43 |  * import java.util.ArrayList;
 44 |  *
 45 |  * public class LongestCommonSubSequence implements CommandVisitor {
 46 |  *
 47 |  * public LongestCommonSubSequence() {
 48 |  * a = new ArrayList();
 49 |  * }
 50 |  *
 51 |  * public void visitInsertCommand(Object object) {
 52 |  * }
 53 |  *
 54 |  * public void visitKeepCommand(Object object) {
 55 |  * a.add(object);
 56 |  * }
 57 |  *
 58 |  * public void visitDeleteCommand(Object object) {
 59 |  * }
 60 |  *
 61 |  * public Object[] getSubSequence() {
 62 |  * return a.toArray();
 63 |  * }
 64 |  *
 65 |  * private ArrayList a;
 66 |  *
 67 |  * }
 68 | 
* 69 | * 70 | * 71 | * The second example is a visitor that shows the commands and the way 72 | * they transform the first sequence into the second one: 73 | *
 74 |  * import org.apache.commons.collections4.comparators.sequence.CommandVisitor;
 75 |  *
 76 |  * import java.util.Arrays;
 77 |  * import java.util.ArrayList;
 78 |  * import java.util.Iterator;
 79 |  *
 80 |  * public class ShowVisitor implements CommandVisitor {
 81 |  *
 82 |  * public ShowVisitor(Object[] sequence1) {
 83 |  * v = new ArrayList();
 84 |  * v.addAll(Arrays.asList(sequence1));
 85 |  * index = 0;
 86 |  * }
 87 |  *
 88 |  * public void visitInsertCommand(Object object) {
 89 |  * v.insertElementAt(object, index++);
 90 |  * display("insert", object);
 91 |  * }
 92 |  *
 93 |  * public void visitKeepCommand(Object object) {
 94 |  * ++index;
 95 |  * display("keep  ", object);
 96 |  * }
 97 |  *
 98 |  * public void visitDeleteCommand(Object object) {
 99 |  * v.remove(index);
100 |  * display("delete", object);
101 |  * }
102 |  *
103 |  * private void display(String commandName, Object object) {
104 |  * System.out.println(commandName + " " + object + " ->" + this);
105 |  * }
106 |  *
107 |  * public String toString() {
108 |  * StringBuffer buffer = new StringBuffer();
109 |  * for (Iterator iter = v.iterator(); iter.hasNext();) {
110 |  * buffer.append(' ').append(iter.next());
111 |  * }
112 |  * return buffer.toString();
113 |  * }
114 |  *
115 |  * private ArrayList v;
116 |  * private int index;
117 |  *
118 |  * }
119 | 
* 120 | * 121 | * @since 4.0 122 | * @version $Id: CommandVisitor.java 1477760 2013-04-30 18:34:03Z tn $ 123 | */ 124 | interface CommandVisitor { 125 | /** 126 | * Method called when an insert command is encountered. 127 | * 128 | * @param object object to insert (this object comes from the second sequence) 129 | */ 130 | fun visitInsertCommand(`object`: T) 131 | 132 | /** 133 | * Method called when a keep command is encountered. 134 | * 135 | * @param object object to keep (this object comes from the first sequence) 136 | */ 137 | fun visitKeepCommand(`object`: T) 138 | 139 | /** 140 | * Method called when a delete command is encountered. 141 | * 142 | * @param object object to delete (this object comes from the first sequence) 143 | */ 144 | fun visitDeleteCommand(`object`: T) 145 | } -------------------------------------------------------------------------------- /.idea/codeStyles: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 13 | 22 | 23 | 24 | 25 | 27 | 28 | 29 |
30 | 31 | 32 | 33 | xmlns:android 34 | 35 | ^$ 36 | 37 | 38 | 39 |
40 |
41 | 42 | 43 | 44 | xmlns:.* 45 | 46 | ^$ 47 | 48 | 49 | BY_NAME 50 | 51 |
52 |
53 | 54 | 55 | 56 | .*:id 57 | 58 | http://schemas.android.com/apk/res/android 59 | 60 | 61 | 62 |
63 |
64 | 65 | 66 | 67 | .*:name 68 | 69 | http://schemas.android.com/apk/res/android 70 | 71 | 72 | 73 |
74 |
75 | 76 | 77 | 78 | name 79 | 80 | ^$ 81 | 82 | 83 | 84 |
85 |
86 | 87 | 88 | 89 | style 90 | 91 | ^$ 92 | 93 | 94 | 95 |
96 |
97 | 98 | 99 | 100 | .* 101 | 102 | ^$ 103 | 104 | 105 | BY_NAME 106 | 107 |
108 |
109 | 110 | 111 | 112 | .* 113 | 114 | http://schemas.android.com/apk/res/android 115 | 116 | 117 | ANDROID_ATTRIBUTE_ORDER 118 | 119 |
120 |
121 | 122 | 123 | 124 | .* 125 | 126 | .* 127 | 128 | 129 | BY_NAME 130 | 131 |
132 |
133 |
134 |
135 |
136 |
137 |
-------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/JsonPatch.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.reidsync.kxjsonpatch 18 | 19 | import kotlinx.serialization.json.* 20 | import kotlin.jvm.JvmOverloads 21 | import kotlin.jvm.JvmStatic 22 | 23 | object JsonPatch { 24 | internal var op = Operations() 25 | internal var consts = Constants() 26 | 27 | private fun getPatchAttr(jsonNode: JsonObject, attr: String): JsonElement { 28 | val child = jsonNode.get(attr) ?: throw InvalidJsonPatchException("Invalid JSON Patch payload (missing '$attr' field)") 29 | return child 30 | } 31 | 32 | private fun getPatchAttrWithDefault(jsonNode: JsonObject, attr: String, defaultValue: JsonElement): JsonElement { 33 | val child = jsonNode.get(attr) 34 | if (child == null) 35 | return defaultValue 36 | else 37 | return child 38 | } 39 | 40 | @Throws(InvalidJsonPatchException::class) 41 | private fun process(patch: JsonElement, processor: JsonPatchApplyProcessor, flags: Set) { 42 | 43 | if (patch !is JsonArray) 44 | throw InvalidJsonPatchException("Invalid JSON Patch payload (not an array)") 45 | val operations = patch.jsonArray.iterator() 46 | while (operations.hasNext()) { 47 | val jsonNode_ = operations.next() 48 | if (jsonNode_ !is JsonObject) throw InvalidJsonPatchException("Invalid JSON Patch payload (not an object)") 49 | val jsonNode = jsonNode_.jsonObject 50 | val operation = op.opFromName(getPatchAttr(jsonNode.jsonObject, consts.OP).toString().replace("\"".toRegex(), "")) 51 | val path = getPath(getPatchAttr(jsonNode, consts.PATH)) 52 | 53 | when (operation) { 54 | op.REMOVE -> { 55 | processor.edit { remove(path) } 56 | } 57 | 58 | op.ADD -> { 59 | val value: JsonElement 60 | if (!flags.contains(CompatibilityFlags.MISSING_VALUES_AS_NULLS)) 61 | value = getPatchAttr(jsonNode, consts.VALUE) 62 | else 63 | value = getPatchAttrWithDefault(jsonNode, consts.VALUE, JsonNull) 64 | processor.edit { add(path, value) } 65 | } 66 | 67 | op.REPLACE -> { 68 | val value: JsonElement 69 | if (!flags.contains(CompatibilityFlags.MISSING_VALUES_AS_NULLS)) 70 | value = getPatchAttr(jsonNode, consts.VALUE) 71 | else 72 | value = getPatchAttrWithDefault(jsonNode, consts.VALUE, JsonNull) 73 | processor.edit { replace(path, value) } 74 | } 75 | 76 | op.MOVE -> { 77 | val fromPath = getPath(getPatchAttr(jsonNode, consts.FROM)) 78 | processor.edit { move(fromPath, path) } 79 | } 80 | 81 | op.COPY -> { 82 | val fromPath = getPath(getPatchAttr(jsonNode, consts.FROM)) 83 | processor.edit { copy(fromPath, path) } 84 | } 85 | 86 | op.TEST -> { 87 | val value: JsonElement 88 | if (!flags.contains(CompatibilityFlags.MISSING_VALUES_AS_NULLS)) 89 | value = getPatchAttr(jsonNode, consts.VALUE) 90 | else 91 | value = getPatchAttrWithDefault(jsonNode, consts.VALUE, JsonNull) 92 | processor.edit { test(path, value) } 93 | } 94 | } 95 | } 96 | } 97 | 98 | @Throws(InvalidJsonPatchException::class) 99 | @JvmStatic 100 | @JvmOverloads 101 | fun validate(patch: JsonElement, flags: Set = CompatibilityFlags.defaults()) { 102 | process(patch, NoopProcessor.INSTANCE, flags) 103 | } 104 | 105 | @Throws(JsonPatchApplicationException::class) 106 | @JvmStatic 107 | @JvmOverloads 108 | fun apply(patch: JsonElement, source: JsonElement, flags: Set = CompatibilityFlags.defaults()): JsonElement { 109 | val processor = ApplyProcessor(source) 110 | process(patch, processor, flags) 111 | return processor.result() 112 | } 113 | 114 | 115 | private fun decodePath(path: String): String { 116 | return path.replace("~1".toRegex(), "/").replace("~0".toRegex(), "~") // see http://tools.ietf.org/html/rfc6901#section-4 117 | } 118 | 119 | private fun getPath(path: JsonElement): List { 120 | // List paths = Splitter.on('/').splitToList(path.toString().replaceAll("\"", "")); 121 | // return Lists.newArrayList(Iterables.transform(paths, DECODE_PATH_FUNCTION)); 122 | val pathstr = path.toString().replace("\"", "") 123 | val paths = pathstr.split("/") 124 | return paths.map { decodePath(it) } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [kotlin-json-patch] 2 | [![CircleCI](https://dl.circleci.com/status-badge/img/circleci/FX4uQvXfdGbsC2LtLwAcHN/6WSq31hZUQd6ntmfk7zYqZ/tree/main.svg?style=svg&circle-token=726a635dd6621f418b6a9b009e03e14aff877c5b)](https://dl.circleci.com/status-badge/redirect/circleci/FX4uQvXfdGbsC2LtLwAcHN/6WSq31hZUQd6ntmfk7zYqZ/tree/main) 3 | [![CircleCI](https://dl.circleci.com/status-badge/img/circleci/FX4uQvXfdGbsC2LtLwAcHN/6WSq31hZUQd6ntmfk7zYqZ/tree/main.svg?style=shield&circle-token=726a635dd6621f418b6a9b009e03e14aff877c5b)](https://dl.circleci.com/status-badge/redirect/circleci/FX4uQvXfdGbsC2LtLwAcHN/6WSq31hZUQd6ntmfk7zYqZ/tree/main) 4 | [![Kotlin](https://img.shields.io/badge/kotlin-1.9.20-white.svg?logo=kotlin&color=6A5ACD)](http://kotlinlang.org/) 5 | [![Apache License](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg?logo=apache)](https://www.apache.org/licenses/LICENSE-2.0.txt) 6 | [![Maven Central](https://img.shields.io/maven-central/v/io.github.reidsync/kotlin-json-patch?logo=sonatype&logoColor=D2691E&color=D2691E)](https://central.sonatype.com/artifact/io.github.reidsync/kotlin-json-patch/overview) 7 | 8 | ![badge-support-kotlin-multiplatform] 9 | ![badge-support-android-native] 10 | ![badge-support-apple-silicon] 11 | API 12 | ![badge-platform-android] 13 | ![badge-platform-ios] 14 | ![badge-platform-jvm] 15 | ![badge-platform-js] 16 | 17 | ## Kotlin JSON Patching Library 18 | 19 | ### This is an implementation of [RFC 6902 JSON Patch](https://datatracker.ietf.org/doc/html/rfc6902) written exclusively in Kotlin. 20 | It is based on the [Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0) licensed library from Flipkart, [zjsonpatch](https://github.com/flipkart-incubator/zjsonpatch). 21 | This project is a fork of [KJsonPatch](https://github.com/beyondeye/kjsonpatch) (with the [latest commit referenced](https://github.com/beyondeye/kjsonpatch/commit/939455832a09de666d9578963676996b5e09b6be)). 22 | 23 | ## Changes 24 | 25 | This code has been modified from the original library in the following ways: 26 | * Ported from Java to Kotlin 27 | * Changed package names 28 | * Substituted Gson dependency with [`kotlinx.serialization.json`](https://kotlinlang.org/api/latest/kotlin.test/) 29 | * Added extensions for convenient usage of [`kotlinx.serialization.json`](https://kotlinlang.org/api/latest/kotlin.test/) 30 | 31 | ## Setup 32 | Add the dependency to your app module’s `build.gradle` file: 33 | 34 | ```kotlin 35 | repositories { 36 | mavenCentral() 37 | } 38 | 39 | dependencies { 40 | // e.g., implementation("io.github.reidsync:kotlin-json-patch:1.0.0") 41 | implementation("io.github.reidsync:kotlin-json-patch:${kotliln_json_patch_version}") 42 | } 43 | ``` 44 | > _**Check the [kotlin-json-patch versions](https://central.sonatype.com/artifact/io.github.reidsync/kotlin-json-patch/versions)**_ 45 | latest version : [![Maven Central](https://img.shields.io/maven-central/v/io.github.reidsync/kotlin-json-patch)](https://central.sonatype.com/artifact/io.github.reidsync/kotlin-json-patch/overview) 46 | 47 | You can add the dependency to `sourceSets.commonMain.dependecies` for your Kotlin Multiplatform project. 48 | 49 | ```kotlin 50 | kotlin { 51 | sourceSets { 52 | commonMain.dependencies { 53 | //put your multiplatform dependencies here 54 | implementation("io.github.reidsync:kotlin-json-patch:${kotliln_json_patch_version}") 55 | } 56 | } 57 | } 58 | 59 | ``` 60 | 61 | ## API Usage 62 | 63 | > The variables `source`, `target`, and `patch` below must be asserted as valid `JsonElement` objects. 64 | ### Generating JSON Diff as a patch 65 | ```kotlin 66 | val diff: JsonArray = JsonDiff.asJson(source: JsonElement, target: JsonElement) 67 | ``` 68 | or 69 | ```kotlin 70 | val diff: JsonElement = source.generatePatch(with: target) 71 | ``` 72 | ### Applying JSON patch 73 | ```kotlin 74 | val result: JsonElement = JsonPatch.apply(patch: JsonElement, source: JsonElement) 75 | ``` 76 | or 77 | ```kotlin 78 | val result: JsonElement = source.apply(patch: patch) 79 | ``` 80 | This operation is performed on a clone of the source object. 81 | 82 | ## 83 | These changes mostly involve porting from Java to Kotlin to transform it into a pure Kotlin library that can be imported into Kotlin Multiplatform. If you have any specific preferences or further adjustments, feel free to let me know! 84 | 85 | 97 | 98 | 99 | [badge-platform-android]: https://img.shields.io/badge/-android-6EDB8D.svg?logo=android&&logoColor=white&style=flat 100 | [badge-platform-jvm]: https://img.shields.io/badge/-jvm-DB413D.svg?logo=jvm&logoColor=white&style=flat 101 | [badge-platform-js]: https://img.shields.io/badge/-js-F8DB5D.svg?logo=JavaScript&logoColor=white&style=flat 102 | [badge-platform-js-node]: https://img.shields.io/badge/-nodejs-68a063.svg?logo=nodedotjs&logoColor=white&style=flat 103 | [badge-platform-linux]: https://img.shields.io/badge/-linux-2D3F6C.svg?logo=linux&logoColor=white&style=flat 104 | [badge-platform-macos]: https://img.shields.io/badge/-macos-111111.svg?logo=macOS&logoColor=white&style=flat 105 | [badge-platform-ios]: https://img.shields.io/badge/-ios-CDCDCD.svg?logo=iOS&logoColor=white&style=flat 106 | [badge-platform-tvos]: https://img.shields.io/badge/-tvos-808080.svg?logo=AppleTV&logoColor=white&style=flat 107 | [badge-platform-watchos]: https://img.shields.io/badge/-watchos-C0C0C0.svg?logo=Apple&logoColor=white&style=flat 108 | [badge-platform-wasm]: https://img.shields.io/badge/-wasm-624FE8.svg?logo=webassembly&logoColor=white&style=flat 109 | [badge-platform-windows]: https://img.shields.io/badge/-windows-4D76CD.svg?logo=Windows&logoColor=whitestyle=flat 110 | [badge-support-android-native]: https://img.shields.io/badge/support-Android%20Native-6EDB8D.svg?style=flat?fontColor=white 111 | [badge-support-apple-silicon]: https://img.shields.io/badge/support-Apple%20Silicon-808080.svg?style=flat 112 | [badge-support-kotlin-multiplatform]: https://img.shields.io/badge/support-Kotlin%20Multiplatform-6A5ACD.svg?style=flat 113 | [badge-support-js-ir]: https://img.shields.io/badge/support-[js--IR]-AAC4E0.svg?style=flat 114 | [badge-support-linux-arm]: https://img.shields.io/badge/support-[LinuxArm]-2D3F6C.svg?style=flat 115 | 116 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.toptal.com/developers/gitignore/api/androidstudio,xcode,macos,kotlin,swift,swiftpackagemanager 2 | # Edit at https://www.toptal.com/developers/gitignore?templates=androidstudio,xcode,macos,kotlin,swift,swiftpackagemanager 3 | 4 | ### Kotlin ### 5 | # Compiled class file 6 | *.class 7 | 8 | # Log file 9 | *.log 10 | 11 | # BlueJ files 12 | *.ctxt 13 | 14 | # Mobile Tools for Java (J2ME) 15 | .mtj.tmp/ 16 | 17 | # Package Files # 18 | *.jar 19 | *.war 20 | *.nar 21 | *.ear 22 | *.zip 23 | *.tar.gz 24 | *.rar 25 | 26 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 27 | hs_err_pid* 28 | replay_pid* 29 | 30 | ### macOS ### 31 | # General 32 | .DS_Store 33 | .AppleDouble 34 | .LSOverride 35 | 36 | # Icon must end with two \r 37 | Icon 38 | 39 | 40 | # Thumbnails 41 | ._* 42 | 43 | # Files that might appear in the root of a volume 44 | .DocumentRevisions-V100 45 | .fseventsd 46 | .Spotlight-V100 47 | .TemporaryItems 48 | .Trashes 49 | .VolumeIcon.icns 50 | .com.apple.timemachine.donotpresent 51 | 52 | # Directories potentially created on remote AFP share 53 | .AppleDB 54 | .AppleDesktop 55 | Network Trash Folder 56 | Temporary Items 57 | .apdisk 58 | 59 | ### macOS Patch ### 60 | # iCloud generated files 61 | *.icloud 62 | 63 | ### Swift ### 64 | # Xcode 65 | # 66 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 67 | 68 | ## User settings 69 | xcuserdata/ 70 | 71 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) 72 | *.xcscmblueprint 73 | *.xccheckout 74 | 75 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) 76 | build/ 77 | DerivedData/ 78 | *.moved-aside 79 | *.pbxuser 80 | !default.pbxuser 81 | *.mode1v3 82 | !default.mode1v3 83 | *.mode2v3 84 | !default.mode2v3 85 | *.perspectivev3 86 | !default.perspectivev3 87 | 88 | ## Obj-C/Swift specific 89 | *.hmap 90 | 91 | ## App packaging 92 | *.ipa 93 | *.dSYM.zip 94 | *.dSYM 95 | 96 | ## Playgrounds 97 | timeline.xctimeline 98 | playground.xcworkspace 99 | 100 | # Swift Package Manager 101 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 102 | # Packages/ 103 | # Package.pins 104 | # Package.resolved 105 | # *.xcodeproj 106 | # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata 107 | # hence it is not needed unless you have added a package configuration file to your project 108 | # .swiftpm 109 | 110 | .build/ 111 | 112 | # CocoaPods 113 | # We recommend against adding the Pods directory to your .gitignore. However 114 | # you should judge for yourself, the pros and cons are mentioned at: 115 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 116 | # Pods/ 117 | # Add this line if you want to avoid checking in source code from the Xcode workspace 118 | # *.xcworkspace 119 | 120 | # Carthage 121 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 122 | # Carthage/Checkouts 123 | 124 | Carthage/Build/ 125 | 126 | # Accio dependency management 127 | Dependencies/ 128 | .accio/ 129 | 130 | # fastlane 131 | # It is recommended to not store the screenshots in the git repo. 132 | # Instead, use fastlane to re-generate the screenshots whenever they are needed. 133 | # For more information about the recommended setup visit: 134 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 135 | 136 | fastlane/report.xml 137 | fastlane/Preview.html 138 | fastlane/screenshots/**/*.png 139 | fastlane/test_output 140 | 141 | # Code Injection 142 | # After new code Injection tools there's a generated folder /iOSInjectionProject 143 | # https://github.com/johnno1962/injectionforxcode 144 | 145 | iOSInjectionProject/ 146 | 147 | ### SwiftPackageManager ### 148 | Packages 149 | xcuserdata 150 | *.xcodeproj 151 | 152 | 153 | ### Xcode ### 154 | 155 | ## Xcode 8 and earlier 156 | 157 | ### Xcode Patch ### 158 | *.xcodeproj/* 159 | !*.xcodeproj/project.pbxproj 160 | !*.xcodeproj/xcshareddata/ 161 | !*.xcodeproj/project.xcworkspace/ 162 | !*.xcworkspace/contents.xcworkspacedata 163 | /*.gcno 164 | **/xcshareddata/WorkspaceSettings.xcsettings 165 | 166 | ### AndroidStudio ### 167 | # Covers files to be ignored for android development using Android Studio. 168 | 169 | # Built application files 170 | *.apk 171 | *.ap_ 172 | *.aab 173 | 174 | # Files for the ART/Dalvik VM 175 | *.dex 176 | 177 | # Java class files 178 | 179 | # Generated files 180 | bin/ 181 | gen/ 182 | out/ 183 | 184 | # Gradle files 185 | .gradle 186 | .gradle/ 187 | 188 | # Signing files 189 | .signing/ 190 | 191 | # Local configuration file (sdk path, etc) 192 | local.properties 193 | 194 | # Proguard folder generated by Eclipse 195 | proguard/ 196 | 197 | # Log Files 198 | 199 | # Android Studio 200 | /*/build/ 201 | /*/local.properties 202 | /*/out 203 | /*/*/build 204 | /*/*/production 205 | captures/ 206 | .navigation/ 207 | *.ipr 208 | *~ 209 | *.swp 210 | 211 | # Keystore files 212 | *.jks 213 | *.keystore 214 | 215 | # Google Services (e.g. APIs or Firebase) 216 | # google-services.json 217 | 218 | # Android Patch 219 | gen-external-apklibs 220 | 221 | # External native build folder generated in Android Studio 2.2 and later 222 | .externalNativeBuild 223 | 224 | # NDK 225 | obj/ 226 | 227 | # IntelliJ IDEA 228 | *.iml 229 | *.iws 230 | /out/ 231 | 232 | # User-specific configurations 233 | .idea/caches/ 234 | .idea/libraries/ 235 | .idea/shelf/ 236 | .idea/workspace.xml 237 | .idea/tasks.xml 238 | .idea/.name 239 | .idea/compiler.xml 240 | .idea/copyright/profiles_settings.xml 241 | .idea/encodings.xml 242 | .idea/misc.xml 243 | .idea/modules.xml 244 | .idea/scopes/scope_settings.xml 245 | .idea/dictionaries 246 | .idea/vcs.xml 247 | .idea/jsLibraryMappings.xml 248 | .idea/datasources.xml 249 | .idea/dataSources.ids 250 | .idea/sqlDataSources.xml 251 | .idea/dynamic.xml 252 | .idea/uiDesigner.xml 253 | .idea/assetWizardSettings.xml 254 | .idea/gradle.xml 255 | .idea/jarRepositories.xml 256 | .idea/navEditor.xml 257 | 258 | # Legacy Eclipse project files 259 | .classpath 260 | .project 261 | .cproject 262 | .settings/ 263 | 264 | # Mobile Tools for Java (J2ME) 265 | 266 | # Package Files # 267 | 268 | # virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml) 269 | 270 | ## Plugin-specific files: 271 | 272 | # mpeltonen/sbt-idea plugin 273 | .idea_modules/ 274 | 275 | # JIRA plugin 276 | atlassian-ide-plugin.xml 277 | 278 | # Mongo Explorer plugin 279 | .idea/mongoSettings.xml 280 | 281 | # Crashlytics plugin (for Android Studio and IntelliJ) 282 | com_crashlytics_export_strings.xml 283 | crashlytics.properties 284 | crashlytics-build.properties 285 | fabric.properties 286 | 287 | ### AndroidStudio Patch ### 288 | 289 | !/gradle/wrapper/gradle-wrapper.jar 290 | 291 | # End of https://www.toptal.com/developers/gitignore/api/androidstudio,xcode,macos,kotlin,swift,swiftpackagemanager 292 | -------------------------------------------------------------------------------- /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 | # Use the maximum available, or set MAX_FD != -1 to use that value. 89 | MAX_FD=maximum 90 | 91 | warn () { 92 | echo "$*" 93 | } >&2 94 | 95 | die () { 96 | echo 97 | echo "$*" 98 | echo 99 | exit 1 100 | } >&2 101 | 102 | # OS specific support (must be 'true' or 'false'). 103 | cygwin=false 104 | msys=false 105 | darwin=false 106 | nonstop=false 107 | case "$( uname )" in #( 108 | CYGWIN* ) cygwin=true ;; #( 109 | Darwin* ) darwin=true ;; #( 110 | MSYS* | MINGW* ) msys=true ;; #( 111 | NONSTOP* ) nonstop=true ;; 112 | esac 113 | 114 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 115 | 116 | 117 | # Determine the Java command to use to start the JVM. 118 | if [ -n "$JAVA_HOME" ] ; then 119 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 120 | # IBM's JDK on AIX uses strange locations for the executables 121 | JAVACMD=$JAVA_HOME/jre/sh/java 122 | else 123 | JAVACMD=$JAVA_HOME/bin/java 124 | fi 125 | if [ ! -x "$JAVACMD" ] ; then 126 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 127 | 128 | Please set the JAVA_HOME variable in your environment to match the 129 | location of your Java installation." 130 | fi 131 | else 132 | JAVACMD=java 133 | if ! command -v java >/dev/null 2>&1 134 | then 135 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 136 | 137 | Please set the JAVA_HOME variable in your environment to match the 138 | location of your Java installation." 139 | fi 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 | 201 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 202 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 203 | 204 | # Collect all arguments for the java command; 205 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 206 | # shell script including quotes and variable substitutions, so put them in 207 | # double quotes to make sure that they get re-expanded; and 208 | # * put everything else in single quotes, so that it's not re-expanded. 209 | 210 | set -- \ 211 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 212 | -classpath "$CLASSPATH" \ 213 | org.gradle.wrapper.GradleWrapperMain \ 214 | "$@" 215 | 216 | # Stop when "xargs" is not available. 217 | if ! command -v xargs >/dev/null 2>&1 218 | then 219 | die "xargs is not available" 220 | fi 221 | 222 | # Use "xargs" to parse quoted args. 223 | # 224 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 225 | # 226 | # In Bash we could simply go: 227 | # 228 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 229 | # set -- "${ARGS[@]}" "$@" 230 | # 231 | # but POSIX shell has neither arrays nor command substitution, so instead we 232 | # post-process each arg (as a line of input to sed) to backslash-escape any 233 | # character that might be a shell metacharacter, then use eval to reverse 234 | # that process (while maintaining the separation between arguments), and wrap 235 | # the whole thing up as a single "set" statement. 236 | # 237 | # This will of course break if any of these variables contains a newline or 238 | # an unmatched quote. 239 | # 240 | 241 | eval "set -- $( 242 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 243 | xargs -n1 | 244 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 245 | tr '\n' ' ' 246 | )" '"$@"' 247 | 248 | exec "$JAVACMD" "$@" 249 | -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/JsonPatchEditingContextImpl.kt: -------------------------------------------------------------------------------- 1 | package com.reidsync.kxjsonpatch 2 | 3 | import kotlinx.serialization.json.* 4 | 5 | /* 6 | * Copyright 2023 Reid Byun. 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | class JsonPatchEditingContextImpl(var source: JsonElement): JsonPatchEditingContext { 22 | override fun remove(path: List) { 23 | source = editElement(source, path, action = { root -> 24 | if (path.isEmpty()) { 25 | throw JsonPatchApplicationException("[Remove Operation] path is empty") 26 | } 27 | else { 28 | var parentNode = root//getParentNode(root, searchPath) 29 | if (parentNode == null) { 30 | throw JsonPatchApplicationException("[Remove Operation] noSuchPath in source, path provided : " + path) 31 | } 32 | else { 33 | val fieldToRemove = path[path.size - 1].replace("\"".toRegex(), "") 34 | if (parentNode is JsonObject) { 35 | val copyp = parentNode.remove(fieldToRemove) 36 | println(parentNode) 37 | println(copyp) 38 | println(root) 39 | parentNode = copyp 40 | } 41 | else if (parentNode is JsonArray) { 42 | parentNode = parentNode.remove(arrayIndex(fieldToRemove, parentNode.size - 1)) 43 | //return parentNode 44 | } 45 | else { 46 | throw JsonPatchApplicationException("[Remove Operation] noSuchPath in source, path provided : " + path) 47 | } 48 | } 49 | parentNode 50 | }}) ?: source 51 | } 52 | 53 | override fun replace(path: List, value: JsonElement) { 54 | source = editElement(source, path, action = { root -> 55 | if (path.isEmpty()) { 56 | throw JsonPatchApplicationException("[Replace Operation] path is empty") 57 | } else { 58 | var parentNode = getParentNode(source, path) 59 | if (parentNode == null) { 60 | throw JsonPatchApplicationException("[Replace Operation] noSuchPath in source, path provided : " + path) 61 | } else { 62 | val fieldToReplace = path[path.size - 1].replace("\"".toRegex(), "") 63 | if (fieldToReplace.isEmpty() && path.size == 1) { 64 | parentNode = value 65 | } 66 | else if (parentNode is JsonObject) { 67 | parentNode = parentNode.add(fieldToReplace, value) 68 | } 69 | else if (parentNode is JsonArray) { 70 | parentNode = parentNode.set(arrayIndex(fieldToReplace, parentNode.size - 1), value) 71 | } 72 | else { 73 | throw JsonPatchApplicationException("[Replace Operation] noSuchPath in source, path provided : " + path) 74 | } 75 | parentNode 76 | } 77 | } 78 | }) ?: source 79 | } 80 | 81 | override fun add(path: List, value: JsonElement) { 82 | source = editElement(source, path, action = { root -> 83 | if (path.isEmpty()) { 84 | throw JsonPatchApplicationException("[ADD Operation] path is empty , path : ") 85 | } else { 86 | var parentNode = root//getParentNode(root, searchPath) 87 | if (parentNode == null) { 88 | throw JsonPatchApplicationException("[ADD Operation] noSuchPath in source, path provided : " + path) 89 | } else { 90 | val fieldToReplace = path[path.size - 1].replace("\"".toRegex(), "") 91 | if (fieldToReplace == "" && path.size == 1) 92 | parentNode = value 93 | else if (!parentNode.isContainerNode()) { 94 | throw JsonPatchApplicationException("[ADD Operation] parent is not a container in source, path provided : $path | node : $parentNode") 95 | } 96 | else if (parentNode is JsonArray) { 97 | parentNode = addToArray(path, value, parentNode) 98 | } 99 | else { 100 | parentNode = addToObject(path, parentNode, value) 101 | } 102 | } 103 | parentNode 104 | } 105 | }) ?: source 106 | } 107 | 108 | override fun move(fromPath: List, toPath: List) { 109 | val parentNode = getParentNode(source, fromPath) 110 | val field = fromPath[fromPath.size - 1].replace("\"".toRegex(), "") 111 | val valueNode = if (parentNode!! is JsonArray) { 112 | parentNode.jsonArray[field.toInt()] 113 | } 114 | else { 115 | parentNode.jsonObject[field] 116 | } 117 | 118 | remove(fromPath) 119 | add(toPath, valueNode!!) 120 | } 121 | 122 | override fun copy(fromPath: List, toPath: List) { 123 | val parentNode = getParentNode(source, fromPath) 124 | val field = fromPath[fromPath.size - 1].replace("\"".toRegex(), "") 125 | val valueNode = if (parentNode!! is JsonArray) { 126 | parentNode.jsonArray[field.toInt()] 127 | } 128 | else { 129 | parentNode.jsonObject[field] 130 | } 131 | add(toPath, valueNode!!) 132 | } 133 | 134 | override fun test(path: List, value: JsonElement) { 135 | source = editElement(source, path, action = { root -> 136 | if (path.isEmpty()) { 137 | throw JsonPatchApplicationException("[TEST Operation] path is empty , path : ") 138 | } else { 139 | var parentNode = root 140 | if (parentNode == null) { 141 | throw JsonPatchApplicationException("[TEST Operation] noSuchPath in source, path provided : " + path) 142 | } 143 | else { 144 | val fieldToReplace = path[path.size - 1].replace("\"".toRegex(), "") 145 | if (fieldToReplace == "" && path.size == 1) 146 | parentNode = value 147 | else if (!parentNode.isContainerNode()) 148 | throw JsonPatchApplicationException("[TEST Operation] parent is not a container in source, path provided : $path | node : $parentNode") 149 | else if (parentNode is JsonArray) { 150 | val target = parentNode 151 | val idxStr = path[path.size - 1] 152 | 153 | if ("-" == idxStr) { 154 | // see http://tools.ietf.org/html/rfc6902#section-4.1 155 | if (target.get(target.size - 1) != value) { 156 | throw JsonPatchApplicationException("[TEST Operation] value mismatch") 157 | } 158 | } else { 159 | val idx = arrayIndex(idxStr.replace("\"".toRegex(), ""), target.size) 160 | if (target.get(idx) != value) { 161 | throw JsonPatchApplicationException("[TEST Operation] value mismatch") 162 | } 163 | } 164 | } else { 165 | val target = parentNode as JsonObject 166 | val key = path[path.size - 1].replace("\"".toRegex(), "") 167 | if (target.get(key) != value) { 168 | throw JsonPatchApplicationException("[TEST Operation] value mismatch") 169 | } 170 | } 171 | parentNode 172 | } 173 | } 174 | }) ?: source 175 | } 176 | 177 | private fun getParentNode(source: JsonElement, fromPath: List): JsonElement? { 178 | val pathToParent = fromPath.subList(0, fromPath.size - 1) // would never by out of bound, lets see 179 | return getNode(source, pathToParent, 1) 180 | } 181 | 182 | private fun getNode(ret: JsonElement, path: List, pos_: Int): JsonElement? { 183 | var pos = pos_ 184 | if (pos >= path.size) { 185 | return ret 186 | } 187 | val key = path[pos] 188 | if (ret is JsonArray) { 189 | val keyInt = (key.replace("\"".toRegex(), "")).toInt() 190 | return getNode(ret[keyInt], path, ++pos) 191 | } else if (ret is JsonObject) { 192 | if (ret.containsKey(key)) { 193 | return getNode(ret[key]!!, path, ++pos) 194 | } 195 | return null 196 | } else { 197 | return ret 198 | } 199 | } 200 | 201 | private fun editElement(source: JsonElement, fromPath: List, action: (JsonElement)-> JsonElement?): JsonElement? { 202 | val pathToParent = fromPath.subList(0, fromPath.size - 1) // would never by out of bound, lets see 203 | return findAndAction(source, pathToParent, 1, action) 204 | } 205 | 206 | private fun findAndAction(ret: JsonElement, path: List, pos_: Int, action: (JsonElement)-> JsonElement?): JsonElement? { 207 | var pos = pos_ 208 | if (pos >= path.size) { 209 | // Result 210 | return action(ret) 211 | } 212 | val key = path[pos] 213 | if (ret is JsonArray) { 214 | val keyInt = (key.replace("\"".toRegex(), "")).toInt() 215 | return ret.set(keyInt, findAndAction(ret[keyInt], path, ++pos, action)) 216 | } 217 | else if (ret is JsonObject) { 218 | if (ret.containsKey(key)) { 219 | return ret.set(key, findAndAction(ret[key]!!, path, ++pos, action)) 220 | } 221 | return null 222 | } else { 223 | // Result 224 | return action(ret) 225 | } 226 | } 227 | 228 | private fun arrayIndex(s: String, max: Int): Int { 229 | val index = s.toInt() 230 | if (index < 0) { 231 | throw JsonPatchApplicationException("index Out of bound, index is negative") 232 | } else if (index > max) { 233 | throw JsonPatchApplicationException("index Out of bound, index is greater than " + max) 234 | } 235 | return index 236 | } 237 | 238 | private fun addToObject(path: List, node: JsonElement, value: JsonElement): JsonObject { 239 | val target = node as JsonObject 240 | val key = path[path.size - 1].replace("\"".toRegex(), "") 241 | 242 | return target.add(key, value) 243 | } 244 | 245 | private fun addToArray(path: List, value: JsonElement, parentNode: JsonElement): JsonElement { 246 | var target = parentNode as JsonArray 247 | val idxStr = path[path.size - 1] 248 | 249 | if ("-" == idxStr) { 250 | // see http://tools.ietf.org/html/rfc6902#section-4.1 251 | //target.add(value) 252 | target = target.add(value) 253 | } else { 254 | //val idx = arrayIndex(idxStr.replace("\"".toRegex(), ""), target.size()) 255 | val idx = arrayIndex(idxStr.replace("\"".toRegex(), ""), target.size) 256 | target = target.insert(idx, value) 257 | } 258 | 259 | return target 260 | } 261 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonTest/kotlin/resources/js-libs-samples.json.kt: -------------------------------------------------------------------------------- 1 | package resources.testdata 2 | 3 | const val TestData_JS_LIB_SAMPLES: String = """ 4 | { 5 | "errors": [ 6 | { "node": {"bar": [1, 2]}, 7 | "op": [{"op": "add", "path": "/bar/8", "value": "5"}], 8 | "message": "Out of bounds (upper)" }, 9 | 10 | { "node": {"bar": [1, 2]}, 11 | "op": [{"op": "add", "path": "/bar/-1", "value": "5"}], 12 | "message": "Out of bounds (lower)" }, 13 | 14 | { "node": ["foo", "sil"], 15 | "op": [{"op": "add", "path": "/bar", "value": 42}], 16 | "message": "Object operation on array target" }, 17 | 18 | { "node": {"foo": 1, "baz": [{"qux": "hello"}]}, 19 | "op": [{"op": "remove", "path": "/baz/1e0/qux"}], 20 | "message": "remove op shouldn't remove from array with bad number" }, 21 | 22 | { "node": [1, 2, 3, 4], 23 | "op": [{"op": "remove", "path": "/1e0"}], 24 | "message": "remove op shouldn't remove from array with bad number" }, 25 | 26 | { "node": [""], 27 | "op": [{"op": "replace", "path": "/1e0", "value": false}], 28 | "message": "replace op shouldn't replace in array with bad number" }, 29 | 30 | { "node": {"baz": [1,2,3], "bar": 1}, 31 | "op": [{"op": "copy", "from": "/baz/1e0", "path": "/boo"}], 32 | "message": "copy op shouldn't work with bad number" }, 33 | 34 | { "node": {"foo": 1, "baz": [1,2,3,4]}, 35 | "op": [{"op": "move", "from": "/baz/1e0", "path": "/foo"}], 36 | "message": "move op shouldn't work with bad number" }, 37 | 38 | { "node": ["foo", "sil"], 39 | "op": [{"op": "add", "path": "/1e0", "value": "bar"}], 40 | "message": "add op shouldn't add to array with bad number" }, 41 | 42 | { "node": [ 1 ], 43 | "op": [ { "op": "add", "path": "/-" } ], 44 | "message": "missing 'value' parameter" }, 45 | 46 | { "node": [ 1 ], 47 | "op": [ { "op": "replace", "path": "/0" } ], 48 | "message": "missing 'value' parameter" }, 49 | 50 | { "node": [ null ], 51 | "op": [ { "op": "test", "path": "/0" } ], 52 | "message": "missing 'value' parameter" }, 53 | 54 | { "node": [ false ], 55 | "op": [ { "op": "test", "path": "/0" } ], 56 | "message": "missing 'value' parameter" }, 57 | 58 | { "node": [ 1 ], 59 | "op": [ { "op": "copy", "path": "/-" } ], 60 | "message": "missing 'from' parameter" }, 61 | 62 | { "node": { "foo": 1 }, 63 | "op": [ { "op": "move", "path": "" } ], 64 | "message": "missing 'from' parameter" }, 65 | 66 | { "node": { "foo": "bar" }, 67 | "op": [ { "op": "add", "path": "/baz", "value": "qux", 68 | "op": "move", "from":"/foo" } ], 69 | "message": "patch has two 'op' members", 70 | "disabled": true }, 71 | 72 | { "node": {"foo": 1}, 73 | "op": [{"op": "spam", "path": "/foo", "value": 1}], 74 | "message": "Unrecognized op 'spam'" } 75 | 76 | ], 77 | "ops": [ 78 | { "message": "replacing the root of the document is possible with add", 79 | "node": {"foo": "bar"}, 80 | "op": [{"op": "add", "path": "", "value": {"baz": "qux"}}], 81 | "expected": {"baz":"qux"}}, 82 | 83 | { "message": "replacing the root of the document is possible with add", 84 | "node": {"foo": "bar"}, 85 | "op": [{"op": "add", "path": "", "value": ["baz", "qux"]}], 86 | "expected": ["baz", "qux"]}, 87 | 88 | { "message": "empty list, empty docs", 89 | "node": {}, 90 | "op": [], 91 | "expected": {} }, 92 | 93 | { "message": "empty patch list", 94 | "node": {"foo": 1}, 95 | "op": [], 96 | "expected": {"foo": 1} }, 97 | 98 | { "message": "rearrangements OK?", 99 | "node": {"foo": 1, "bar": 2}, 100 | "op": [], 101 | "expected": {"bar":2, "foo": 1} }, 102 | 103 | { "message": "rearrangements OK? How about one level down ... array", 104 | "node": [{"foo": 1, "bar": 2}], 105 | "op": [], 106 | "expected": [{"bar":2, "foo": 1}] }, 107 | 108 | { "message": "rearrangements OK? How about one level down...", 109 | "node": {"foo":{"foo": 1, "bar": 2}}, 110 | "op": [], 111 | "expected": {"foo":{"bar":2, "foo": 1}} }, 112 | 113 | { "message": "add replaces any existing field", 114 | "node": {"foo": null}, 115 | "op": [{"op": "add", "path": "/foo", "value":1}], 116 | "expected": {"foo": 1} }, 117 | 118 | { "message": "toplevel array", 119 | "node": [], 120 | "op": [{"op": "add", "path": "/0", "value": "foo"}], 121 | "expected": ["foo"] }, 122 | 123 | { "message": "toplevel array, no change", 124 | "node": ["foo"], 125 | "op": [], 126 | "expected": ["foo"] }, 127 | 128 | { "message": "toplevel object, numeric string", 129 | "node": {}, 130 | "op": [{"op": "add", "path": "/foo", "value": "1"}], 131 | "expected": {"foo":"1"} }, 132 | 133 | { "message": "toplevel object, integer", 134 | "node": {}, 135 | "op": [{"op": "add", "path": "/foo", "value": 1}], 136 | "expected": {"foo":1} }, 137 | 138 | { "message": "Toplevel scalar values OK?", 139 | "node": "foo", 140 | "op": [{"op": "replace", "path": "", "value": "bar"}], 141 | "expected": "bar", 142 | "disabled": true }, 143 | 144 | { "message": "Add, / target", 145 | "node": {}, 146 | "op": [ {"op": "add", "path": "/", "value":1 } ], 147 | "expected": {"":1} }, 148 | 149 | { "message": "Add composite value at top level", 150 | "node": {"foo": 1}, 151 | "op": [{"op": "add", "path": "/bar", "value": [1, 2]}], 152 | "expected": {"foo": 1, "bar": [1, 2]} }, 153 | 154 | { "message": "Add into composite value", 155 | "node": {"foo": 1, "baz": [{"qux": "hello"}]}, 156 | "op": [{"op": "add", "path": "/baz/0/foo", "value": "world"}], 157 | "expected": {"foo": 1, "baz": [{"qux": "hello", "foo": "world"}]} }, 158 | 159 | { "node": {"foo": 1}, 160 | "op": [{"op": "add", "path": "/bar", "value": true}], 161 | "expected": {"foo": 1, "bar": true} }, 162 | 163 | { "node": {"foo": 1}, 164 | "op": [{"op": "add", "path": "/bar", "value": false}], 165 | "expected": {"foo": 1, "bar": false} }, 166 | 167 | { "node": {"foo": 1}, 168 | "op": [{"op": "add", "path": "/bar", "value": null}], 169 | "expected": {"foo": 1, "bar": null} }, 170 | 171 | { "message": "0 can be an array index or object element name", 172 | "node": {"foo": 1}, 173 | "op": [{"op": "add", "path": "/0", "value": "bar"}], 174 | "expected": {"foo": 1, "0": "bar" } }, 175 | 176 | { "node": ["foo"], 177 | "op": [{"op": "add", "path": "/1", "value": "bar"}], 178 | "expected": ["foo", "bar"] }, 179 | 180 | { "node": ["foo", "sil"], 181 | "op": [{"op": "add", "path": "/1", "value": "bar"}], 182 | "expected": ["foo", "bar", "sil"] }, 183 | 184 | { "node": ["foo", "sil"], 185 | "op": [{"op": "add", "path": "/0", "value": "bar"}], 186 | "expected": ["bar", "foo", "sil"] }, 187 | 188 | { "node": ["foo", "sil"], 189 | "op": [{"op":"add", "path": "/2", "value": "bar"}], 190 | "expected": ["foo", "sil", "bar"] }, 191 | 192 | { "node": ["foo", "sil"], 193 | "op": [{"op": "add", "path": "/1", "value": ["bar", "baz"]}], 194 | "expected": ["foo", ["bar", "baz"], "sil"], 195 | "message": "value in array add not flattened" }, 196 | 197 | { "node": {"foo": 1, "bar": [1, 2, 3, 4]}, 198 | "op": [{"op": "remove", "path": "/bar"}], 199 | "expected": {"foo": 1} }, 200 | 201 | { "node": {"foo": 1, "baz": [{"qux": "hello"}]}, 202 | "op": [{"op": "remove", "path": "/baz/0/qux"}], 203 | "expected": {"foo": 1, "baz": [{}]} }, 204 | 205 | { "node": {"foo": 1, "baz": [{"qux": "hello"}]}, 206 | "op": [{"op": "replace", "path": "/foo", "value": [1, 2, 3, 4]}], 207 | "expected": {"foo": [1, 2, 3, 4], "baz": [{"qux": "hello"}]} }, 208 | 209 | { "node": {"foo": [1, 2, 3, 4], "baz": [{"qux": "hello"}]}, 210 | "op": [{"op": "replace", "path": "/baz/0/qux", "value": "world"}], 211 | "expected": {"foo": [1, 2, 3, 4], "baz": [{"qux": "world"}]} }, 212 | 213 | { "node": ["foo"], 214 | "op": [{"op": "replace", "path": "/0", "value": "bar"}], 215 | "expected": ["bar"] }, 216 | 217 | { "node": [""], 218 | "op": [{"op": "replace", "path": "/0", "value": 0}], 219 | "expected": [0] }, 220 | 221 | { "node": [""], 222 | "op": [{"op": "replace", "path": "/0", "value": true}], 223 | "expected": [true] }, 224 | 225 | { "node": [""], 226 | "op": [{"op": "replace", "path": "/0", "value": false}], 227 | "expected": [false] }, 228 | 229 | { "node": [""], 230 | "op": [{"op": "replace", "path": "/0", "value": null}], 231 | "expected": [null] }, 232 | 233 | { "node": ["foo", "sil"], 234 | "op": [{"op": "replace", "path": "/1", "value": ["bar", "baz"]}], 235 | "expected": ["foo", ["bar", "baz"]], 236 | "message": "value in array replace not flattened" }, 237 | 238 | { "message": "replace whole document", 239 | "node": {"foo": "bar"}, 240 | "op": [{"op": "replace", "path": "", "value": {"baz": "qux"}}], 241 | "expected": {"baz": "qux"} }, 242 | 243 | { "node": {"foo": null}, 244 | "op": [{"op": "replace", "path": "/foo", "value": "truthy"}], 245 | "expected": {"foo": "truthy"}, 246 | "message": "null value should be valid obj property to be replaced with something truthy" }, 247 | 248 | { "node": {"foo": null}, 249 | "op": [{"op": "remove", "path": "/foo"}], 250 | "expected": {}, 251 | "message": "null value should be valid obj property to be removed" }, 252 | 253 | { "node": {"foo": "bar"}, 254 | "op": [{"op": "replace", "path": "/foo", "value": null}], 255 | "expected": {"foo": null}, 256 | "message": "null value should still be valid obj property replace other value" }, 257 | 258 | { "message": "Move to same location has no effect", 259 | "node": {"foo": 1}, 260 | "op": [{"op": "move", "from": "/foo", "path": "/foo"}], 261 | "expected": {"foo": 1} }, 262 | 263 | { "node": {"foo": 1, "baz": [{"qux": "hello"}]}, 264 | "op": [{"op": "move", "from": "/foo", "path": "/bar"}], 265 | "expected": {"baz": [{"qux": "hello"}], "bar": 1} }, 266 | 267 | { "node": {"baz": [{"qux": "hello"}], "bar": 1}, 268 | "op": [{"op": "move", "from": "/baz/0/qux", "path": "/baz/1"}], 269 | "expected": {"baz": [{}, "hello"], "bar": 1} }, 270 | 271 | { "message": "Adding to \"/-\" adds to the end of the array", 272 | "node": [ 1, 2 ], 273 | "op": [ { "op": "add", "path": "/-", "value": { "foo": [ "bar", "baz" ] } } ], 274 | "expected": [ 1, 2, { "foo": [ "bar", "baz" ] } ]}, 275 | 276 | { "message": "Adding to \"/-\" adds to the end of the array, even n levels down", 277 | "node": [ 1, 2, [ 3, [ 4, 5 ] ] ], 278 | "op": [ { "op": "add", "path": "/2/1/-", "value": { "foo": [ "bar", "baz" ] } } ], 279 | "expected": [ 1, 2, [ 3, [ 4, 5, { "foo": [ "bar", "baz" ] } ] ] ]}, 280 | 281 | { "message": "test remove on array", 282 | "node": [1, 2, 3, 4], 283 | "op": [{"op": "remove", "path": "/0"}], 284 | "expected": [2, 3, 4] }, 285 | 286 | { "message": "test repeated removes", 287 | "node": [1, 2, 3, 4], 288 | "op": [{ "op": "remove", "path": "/1" }, 289 | { "op": "remove", "path": "/2" }], 290 | "expected": [1, 3] } 291 | ] 292 | } 293 | """ -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/lcs/SequencesComparator.kt: -------------------------------------------------------------------------------- 1 | package com.reidsync.kxjsonpatch.lcs 2 | 3 | import kotlin.jvm.JvmOverloads 4 | 5 | /* 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | /** 22 | * This class allows to compare two objects sequences. 23 | * 24 | * 25 | * The two sequences can hold any object type, as only the `equals` 26 | * method is used to compare the elements of the sequences. It is guaranteed 27 | * that the comparisons will always be done as `o1.equals(o2)` where 28 | * `o1` belongs to the first sequence and `o2` belongs to 29 | * the second sequence. This can be important if subclassing is used for some 30 | * elements in the first sequence and the `equals` method is 31 | * specialized. 32 | * 33 | * 34 | * Comparison can be seen from two points of view: either as giving the smallest 35 | * modification allowing to transform the first sequence into the second one, or 36 | * as giving the longest sequence which is a subsequence of both initial 37 | * sequences. The `equals` method is used to compare objects, so any 38 | * object can be put into sequences. Modifications include deleting, inserting 39 | * or keeping one object, starting from the beginning of the first sequence. 40 | * 41 | * 42 | * This class implements the comparison algorithm, which is the very efficient 43 | * algorithm from Eugene W. Myers 44 | * [ 45 | * An O(ND) Difference Algorithm and Its Variations](http://www.cis.upenn.edu/~bcpierce/courses/dd/papers/diff.ps). This algorithm produces 46 | * the shortest possible 47 | * [edit script][EditScript] 48 | * containing all the 49 | * [commands][EditCommand] 50 | * needed to transform the first sequence into the second one. 51 | * 52 | * @see EditScript 53 | * 54 | * @see EditCommand 55 | * 56 | * @see CommandVisitor 57 | * 58 | * 59 | * @since 4.0 60 | * @version $Id: SequencesComparator.java 1540567 2013-11-10 22:19:29Z tn $ 61 | */ 62 | 63 | class SequencesComparator @JvmOverloads constructor( 64 | //class SequencesComparator constructor( 65 | sequence1: List, 66 | sequence2: List, 67 | equator: Equator = DefaultEquator.defaultEquator() 68 | ) { 69 | /** First sequence. */ 70 | private val sequence1: List 71 | 72 | /** Second sequence. */ 73 | private val sequence2: List 74 | 75 | /** The equator used for testing object equality. */ 76 | private val equator: Equator 77 | 78 | /** Temporary variables. */ 79 | private val vDown: IntArray 80 | private val vUp: IntArray 81 | /** 82 | * Simple constructor. 83 | * 84 | * 85 | * Creates a new instance of SequencesComparator with a custom [Equator]. 86 | * 87 | * 88 | * It is *guaranteed* that the comparisons will always be done as 89 | * `Equator.equate(o1, o2)` where `o1` belongs to the first 90 | * sequence and `o2` belongs to the second sequence. 91 | * 92 | * @param sequence1 first sequence to be compared 93 | * @param sequence2 second sequence to be compared 94 | * @param equator the equator to use for testing object equality 95 | */ 96 | /** 97 | * Simple constructor. 98 | * 99 | * 100 | * Creates a new instance of SequencesComparator using a [DefaultEquator]. 101 | * 102 | * 103 | * It is *guaranteed* that the comparisons will always be done as 104 | * `o1.equals(o2)` where `o1` belongs to the first 105 | * sequence and `o2` belongs to the second sequence. This can be 106 | * important if subclassing is used for some elements in the first sequence 107 | * and the `equals` method is specialized. 108 | * 109 | * @param sequence1 first sequence to be compared 110 | * @param sequence2 second sequence to be compared 111 | */ 112 | init { 113 | this.sequence1 = sequence1 114 | this.sequence2 = sequence2 115 | this.equator = equator 116 | val size = sequence1.size + sequence2.size + 2 117 | vDown = IntArray(size) 118 | vUp = IntArray(size) 119 | } 120 | 121 | /** 122 | * Get the [EditScript] object. 123 | * 124 | * 125 | * It is guaranteed that the objects embedded in the [ insert commands][InsertCommand] come from the second sequence and that the objects 126 | * embedded in either the [delete commands][DeleteCommand] or 127 | * [keep commands][KeepCommand] come from the first sequence. This can 128 | * be important if subclassing is used for some elements in the first 129 | * sequence and the `equals` method is specialized. 130 | * 131 | * @return the edit script resulting from the comparison of the two 132 | * sequences 133 | */ 134 | fun getScript(): EditScript { 135 | val script = EditScript() 136 | buildScript(0, sequence1.size, 0, sequence2.size, script) 137 | return script 138 | } 139 | 140 | /** 141 | * Build a snake. 142 | * 143 | * @param start the value of the start of the snake 144 | * @param diag the value of the diagonal of the snake 145 | * @param end1 the value of the end of the first sequence to be compared 146 | * @param end2 the value of the end of the second sequence to be compared 147 | * @return the snake built 148 | */ 149 | private fun buildSnake(start: Int, diag: Int, end1: Int, end2: Int): Snake { 150 | var end = start 151 | while (end - diag < end2 && end < end1 && equator.equate( 152 | sequence1[end], 153 | sequence2[end - diag] 154 | ) 155 | ) { 156 | ++end 157 | } 158 | return Snake(start, end, diag) 159 | } 160 | 161 | /** 162 | * Get the middle snake corresponding to two subsequences of the 163 | * main sequences. 164 | * 165 | * 166 | * The snake is found using the MYERS Algorithm (this algorithms has 167 | * also been implemented in the GNU diff program). This algorithm is 168 | * explained in Eugene Myers article: 169 | * [ 170 | * An O(ND) Difference Algorithm and Its Variations](http://www.cs.arizona.edu/people/gene/PAPERS/diff.ps). 171 | * 172 | * @param start1 the begin of the first sequence to be compared 173 | * @param end1 the end of the first sequence to be compared 174 | * @param start2 the begin of the second sequence to be compared 175 | * @param end2 the end of the second sequence to be compared 176 | * @return the middle snake 177 | */ 178 | private fun getMiddleSnake(start1: Int, end1: Int, start2: Int, end2: Int): Snake? { 179 | // Myers Algorithm 180 | // Initialisations 181 | val m = end1 - start1 182 | val n = end2 - start2 183 | if (m == 0 || n == 0) { 184 | return null 185 | } 186 | val delta = m - n 187 | val sum = n + m 188 | val offset = (if (sum % 2 == 0) sum else sum + 1) / 2 189 | vDown[1 + offset] = start1 190 | vUp[1 + offset] = end1 + 1 191 | for (d in 0..offset) { 192 | // Down 193 | run { 194 | var k = -d 195 | while (k <= d) { 196 | 197 | // First step 198 | val i = k + offset 199 | if (k == -d || k != d && vDown[i - 1] < vDown[i + 1]) { 200 | vDown[i] = vDown[i + 1] 201 | } else { 202 | vDown[i] = vDown[i - 1] + 1 203 | } 204 | var x = vDown[i] 205 | var y = x - start1 + start2 - k 206 | while (x < end1 && y < end2 && equator.equate( 207 | sequence1[x], 208 | sequence2[y] 209 | ) 210 | ) { 211 | vDown[i] = ++x 212 | ++y 213 | } 214 | // Second step 215 | if (delta % 2 != 0 && delta - d <= k && k <= delta + d) { 216 | if (vUp[i - delta] <= vDown[i]) { 217 | return buildSnake(vUp[i - delta], k + start1 - start2, end1, end2) 218 | } 219 | } 220 | k += 2 221 | } 222 | } 223 | 224 | // Up 225 | var k = delta - d 226 | while (k <= delta + d) { 227 | 228 | // First step 229 | val i = k + offset - delta 230 | if (k == delta - d 231 | || k != delta + d && vUp[i + 1] <= vUp[i - 1] 232 | ) { 233 | vUp[i] = vUp[i + 1] - 1 234 | } else { 235 | vUp[i] = vUp[i - 1] 236 | } 237 | var x = vUp[i] - 1 238 | var y = x - start1 + start2 - k 239 | while (x >= start1 && y >= start2 && equator.equate(sequence1[x], sequence2[y])) { 240 | vUp[i] = x-- 241 | y-- 242 | } 243 | // Second step 244 | if (delta % 2 == 0 && -d <= k && k <= d) { 245 | if (vUp[i] <= vDown[i + delta]) { 246 | return buildSnake(vUp[i], k + start1 - start2, end1, end2) 247 | } 248 | } 249 | k += 2 250 | } 251 | } 252 | throw RuntimeException("Internal Error") 253 | } 254 | 255 | /** 256 | * Build an edit script. 257 | * 258 | * @param start1 the begin of the first sequence to be compared 259 | * @param end1 the end of the first sequence to be compared 260 | * @param start2 the begin of the second sequence to be compared 261 | * @param end2 the end of the second sequence to be compared 262 | * @param script the edited script 263 | */ 264 | private fun buildScript( 265 | start1: Int, end1: Int, start2: Int, end2: Int, 266 | script: EditScript 267 | ) { 268 | val middle = getMiddleSnake(start1, end1, start2, end2) 269 | if (middle == null || middle.start === end1 && middle.diag === end1 - end2 || middle.end === start1 && middle.diag === start1 - start2) { 270 | var i = start1 271 | var j = start2 272 | while (i < end1 || j < end2) { 273 | if (i < end1 && j < end2 && equator.equate(sequence1[i], sequence2[j])) { 274 | script.append(KeepCommand(sequence1[i])) 275 | ++i 276 | ++j 277 | } else { 278 | if (end1 - start1 > end2 - start2) { 279 | script.append(DeleteCommand(sequence1[i])) 280 | ++i 281 | } else { 282 | script.append(InsertCommand(sequence2[j])) 283 | ++j 284 | } 285 | } 286 | } 287 | } else { 288 | buildScript( 289 | start1, middle.start, 290 | start2, middle.start - middle.diag, 291 | script 292 | ) 293 | for (i in middle.start until middle.end) { 294 | script.append(KeepCommand(sequence1[i])) 295 | } 296 | buildScript( 297 | middle.end, end1, 298 | middle.end - middle.diag, end2, 299 | script 300 | ) 301 | } 302 | } 303 | /** 304 | * This class is a simple placeholder to hold the end part of a path 305 | * under construction in a [SequencesComparator]. 306 | */ 307 | 308 | 309 | private class Snake 310 | /** 311 | * Simple constructor. Creates a new instance of Snake with specified indices. 312 | * 313 | * @param start start index of the snake 314 | * @param end end index of the snake 315 | * @param diag diagonal number 316 | */( 317 | /** Start index. */ 318 | val start: Int, 319 | /** End index. */ 320 | val end: Int, 321 | /** Diagonal number. */ 322 | val diag: Int 323 | ) { 324 | /** 325 | * Get the start index of the snake. 326 | * 327 | * @return start index of the snake 328 | */ 329 | /** 330 | * Get the end index of the snake. 331 | * 332 | * @return end index of the snake 333 | */ 334 | /** 335 | * Get the diagonal number of the snake. 336 | * 337 | * @return diagonal number of the snake 338 | */ 339 | 340 | } 341 | } -------------------------------------------------------------------------------- /kotlin-json-patch/src/commonMain/kotlin/com/reidsync/kxjsonpatch/JsonDiff.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 flipkart.com zjsonpatch. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.reidsync.kxjsonpatch 18 | 19 | import com.reidsync.kxjsonpatch.lcs.ListUtils 20 | import kotlinx.serialization.json.* 21 | import kotlin.jvm.JvmStatic 22 | import kotlin.math.min 23 | 24 | object JsonDiff { 25 | internal var op = Operations() 26 | internal var consts = Constants() 27 | 28 | 29 | @JvmStatic 30 | fun asJson(source: JsonElement, target: JsonElement): JsonArray { 31 | val diffs = ArrayList() 32 | val path = ArrayList() 33 | /* 34 | * generating diffs in the order of their occurrence 35 | */ 36 | generateDiffs(diffs, path, source, target) 37 | /* 38 | * Merging remove & add to move operation 39 | */ 40 | compactDiffs(diffs) 41 | /* 42 | * Introduce copy operation 43 | */ 44 | introduceCopyOperation(source, target, diffs) 45 | 46 | return getJsonNodes(diffs) 47 | } 48 | 49 | private fun getMatchingValuePath(unchangedValues: Map>, value: JsonElement): List? { 50 | return unchangedValues[value] 51 | } 52 | 53 | private fun introduceCopyOperation(source: JsonElement, target: JsonElement, diffs: MutableList) { 54 | val unchangedValues = getUnchangedPart(source, target) 55 | for (i in diffs.indices) { 56 | val diff = diffs[i] 57 | if (op.ADD==diff.operation) { 58 | val matchingValuePath = getMatchingValuePath(unchangedValues, diff.value) 59 | if (matchingValuePath != null) { 60 | diffs[i] = Diff(op.COPY, matchingValuePath, diff.path) 61 | } 62 | } 63 | } 64 | } 65 | 66 | private fun getUnchangedPart(source: JsonElement, target: JsonElement): Map> { 67 | val unchangedValues = HashMap>() 68 | computeUnchangedValues(unchangedValues, listOf(), source, target) 69 | return unchangedValues 70 | } 71 | 72 | private fun computeUnchangedValues(unchangedValues: MutableMap>, path: List, source: JsonElement, target: JsonElement) { 73 | if (source == target) { 74 | unchangedValues.put(target, path) 75 | return 76 | } 77 | 78 | val firstType = NodeType.getNodeType(source) 79 | val secondType = NodeType.getNodeType(target) 80 | 81 | if (firstType == secondType) { 82 | when (firstType) { 83 | NodeType.OBJECT -> computeObject(unchangedValues, path, source.jsonObject, target.jsonObject) 84 | NodeType.ARRAY -> computeArray(unchangedValues, path, source.jsonArray, target.jsonArray) 85 | }/* nothing */ 86 | } 87 | } 88 | 89 | private fun computeArray(unchangedValues: MutableMap>, path: List, source: JsonArray, target: JsonArray) { 90 | val size = min(source.size, target.size) 91 | 92 | for (i in 0..size - 1) { 93 | val currPath = getPath(path, i) 94 | computeUnchangedValues(unchangedValues, currPath, source.get(i), target.get(i)) 95 | } 96 | } 97 | 98 | private fun computeObject(unchangedValues: MutableMap>, path: List, source: JsonObject, target: JsonObject) { 99 | //val firstFields = source.entrySet().iterator() 100 | val firstFields = source.iterator() 101 | while (firstFields.hasNext()) { 102 | val name = firstFields.next().key 103 | if (target.containsKey(name)) { 104 | val currPath = getPath(path, name) 105 | computeUnchangedValues(unchangedValues, currPath, source.get(name)!!, target.get(name)!!) 106 | } 107 | } 108 | } 109 | 110 | /** 111 | * This method merge 2 diffs ( remove then add, or vice versa ) with same value into one Move operation, 112 | * all the core logic resides here only 113 | */ 114 | private fun compactDiffs(diffs: MutableList) { 115 | var i=-1 116 | while (++i <=diffs.size-1) { 117 | val diff1 = diffs[i] 118 | 119 | // if not remove OR add, move to next diff 120 | if (!(op.REMOVE==diff1.operation || op.ADD==diff1.operation)) { 121 | continue 122 | } 123 | 124 | for (j in i + 1..diffs.size - 1) { 125 | val diff2 = diffs[j] 126 | if (diff1.value != diff2.value) { 127 | continue 128 | } 129 | 130 | var moveDiff: Diff? = null 131 | if (op.REMOVE==diff1.operation && op.ADD==diff2.operation) { 132 | computeRelativePath(diff2.path, i + 1, j - 1, diffs) 133 | moveDiff = Diff(op.MOVE, diff1.path, diff2.path) 134 | 135 | } else if (op.ADD==diff1.operation && op.REMOVE==diff2.operation) { 136 | computeRelativePath(diff2.path, i, j - 1, diffs) // diff1's add should also be considered 137 | moveDiff = Diff(op.MOVE, diff2.path, diff1.path) 138 | } 139 | if (moveDiff != null) { 140 | diffs.removeAt(j) 141 | diffs[i] = moveDiff 142 | break 143 | } 144 | } 145 | } 146 | } 147 | 148 | //Note : only to be used for arrays 149 | //Finds the longest common Ancestor ending at Array 150 | private fun computeRelativePath(path: MutableList, startIdx: Int, endIdx: Int, diffs: List) { 151 | val counters = ArrayList() 152 | 153 | resetCounters(counters, path.size) 154 | 155 | for (i in startIdx..endIdx) { 156 | val diff = diffs[i] 157 | //Adjust relative path according to #ADD and #Remove 158 | if (op.ADD==diff.operation || op.REMOVE==diff.operation) { 159 | updatePath(path, diff, counters) 160 | } 161 | } 162 | updatePathWithCounters(counters, path) 163 | } 164 | 165 | private fun resetCounters(counters: MutableList, size: Int) { 166 | for (i in 0..size - 1) { 167 | counters.add(0) 168 | } 169 | } 170 | 171 | private fun updatePathWithCounters(counters: List, path: MutableList) { 172 | for (i in counters.indices) { 173 | val value = counters[i] 174 | if (value != 0) { 175 | val currValue = path[i].toString().toInt() 176 | path[i] = (currValue + value).toString() 177 | } 178 | } 179 | } 180 | 181 | private fun updatePath(path: List, pseudo: Diff, counters: MutableList) { 182 | //find longest common prefix of both the paths 183 | 184 | if (pseudo.path.size <= path.size) { 185 | var idx = -1 186 | for (i in 0..pseudo.path.size - 1 - 1) { 187 | if (pseudo.path[i] == path[i]) { 188 | idx = i 189 | } else { 190 | break 191 | } 192 | } 193 | if (idx == pseudo.path.size - 2) { 194 | if (pseudo.path[pseudo.path.size - 1] is Int) { 195 | updateCounters(pseudo, pseudo.path.size - 1, counters) 196 | } 197 | } 198 | } 199 | } 200 | 201 | private fun updateCounters(pseudo: Diff, idx: Int, counters: MutableList) { 202 | if (op.ADD==pseudo.operation) { 203 | counters[idx] = counters[idx] - 1 204 | } else { 205 | if (op.REMOVE==pseudo.operation) { 206 | counters[idx] = counters[idx] + 1 207 | } 208 | } 209 | } 210 | 211 | private fun getJsonNodes(diffs: List): JsonArray { 212 | var patch = JsonArray(emptyList()) 213 | for (diff in diffs) { 214 | val jsonNode = getJsonNode(diff) 215 | patch = patch.add(jsonNode) 216 | } 217 | return patch 218 | } 219 | 220 | private fun getJsonNode(diff: Diff): JsonObject { 221 | var jsonNode = JsonObject(emptyMap()) 222 | jsonNode = jsonNode.addProperty(consts.OP, op.nameFromOp(diff.operation)) 223 | if (op.MOVE==diff.operation || op.COPY==diff.operation) { 224 | jsonNode = jsonNode.addProperty(consts.FROM, getArrayNodeRepresentation(diff.path)) //required {from} only in case of Move Operation 225 | jsonNode = jsonNode.addProperty(consts.PATH, getArrayNodeRepresentation(diff.toPath)) // destination Path 226 | } else { 227 | jsonNode = jsonNode.addProperty(consts.PATH, getArrayNodeRepresentation(diff.path)) 228 | if (op.REMOVE != diff.operation) { 229 | jsonNode = jsonNode.add(consts.VALUE, diff.value) 230 | } 231 | } 232 | return jsonNode 233 | } 234 | 235 | 236 | private fun EncodePath(`object`: Any): String { 237 | val path = `object`.toString() // see http://tools.ietf.org/html/rfc6901#section-4 238 | return path.replace("~".toRegex(), "~0").replace("/".toRegex(), "~1") 239 | } 240 | //join path parts in argument 'path', inserting a '/' between joined elements, starting with '/' and transforming the element of the list with ENCODE_PATH_FUNCTION 241 | private fun getArrayNodeRepresentation(path: List): String { 242 | // return Joiner.on('/').appendTo(new StringBuilder().append('/'), 243 | // Iterables.transform(path, ENCODE_PATH_FUNCTION)).toString(); 244 | val sb = StringBuilder() 245 | for (i in path.indices) { 246 | sb.append('/') 247 | sb.append(EncodePath(path[i])) 248 | 249 | } 250 | return sb.toString() 251 | } 252 | 253 | 254 | 255 | private fun generateDiffs(diffs: MutableList, path: List, source: JsonElement, target: JsonElement) { 256 | if (source != target) { 257 | val sourceType = NodeType.getNodeType(source) 258 | val targetType = NodeType.getNodeType(target) 259 | 260 | if (sourceType == NodeType.ARRAY && targetType == NodeType.ARRAY) { 261 | //both are arrays 262 | compareArray(diffs, path, source.jsonArray, target.jsonArray) 263 | } else if (sourceType == NodeType.OBJECT && targetType == NodeType.OBJECT) { 264 | //both are json 265 | compareObjects(diffs, path, source.jsonObject, target.jsonObject) 266 | } else { 267 | //can be replaced 268 | 269 | diffs.add(Diff.generateDiff(op.REPLACE, path, target)) 270 | } 271 | } 272 | } 273 | 274 | private fun compareArray(diffs: MutableList, path: List, source: JsonArray, target: JsonArray) { 275 | val lcs = getLCS(source, target) 276 | var srcIdx = 0 277 | var targetIdx = 0 278 | var lcsIdx = 0 279 | val srcSize = source.size 280 | val targetSize = target.size 281 | val lcsSize = lcs.size 282 | 283 | var pos = 0 284 | while (lcsIdx < lcsSize) { 285 | val lcsNode = lcs[lcsIdx] 286 | val srcNode = source.get(srcIdx) 287 | val targetNode = target.get(targetIdx) 288 | 289 | 290 | if (lcsNode == srcNode && lcsNode == targetNode) { // Both are same as lcs node, nothing to do here 291 | srcIdx++ 292 | targetIdx++ 293 | lcsIdx++ 294 | pos++ 295 | } else { 296 | if (lcsNode == srcNode) { // src node is same as lcs, but not targetNode 297 | //addition 298 | val currPath = getPath(path, pos) 299 | diffs.add(Diff.generateDiff(op.ADD, currPath, targetNode)) 300 | pos++ 301 | targetIdx++ 302 | } else if (lcsNode == targetNode) { //targetNode node is same as lcs, but not src 303 | //removal, 304 | val currPath = getPath(path, pos) 305 | diffs.add(Diff.generateDiff(op.REMOVE, currPath, srcNode)) 306 | srcIdx++ 307 | } else { 308 | val currPath = getPath(path, pos) 309 | //both are unequal to lcs node 310 | generateDiffs(diffs, currPath, srcNode, targetNode) 311 | srcIdx++ 312 | targetIdx++ 313 | pos++ 314 | } 315 | } 316 | } 317 | 318 | while (srcIdx < srcSize && targetIdx < targetSize) { 319 | val srcNode = source.get(srcIdx) 320 | val targetNode = target.get(targetIdx) 321 | val currPath = getPath(path, pos) 322 | generateDiffs(diffs, currPath, srcNode, targetNode) 323 | srcIdx++ 324 | targetIdx++ 325 | pos++ 326 | } 327 | pos = addRemaining(diffs, path, target, pos, targetIdx, targetSize) 328 | removeRemaining(diffs, path, pos, srcIdx, srcSize, source) 329 | } 330 | 331 | private fun removeRemaining(diffs: MutableList, path: List, pos: Int, srcIdx_: Int, srcSize: Int, source_: JsonElement): Int { 332 | var srcIdx = srcIdx_ 333 | val source = source_.jsonArray 334 | while (srcIdx < srcSize) { 335 | val currPath = getPath(path, pos) 336 | diffs.add(Diff.generateDiff(op.REMOVE, currPath, source.get(srcIdx))) 337 | srcIdx++ 338 | } 339 | return pos 340 | } 341 | 342 | private fun addRemaining(diffs: MutableList, path: List, target_: JsonElement, pos_: Int, targetIdx_: Int, targetSize: Int): Int { 343 | var pos = pos_ 344 | var targetIdx = targetIdx_ 345 | val target = target_.jsonArray 346 | while (targetIdx < targetSize) { 347 | val jsonNode = target.get(targetIdx) 348 | val currPath = getPath(path, pos) 349 | diffs.add(Diff.generateDiff(op.ADD, currPath, jsonNode.deepCopy())) 350 | pos++ 351 | targetIdx++ 352 | } 353 | return pos 354 | } 355 | 356 | private fun compareObjects(diffs: MutableList, path: List, source: JsonObject, target: JsonObject) { 357 | val keysFromSrc = source.iterator() 358 | while (keysFromSrc.hasNext()) { 359 | val key = keysFromSrc.next().key 360 | if (!target.containsKey(key)) { 361 | //remove case 362 | val currPath = getPath(path, key) 363 | diffs.add(Diff.generateDiff(op.REMOVE, currPath, source.get(key)!!)) 364 | continue 365 | } 366 | val currPath = getPath(path, key) 367 | generateDiffs(diffs, currPath, source.get(key)!!, target.get(key)!!) 368 | } 369 | val keysFromTarget = target.iterator() 370 | while (keysFromTarget.hasNext()) { 371 | val key = keysFromTarget.next().key 372 | if (!source.containsKey(key)) { 373 | //add case 374 | val currPath = getPath(path, key) 375 | diffs.add(Diff.generateDiff(op.ADD, currPath, target.get(key)!!)) 376 | } 377 | } 378 | } 379 | 380 | private fun getPath(path: List, key: Any): List { 381 | val toReturn = ArrayList() 382 | toReturn.addAll(path) 383 | toReturn.add(key) 384 | return toReturn 385 | } 386 | 387 | private fun getLCS(first_: JsonElement, second_: JsonElement): List { 388 | if (first_ !is JsonArray) throw IllegalArgumentException("LCS can only work on JSON arrays") 389 | if (second_ !is JsonArray) throw IllegalArgumentException("LCS can only work on JSON arrays") 390 | val first = first_ as JsonArray 391 | val second = second_ as JsonArray 392 | return ListUtils.longestCommonSubsequence(first.toList(),second.toList()) 393 | } 394 | } 395 | 396 | 397 | --------------------------------------------------------------------------------