Skip to content

Commit

Permalink
Unnecessary casting removed from AvroFormatter to fix primitive value…
Browse files Browse the repository at this point in the history
…s deserialization (provectus#902)

* Unnecessary casting removed from AvroFormatter to prevent primitive values deserialization
  • Loading branch information
Ilya Kuramshin committed Sep 23, 2021
1 parent 1dd43f5 commit 528bcf4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import io.confluent.kafka.schemaregistry.client.SchemaRegistryClient;
import io.confluent.kafka.serializers.KafkaAvroDeserializer;
import lombok.SneakyThrows;
import org.apache.avro.generic.GenericRecord;

public class AvroMessageFormatter implements MessageFormatter {
private final KafkaAvroDeserializer avroDeserializer;
Expand All @@ -16,8 +15,10 @@ public AvroMessageFormatter(SchemaRegistryClient client) {
@Override
@SneakyThrows
public String format(String topic, byte[] value) {
GenericRecord avroRecord = (GenericRecord) avroDeserializer.deserialize(topic, value);
byte[] jsonBytes = AvroSchemaUtils.toJson(avroRecord);
// deserialized will have type, that depends on schema type (record or primitive),
// AvroSchemaUtils.toJson(...) method will take it into account
Object deserialized = avroDeserializer.deserialize(topic, value);
byte[] jsonBytes = AvroSchemaUtils.toJson(deserialized);
return new String(jsonBytes);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ public class SendAndReadTests extends AbstractBaseTest {
+ "}"
);

private static final AvroSchema AVRO_SCHEMA_PRIMITIVE_STRING =
new AvroSchema("{ \"type\": \"string\" }");

private static final AvroSchema AVRO_SCHEMA_PRIMITIVE_INT =
new AvroSchema("{ \"type\": \"int\" }");


private static final String AVRO_SCHEMA_1_JSON_RECORD
= "{ \"field1\":\"testStr\", \"field2\": 123 }";

Expand Down Expand Up @@ -187,6 +194,22 @@ void noSchemaValueIsNull() {
});
}

@Test
void primitiveAvroSchemas() {
new SendAndReadSpec()
.withKeySchema(AVRO_SCHEMA_PRIMITIVE_STRING)
.withValueSchema(AVRO_SCHEMA_PRIMITIVE_INT)
.withMsgToSend(
new CreateTopicMessage()
.key("\"some string\"")
.content("123")
)
.doAssert(polled -> {
assertThat(polled.getKey()).isEqualTo("\"some string\"");
assertThat(polled.getContent()).isEqualTo("123");
});
}

@Test
void nonNullableKvWithAvroSchema() {
new SendAndReadSpec()
Expand Down

0 comments on commit 528bcf4

Please sign in to comment.