Polish StringOrBytesSerializer
* Use `Assertions#assertThatIllegalStateException` Signed-off-by: Tran Ngoc Nhan <ngocnhan.tran1996@gmail.com>
This commit is contained in:
@@ -27,6 +27,7 @@ import org.apache.kafka.common.utils.Bytes;
|
||||
* Convenient when used with one of the Json message converters.
|
||||
*
|
||||
* @author Gary Russell
|
||||
* @author Ngoc Nhan
|
||||
* @since 2.3
|
||||
*
|
||||
*/
|
||||
@@ -42,21 +43,23 @@ public class StringOrBytesSerializer implements Serializer<Object> {
|
||||
@SuppressWarnings("NullAway") // Dataflow analysis limitation
|
||||
@Override
|
||||
public byte[] serialize(String topic, Object data) {
|
||||
if (data instanceof byte[]) {
|
||||
return (byte[]) data;
|
||||
}
|
||||
else if (data instanceof Bytes) {
|
||||
return ((Bytes) data).get();
|
||||
}
|
||||
else if (data instanceof String) {
|
||||
return this.stringSerializer.serialize(topic, (String) data);
|
||||
}
|
||||
else if (data == null) {
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
else {
|
||||
throw new IllegalStateException("This serializer can only handle byte[], Bytes or String values");
|
||||
|
||||
if (data instanceof byte[] bytes) {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
if (data instanceof Bytes bytes) {
|
||||
return bytes.get();
|
||||
}
|
||||
|
||||
if (data instanceof String string) {
|
||||
return this.stringSerializer.serialize(topic, string);
|
||||
}
|
||||
|
||||
throw new IllegalStateException("This serializer can only handle byte[], Bytes or String values");
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2019-2024 the original author or authors.
|
||||
* Copyright 2019-2025 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -26,10 +26,12 @@ import org.junit.jupiter.api.Test;
|
||||
import org.springframework.kafka.test.utils.KafkaTestUtils;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
|
||||
|
||||
/**
|
||||
* @author Gary Russell
|
||||
* @author Soby Chacko
|
||||
* @author Ngoc Nhan
|
||||
* @since 2.3
|
||||
*
|
||||
*/
|
||||
@@ -51,6 +53,9 @@ public class StringOrBytesSerializerTests {
|
||||
Map<String, Object> configs = Collections.singletonMap("serializer.encoding", "UTF-16");
|
||||
serializer.configure(configs, false);
|
||||
assertThat(KafkaTestUtils.getPropertyValue(serializer, "stringSerializer.encoding")).isEqualTo(StandardCharsets.UTF_16);
|
||||
assertThat(serializer.serialize("null", null)).isNull();
|
||||
assertThatIllegalStateException().isThrownBy(() -> serializer.serialize("ex", 0))
|
||||
.withMessage("This serializer can only handle byte[], Bytes or String values");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user