100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Handle custom discriminator properties in JSON Forms (#2445)
Koen2fd118791298
diff --git a/model/src/main/java/org/openremote/model/util/JSONSchemaUtil.java b/model/src/main/java/org/openremote/model/util/JSONSchemaUtil.javaindex dbdc1692b..f15904174 100644--- a/model/src/main/java/org/openremote/model/util/JSONSchemaUtil.java+++ b/model/src/main/java/org/openremote/model/util/JSONSchemaUtil.java@@ -579,7 +579,6 @@ public class JSONSchemaUtil {if (props instanceof ObjectNode propsObj) {// Remove type property on type property for subtypes to enable definition mergingpropsObj.remove(typeKey);- propsObj.remove(customTypeKey);}return;}@@ -590,19 +589,10 @@ public class JSONSchemaUtil {continue;}- // Rename custom type key with normal type key- if (!propsObj.has(typeKey) && propsObj.has(customTypeKey)) {- propsObj.set(typeKey, propsObj.get(customTypeKey));- propsObj.remove(customTypeKey);- }-- if (customTypeKey != null && node.get(context.getKeyword(SchemaKeyword.TAG_REQUIRED)) instanceof ArrayNode arr) {- for (int i = 0; i < arr.size(); i++) {- if (arr.get(i).textValue().equals(customTypeKey)) {- arr.remove(i);- arr.add(context.getKeyword(SchemaKeyword.TAG_TYPE));- };- }+ // Add property indicating the custom discriminator property name+ if (customTypeKey != null && !customTypeKey.equals(typeKey)) {+ attrs.putObject("discriminator").put("propertyName", customTypeKey);+ typeKey = customTypeKey;}JsonNode typeNode = propsObj.get(typeKey);diff --git a/model/src/test/java/org/openremote/model/util/JSONSchemaUtilTest.java b/model/src/test/java/org/openremote/model/util/JSONSchemaUtilTest.javaindex 010c4bdfb..c0c3e1ea2 100644--- a/model/src/test/java/org/openremote/model/util/JSONSchemaUtilTest.java+++ b/model/src/test/java/org/openremote/model/util/JSONSchemaUtilTest.java@@ -14,7 +14,6 @@ import org.openremote.model.util.JSONSchemaUtil.*;import java.io.IOException;import java.io.InputStream;import java.io.Serializable;-import java.net.URL;import java.time.*;import java.util.Date;import java.util.Map;@@ -403,6 +402,72 @@ public class JSONSchemaUtilTest {assertEquals(expected.toString(), actual.toString(), true);}+ @JsonTypeInfo(property = "customType", use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY)+ @JsonSubTypes({+ @JsonSubTypes.Type(CustomSubType.class),+ @JsonSubTypes.Type(CustomSubTypeSuperclass.class),+ })+ abstract static class CustomPolymorphicType<T extends CustomPolymorphicType<?>> implements Serializable {}+ @JsonTypeName("SubType")+ static class CustomSubType extends CustomPolymorphicType<CustomSubType> {}+ @JsonTypeName("SubTypeSuperclass")+ static class CustomSubTypeSuperclass extends CustomSubType { }++ @Test+ public void shouldHaveSubtypesWithCustomTypeProperty() throws JsonProcessingException, JSONException {+ JsonNode expected = ValueUtil.JSON.readTree("""+ {+ "$schema": "http://json-schema.org/draft-07/schema#",+ "definitions": {+ "CustomSubType": {+ "title": "Custom Sub Type",+ "type": "object",+ "additionalProperties": true,+ "properties": {+ "customType": {+ "const": "SubType",+ "default": "SubType"+ }+ },+ "required": [+ "customType"+ ],+ "discriminator": {+ "propertyName": "customType"+ }+ },+ "CustomSubTypeSuperclass": {+ "title": "Custom Sub Type Superclass",+ "type": "object",+ "additionalProperties": true,+ "properties": {+ "customType": {+ "const": "SubTypeSuperclass",+ "default": "SubTypeSuperclass"+ }+ },+ "required": [+ "customType"+ ],+ "discriminator": {+ "propertyName": "customType"+ }+ }+ },+ "oneOf": [+ { "$ref": "#/definitions/CustomSubType" },+ { "$ref": "#/definitions/CustomSubTypeSuperclass" }+ ],+ "type": "object",+ "additionalProperties": true,+ "title": "Custom Polymorphic Type"+ }"""+ );++ JsonNode actual = ValueUtil.getSchema(CustomPolymorphicType.class);+ assertEquals(expected.toString(), actual.toString(), true);+ }+@JsonTypeInfo(property = "type", use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY)@JsonSubTypes({@JsonSubTypes.Type(ExternalSubType.class),diff --git a/ui/component/or-json-forms/src/util.ts b/ui/component/or-json-forms/src/util.tsindex ea5449c86..f1cbab368 100644--- a/ui/component/or-json-forms/src/util.ts+++ b/ui/component/or-json-forms/src/util.ts@@ -191,7 +191,7 @@ function getSchemaObjectProperties(schema: JsonSchema): [string, JsonSchema][] {const COMBINATOR_IDENTIFICATION_PROPERTY = "type";/**- * TODO: when updating to jsonforms/core 4.0 use `getCombinatorIndexOfFittingSchema` from jsonform/core instead+ * TODO: when updating to jsonforms/core 4.0 consider using `getCombinatorIndexOfFittingSchema` from jsonforms/core instead*/export function getCombinatorIndexOfFittingSchema(data: any,@@ -207,7 +207,7 @@ export function getCombinatorIndexOfFittingSchema(for (let i = 0; i < schema[keyword]!.length; i++) {let resolvedSchema = schema[keyword]![i];if (resolvedSchema.$ref) {- resolvedSchema = Resolve.schema( rootSchema, resolvedSchema.$ref, rootSchema);+ resolvedSchema = Resolve.schema(rootSchema, resolvedSchema.$ref, rootSchema);}resolvedCombinatorSchemas.push(resolvedSchema);}@@ -216,14 +216,15 @@ export function getCombinatorIndexOfFittingSchema(// Check if the data matches the identification property of one of the resolved schemasfor (let i = 0; i < resolvedCombinatorSchemas.length; i++) {- const resolvedSchema = resolvedCombinatorSchemas[i];+ const resolvedSchema = resolvedCombinatorSchemas[i] as JsonSchema & { discriminator?: { propertyName?: string } };+ const combinatorIdentificationProperty = resolvedSchema?.discriminator?.propertyName || COMBINATOR_IDENTIFICATION_PROPERTY;// Match the identification property against a constant value in resolvedSchema- const maybeConstIdValue = resolvedSchema.properties?.[COMBINATOR_IDENTIFICATION_PROPERTY]?.const;+ const maybeConstIdValue = resolvedSchema.properties?.[combinatorIdentificationProperty]?.const;if (maybeConstIdValue !== undefined &&- data[COMBINATOR_IDENTIFICATION_PROPERTY] === maybeConstIdValue+ data[combinatorIdentificationProperty] === maybeConstIdValue) {indexOfFittingSchema = i;break;diff --git a/ui/component/or-json-forms/test/fixtures/index.ts b/ui/component/or-json-forms/test/fixtures/index.tsindex 44e3ce559..5ac0c772e 100644--- a/ui/component/or-json-forms/test/fixtures/index.ts+++ b/ui/component/or-json-forms/test/fixtures/index.ts@@ -15,6 +15,10 @@ interface WalkFormOptions {}export interface JsonSchema extends JsonSchema7 {+ /**+ * Allow schemas to specify a custom discriminator property to resolve subtypes+ */+ discriminator?: { propertyName?: string };/*** Describes what properties should be manually selected by {@link JsonForms#walkForm}*/@@ -173,10 +177,15 @@ export class JsonForms {locator = locator.locator("or-json-forms-array-control").nth(item);path.push("or-json-forms-array-control", item);await locator.locator("or-collapsible-panel").click();+if (!Array.isArray(schema?.items) && schema.items?.oneOf) {- for (const prop of Object.values<any>(schema.items.oneOf)) {+ for (const subType of Object.values(schema.items.oneOf)) {await locator.getByRole("button", { name: "Add Item" }).click();- await this.dialog.locator("li").getByText(prop.title, { exact: true }).click();+ let resolvedSchema = structuredClone(subType);+ if (subType.$ref) {+ resolvedSchema = this.resolveSchema(schema, subType.$ref!);+ }+ await this.dialog.locator("li").getByText(resolvedSchema.title, { exact: true }).click();await this.dialog.getByRole("button", { name: "Add", exact: true }).click();}} else {@@ -245,6 +254,11 @@ export class JsonForms {await expect(locator).toHaveValue(String(schema["or:test:value"] ?? fallback));}}++ private resolveSchema(schema: JsonSchema, ref: string) {+ const segments = ref.split("/");+ return schema.definitions![segments[segments.length - 1]];+ }}interface ComponentFixtures extends SharedComponentTestFixtures {diff --git a/ui/component/or-json-forms/test/fixtures/schemas.ts b/ui/component/or-json-forms/test/fixtures/schemas.tsindex 89f405641..cfed6209b 100644--- a/ui/component/or-json-forms/test/fixtures/schemas.ts+++ b/ui/component/or-json-forms/test/fixtures/schemas.ts@@ -108,4 +108,45 @@ export const schemas: JsonSchema[] = [},},},+ {+ $schema: "http://json-schema.org/draft-07/schema#",+ title: "Polymorphic",+ type: "array",+ definitions: {+ SubType: {+ title: "Sub Type",+ properties: {+ type: {+ const: "SubType",+ default: "SubType"+ },+ },+ required: [+ "type"+ ],+ },+ CustomSubType: {+ title: "Custom Sub Type",+ properties: {+ customType: {+ const: "CustomSubType",+ default: "CustomSubType"+ }+ },+ required: [+ "customType"+ ],+ discriminator: {+ propertyName: "customType"+ }+ }+ },+ items: {+ type: "object",+ oneOf: [+ { "$ref": "#/definitions/SubType" },+ { "$ref": "#/definitions/CustomSubType" },+ ]+ }+ }];