Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DRAFT WORK IN PROGRESS] Prototype of JSON schema codegen #2205

Closed
wants to merge 24 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ buildscript {
}
dependencies {
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$navigationVersion"
classpath 'com.android.tools.build:gradle:8.2.0'
classpath 'com.android.tools.build:gradle:8.2.1'
classpath 'com.google.gms:google-services:4.3.15'
classpath "com.pascalwelsch.gitversioner:gitversioner:0.5.0"

Expand Down
2 changes: 2 additions & 0 deletions ground/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,8 @@ dependencies {
stagingImplementation "androidx.fragment:fragment-testing:$fragmentVersion"

implementation "com.google.guava:guava:31.1-android"

implementation project(":shared")
}

// Allow references to generated code.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.android.ground.persistence.remote.firebase

import com.google.ground.shared.schema.GeometryObject
import com.google.ground.shared.schema.MultiPolygonObject
import com.google.ground.shared.schema.PointObject
import com.google.ground.shared.schema.PolygonObject
import com.google.gson.GsonBuilder
import com.google.gson.JsonArray
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonNull
import com.google.gson.JsonObject
import com.google.gson.JsonParseException
import com.google.gson.JsonPrimitive
import java.lang.reflect.Type
import kotlin.reflect.KClass

class ObjectMapper {
fun <T : Any> toObject(map: Map<String, Any>, kotlinClass: KClass<T>): T {

val gson =
GsonBuilder().registerTypeAdapter(GeometryObject::class.java, GeometryDeserializer()).create()
val json = map.toJsonElement()
return gson.fromJson(json, kotlinClass.java)
}

private fun Any?.toJsonElement(): JsonElement =
when (this) {
null -> JsonNull.INSTANCE
is JsonElement -> this
is Number -> JsonPrimitive(this)
is Boolean -> JsonPrimitive(this)
is String -> JsonPrimitive(this)
is Array<*> -> toJsonArray()
is List<*> -> toJsonArray()
// TODO: Add annotations for nested arrays.
is Map<*, *> -> toJsonObject()
else -> error("Unsupported type ${this.javaClass}")
}

private fun List<*>.toJsonArray(): JsonArray {
val arr = JsonArray(size)
forEach { arr.add(it.toJsonElement()) }
return arr
}

private fun Array<*>.toJsonArray() = arrayListOf(this).toJsonArray()

private fun Map<*, *>.toJsonObject(): JsonObject {
val obj = JsonObject()
entries.forEach { (k, v) -> obj.add(k.toString(), v.toJsonElement()) }
return obj
}
}

class GeometryDeserializer : JsonDeserializer<GeometryObject> {
override fun deserialize(
json: JsonElement,
typeOfT: Type,
context: JsonDeserializationContext
): GeometryObject {
val type = json.asJsonObject["type"].asString
val kotlinClass =
geometryClassesByType[type] ?: throw JsonParseException("Unknown geometry type $type")
return context.deserialize(json, kotlinClass.java)
}
}

internal val geometryClassesByType =
mapOf(
"Point" to PointObject::class,
"Polygon" to PolygonObject::class,
"MultiPolygon" to MultiPolygonObject::class
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package com.google.android.ground.persistence.remote.firebase

import com.google.firebase.firestore.GeoPoint
import com.google.ground.shared.schema.LinearRingObject
import com.google.ground.shared.schema.LoiDocument
import com.google.ground.shared.schema.PointObject
import com.google.ground.shared.schema.PolygonObject
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlin.test.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner

@RunWith(MockitoJUnitRunner::class)
class ObjectMapperTest {
@Test
fun `Converts Point LOI`() {
val json =
"""
{
"jobId": "123",
"customId": "foo",
"submissionCount": 42,
"geometry": {
"type": "Point",
"coordinates": {"latitude": 12.34, "longitude": 56.78}
}
}
"""
.trimIndent()
val expected =
LoiDocument(
jobId = "123",
customId = "foo",
submissionCount = 42,
geometry =
PointObject(coordinates = GeoPoint(/* latitude= */ 12.34, /* longitude= */ 56.78))
)
val actual = ObjectMapper().toObject(json.toMap(), LoiDocument::class)
assertEquals(expected, actual)
}

@Test
fun `Converts basic Polygon LOI`() {
// TODO: Test Polygon with holes.
val json =
"""
{
"jobId": "123",
"customId": "foo",
"submissionCount": 42,
"geometry": {
"type": "Polygon",
"coordinates": [
{
"$": [
{"latitude": 0.0, "longitude": 0.0},
{"latitude": 0.0, "longitude": 1.0},
{"latitude": 1.0, "longitude": 1.0},
{"latitude": 0.0, "longitude": 0.0}
]
}
]
}
}
"""
.trimIndent()
val expected =
LoiDocument(
jobId = "123",
customId = "foo",
submissionCount = 42,
geometry =
PolygonObject(
coordinates =
listOf(
LinearRingObject(
listOf(
GeoPoint(/* latitude= */ 0.0, /* longitude= */ 0.0),
GeoPoint(/* latitude= */ 0.0, /* longitude= */ 1.0),
GeoPoint(/* latitude= */ 1.0, /* longitude= */ 1.0),
GeoPoint(/* latitude= */ 0.0, /* longitude= */ 0.0)
)
)
)
)
)
val actual = ObjectMapper().toObject(json.toMap(), LoiDocument::class)
assertEquals(expected, actual)
}
}

internal object MapTypeToken : TypeToken<Map<String, Any>>()

internal fun String.toMap(): Map<String, Any> = Gson().fromJson(this, MapTypeToken.type)
2 changes: 1 addition & 1 deletion settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ plugins {
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.4.0'
}

include ':ground', ':sharedTest'
include ':shared', ':ground', ':sharedTest'

72 changes: 72 additions & 0 deletions shared/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import net.pwall.json.kotlin.codegen.gradle.JSONSchemaCodegen
import net.pwall.json.kotlin.codegen.gradle.JSONSchemaCodegenPlugin

plugins {
// Android library plugin.
id("com.android.library")
// Kotlin plugins for Gradle.
id("kotlin-android")
}

android {
namespace = "com.google.ground.shared.schema"
// TODO(#2206): Manage compileSdk version centrally.
compileSdk = 34
sourceSets { getByName("main").java.srcDirs("build/generated-sources/kotlin") }
}

// TODO(#2206): Manage version centrally (e.g., via rootProject.jvmToolchainVersion).
kotlin { jvmToolchain(17) }

// TODO(#2206): Manage version centrally.
dependencies {
implementation("org.jetbrains.kotlin", "kotlin-stdlib", "1.9.20")
implementation(platform("com.google.firebase:firebase-bom:32.4.1"))
implementation("com.google.firebase:firebase-firestore")
}

buildscript {
repositories { mavenCentral() }
dependencies { classpath("net.pwall.json:json-kotlin-gradle:0.102") }
}

apply<JSONSchemaCodegenPlugin>()

configure<JSONSchemaCodegen> {
configFile.set(file("json-schema-codegen/config.json")) // if not in the default location
// inputs { inputFile(file("src/main/resources/schema")) }
val base = "../../ground-platform/schema/src"
inputs {
inputFile(file("$base/loi-document.json"))
inputFile(file("$base/geometry-object.json"))
inputFile(file("$base/point-object.json"))
inputFile(file("$base/polygon-object.json"))
inputFile(file("$base/multi-polygon-object.json"))
inputFile(file("$base/linear-ring-array-wrapper.json"))
inputFile(file("$base/coordinates-object.json"))

inputFile(file("$base/submission-document.json"))
inputFile(file("$base/audit-info-object.json"))
}
// TODO:
// codeGenerator.addCustomClassByURI(URI("http://pwall.net/test#/properties/price"),
// "com.example.Money")
outputDir.set(file("build/generated-sources/kotlin"))
packageName.set("com.google.ground.shared.schema")
}
13 changes: 13 additions & 0 deletions shared/json-schema-codegen/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"classNames": {
"urn:jsonschema:PolygonObject:coordinates": "PolygonCoordinates"
},
"customClasses": {
"extension": {
"x-kt-type": {
"SubmissionDataObject": "com.google.ground.shared.schema.SubmissionDataObject",
"GeoPoint": "com.google.firebase.firestore.GeoPoint"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.ground.shared.schema

// TODO(#2256): Update schema so that values can be strongly typed.
typealias SubmissionDataObject = Map<String, Any>