Skip to content

Polish StringOrBytesSerializer #3933

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
* Convenient when used with one of the Json message converters.
*
* @author Gary Russell
* @author Ngoc Nhan
* @since 2.3
*
*/
Expand All @@ -42,21 +43,23 @@ public void configure(Map<String, ?> configs, boolean isKey) {
@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();
if (data == null) {
return null;
}
else if (data instanceof String) {
return this.stringSerializer.serialize(topic, (String) data);

if (data instanceof byte[] bytes) {
return bytes;
}
else if (data == null) {
return null;

if (data instanceof Bytes bytes) {
return bytes.get();
}
else {
throw new IllegalStateException("This serializer can only handle byte[], Bytes or String values");

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
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -26,10 +26,12 @@
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
*
*/
Expand All @@ -51,6 +53,9 @@ void test() {
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");
}

}