Skip to content

Commit

Permalink
Adding support for defaults from EnumSymbols (#177)
Browse files Browse the repository at this point in the history
When creating fields with the FieldBuilder and supplying a default
value to the field builder by using the adapter's genericDefaultValue
from an existing field, it will return a `GenericData.EnumSymbol`.

This changeset makes Jackson1Utils `GenericData.EnumSymbol` aware.

Co-authored-by: Christopher Harris <[email protected]>
  • Loading branch information
cbrentharris and Christopher Harris authored Aug 2, 2021
1 parent 17f362f commit 498f9b1
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import java.util.Collection;
import java.util.Map;
import org.apache.avro.AvroRuntimeException;
import org.apache.avro.generic.GenericData;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.JsonNodeFactory;
Expand Down Expand Up @@ -50,6 +51,9 @@ public static JsonNode toJsonNode(Object datum) {
} else if (datum instanceof Collection) {
ObjectMapper mapper = new ObjectMapper();
return mapper.convertValue(datum, JsonNode.class);
} else if (datum instanceof GenericData.EnumSymbol) {
GenericData.EnumSymbol enumSymbol = (GenericData.EnumSymbol) datum;
return JsonNodeFactory.instance.textNode(enumSymbol.toString());
} else {
throw new AvroRuntimeException("Unknown datum class: " + datum.getClass());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,21 @@ public void testCreateSchemaFieldWithProvidedDefaultValue() throws IOException {
List<List<String>> actualListValue = mapper.convertValue(actualJsonNode, new TypeReference<List<List<String>>>(){});
Assert.assertEquals(actualListValue.get(0).get(0), "dummyElement");
}

@Test
public void testGetGenericDefaultValueCloningForEnums() throws IOException {
// Given a schema with a default enum field
Schema schema = Schema.parse(TestUtil.load("RecordWithRecursiveTypesAndDefaults.avsc"));
Schema.Field field = schema.getField("enumFieldWithDefault");

// When cloning the field with a field builder and setting the default value as the default value from the schema
Schema.Field clone = AvroCompatibilityHelper.cloneSchemaField(field)
.setDoc(field.doc())
.setSchema(field.schema())
.setDefault(AvroCompatibilityHelper.getGenericDefaultValue(field))
.build();

// Then we should expect the clone and original to be equal
Assert.assertEquals(field, clone);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,17 @@
"default": [
["dummyElement"]
]
},
{
"name": "enumFieldWithDefault",
"type": {
"type": "enum",
"namespace": "com.acme",
"name": "PerfectlyNormalEnum",
"doc": "this enum is perfectly normal",
"symbols": ["A", "B"]
},
"default": "B"
}
]
}

0 comments on commit 498f9b1

Please sign in to comment.