Created
December 26, 2017 18:13
-
-
Save dsebastien/ab3f2828a84289ad1b7cf29d674c4faf to your computer and use it in GitHub Desktop.
Convert object to GenericRecord
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
override fun convertToGenericRecord(thing: Any, schema: Schema): GenericRecord { | |
logger.trace { "Building a generic Avro record for the object" } | |
val genericRecordBuilder = GenericRecordBuilder(schema) | |
logger.trace { "Adding entries to the generic record for each property of the object" } | |
// TODO write utility with cache to find match between member properties and schema Field objects | |
// to accelerate later. See | |
thing::class.memberProperties | |
// we only care about public properties | |
.filter { KVisibility.PUBLIC == it.visibility } | |
.forEach { | |
val fieldName: String = getFieldName(it) | |
logger.trace { "Checking if the field called [$fieldName] is part of the schema" } | |
val schemaField: Schema.Field? = schema.getField(fieldName) | |
if (schemaField != null) { | |
if (!genericRecordBuilder.has(schemaField)) { | |
val propValue = it.getter.call(thing) | |
logger.trace { "Adding the [$fieldName] property to the generic record. Value: $propValue" } | |
genericRecordBuilder.set(schemaField, propValue) | |
} else { | |
logger.warn { "Field is already set! $fieldName" } | |
throw SerializationException("The same field cannot be set twice") | |
} | |
} else { | |
logger.trace { "Schema field not found: $fieldName. Not part of the schema; skipping it" } | |
} | |
} | |
val record: GenericRecord | |
try { | |
record = genericRecordBuilder.build() | |
} catch (exception: AvroRuntimeException) { | |
throw ConversionException("Failed to create the generic record based on the object. This is probably a bug", exception) | |
} | |
return record | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment