Skip to content

Commit

Permalink
GH-3581: Address NPE in AbstractKafkaHeaderMapper
Browse files Browse the repository at this point in the history
Fixes: #3581

#3581

- Optimize headerValueToAddIn method by adding better null checks
- Add unit test to verify

# Conflicts:
#	spring-kafka/src/main/java/org/springframework/kafka/support/AbstractKafkaHeaderMapper.java

(cherry picked from commit cb8740d)
  • Loading branch information
sobychacko authored and spring-builds committed Oct 21, 2024
1 parent 88aaf5f commit d391a88
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
*
* @author Gary Russell
* @author Artem Bilan
* @author Soby Chacko
*
* @since 2.1.3
*
Expand Down Expand Up @@ -267,11 +268,11 @@ else if (value instanceof String) {
* @return the value to add.
*/
protected Object headerValueToAddIn(Header header) {
Object mapped = mapRawIn(header.key(), header.value());
if (mapped == null) {
mapped = header.value();
if (header == null || header.value() == null) {
return null;
}
return mapped;
String mapped = mapRawIn(header.key(), header.value());
return mapped != null ? mapped : header.value();
}

@Nullable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

/**
* @author Gary Russell
Expand Down Expand Up @@ -358,6 +362,20 @@ void deserializationExceptionHeadersAreMappedAsNonByteArray() {
assertThat(headers.lastHeader(SerializationUtils.VALUE_DESERIALIZER_EXCEPTION_HEADER)).isNull();
}

@Test
void ensureNullHeaderValueHandledGraciously() {
DefaultKafkaHeaderMapper mapper = new DefaultKafkaHeaderMapper();

Header mockHeader = mock(Header.class);
given(mockHeader.value()).willReturn(null);

Object result = mapper.headerValueToAddIn(mockHeader);

assertThat(result).isNull();
verify(mockHeader).value();
verify(mockHeader, never()).key();
}

public static final class Foo {

private String bar = "bar";
Expand Down

0 comments on commit d391a88

Please sign in to comment.