Skip to content

Commit a57c319

Browse files
GH-2940: Improvements in DefaultKafkaHeaderMapper
Fixes: #2940 Minor improvements and code cleanup in DefaultKafkaHeaderMapper.
1 parent 4b7e53e commit a57c319

File tree

1 file changed

+24
-24
lines changed

1 file changed

+24
-24
lines changed

spring-kafka/src/main/java/org/springframework/kafka/support/DefaultKafkaHeaderMapper.java

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2017-2022 the original author or authors.
2+
* Copyright 2017-2023 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -20,8 +20,8 @@
2020
import java.nio.ByteBuffer;
2121
import java.nio.charset.StandardCharsets;
2222
import java.util.Arrays;
23+
import java.util.Collections;
2324
import java.util.HashMap;
24-
import java.util.HashSet;
2525
import java.util.LinkedHashSet;
2626
import java.util.List;
2727
import java.util.Map;
@@ -31,13 +31,13 @@
3131
import org.apache.kafka.common.header.Headers;
3232
import org.apache.kafka.common.header.internals.RecordHeader;
3333

34-
import org.springframework.lang.Nullable;
3534
import org.springframework.messaging.MessageHeaders;
3635
import org.springframework.util.Assert;
3736
import org.springframework.util.ClassUtils;
3837
import org.springframework.util.MimeType;
3938

4039
import com.fasterxml.jackson.core.JsonProcessingException;
40+
import com.fasterxml.jackson.core.type.TypeReference;
4141
import com.fasterxml.jackson.databind.DeserializationContext;
4242
import com.fasterxml.jackson.databind.JsonNode;
4343
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -63,26 +63,23 @@ public class DefaultKafkaHeaderMapper extends AbstractKafkaHeaderMapper {
6363

6464
private static final String JAVA_LANG_STRING = "java.lang.String";
6565

66-
private static final Set<String> TRUSTED_ARRAY_TYPES =
67-
new HashSet<>(Arrays.asList(
66+
private static final Set<String> TRUSTED_ARRAY_TYPES = Set.of(
6867
"[B",
6968
"[I",
7069
"[J",
7170
"[F",
7271
"[D",
7372
"[C"
74-
));
73+
);
7574

76-
private static final List<String> DEFAULT_TRUSTED_PACKAGES =
77-
Arrays.asList(
75+
private static final List<String> DEFAULT_TRUSTED_PACKAGES = List.of(
7876
"java.lang",
7977
"java.net",
8078
"java.util",
8179
"org.springframework.util"
8280
);
8381

84-
private static final List<String> DEFAULT_TO_STRING_CLASSES =
85-
Arrays.asList(
82+
private static final List<String> DEFAULT_TO_STRING_CLASSES = List.of(
8683
"org.springframework.util.MimeType",
8784
"org.springframework.http.MediaType"
8885
);
@@ -142,7 +139,7 @@ public DefaultKafkaHeaderMapper(ObjectMapper objectMapper) {
142139
* @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String)
143140
*/
144141
public DefaultKafkaHeaderMapper(String... patterns) {
145-
this(new ObjectMapper(), patterns);
142+
this(JacksonUtils.enhancedObjectMapper(), patterns);
146143
}
147144

148145
/**
@@ -222,7 +219,7 @@ protected boolean isEncodeStrings() {
222219
}
223220

224221
/**
225-
* Set to true to encode String-valued headers as JSON ("..."), by default just the
222+
* Set to true to encode String-valued headers as JSON string ("..."), by default just the
226223
* raw String value is converted to a byte array using the configured charset. Set to
227224
* true if a consumer of the outbound record is using Spring for Apache Kafka version
228225
* less than 2.3
@@ -234,8 +231,15 @@ public void setEncodeStrings(boolean encodeStrings) {
234231
}
235232

236233
/**
237-
* Add packages to the trusted packages list (default {@code java.util, java.lang}) used
234+
* Add packages to the trusted packages list used
238235
* when constructing objects from JSON.
236+
* By default, the following packages are trusted:
237+
* <ul>
238+
* <li>java.lang</li>
239+
* <li>java.net</li>
240+
* <li>java.util</li>
241+
* <li>org.springframework.util</li>
242+
* </ul>
239243
* If any of the supplied packages is {@code "*"}, all packages are trusted.
240244
* If a class for a non-trusted package is encountered, the header is returned to the
241245
* application with value of type {@link NonTrustedHeaderType}.
@@ -286,20 +290,19 @@ public void fromHeaders(MessageHeaders headers, Headers target) {
286290
}
287291
if (!encodeToJson && valueToAdd instanceof String) {
288292
target.add(new RecordHeader(key, ((String) valueToAdd).getBytes(getCharset())));
289-
className = JAVA_LANG_STRING;
290293
}
291294
else {
292295
target.add(new RecordHeader(key, headerObjectMapper.writeValueAsBytes(valueToAdd)));
293296
}
294297
jsonHeaders.put(key, className);
295298
}
296299
catch (Exception e) {
297-
logger.debug(e, () -> "Could not map " + key + " with type " + rawValue.getClass().getName());
300+
logger.error(e, () -> "Could not map " + key + " with type " + rawValue.getClass().getName());
298301
}
299302
}
300303
}
301304
});
302-
if (jsonHeaders.size() > 0) {
305+
if (!jsonHeaders.isEmpty()) {
303306
try {
304307
target.add(new RecordHeader(JSON_TYPES, headerObjectMapper.writeValueAsBytes(jsonHeaders)));
305308
}
@@ -321,7 +324,7 @@ else if (headerName.equals(KafkaHeaders.LISTENER_INFO) && matchesForInbound(head
321324
headers.put(headerName, new String(header.value(), getCharset()));
322325
}
323326
else if (!(headerName.equals(JSON_TYPES)) && matchesForInbound(headerName)) {
324-
if (jsonTypes != null && jsonTypes.containsKey(headerName)) {
327+
if (jsonTypes.containsKey(headerName)) {
325328
String requestedType = jsonTypes.get(headerName);
326329
populateJsonValueHeader(header, requestedType, headers);
327330
}
@@ -355,8 +358,7 @@ private void populateJsonValueHeader(Header header, String requestedType, Map<St
355358
}
356359
catch (IOException e) {
357360
logger.error(e, () ->
358-
"Could not decode json type: " + new String(header.value()) + " for key: "
359-
+ header.key());
361+
"Could not decode json type: " + requestedType + " for key: " + header.key());
360362
headers.put(header.key(), header.value());
361363
}
362364
}
@@ -385,18 +387,16 @@ private Object decodeValue(Header h, Class<?> type) throws IOException, LinkageE
385387
return value;
386388
}
387389

388-
@SuppressWarnings("unchecked")
389-
@Nullable
390390
private Map<String, String> decodeJsonTypes(Headers source) {
391-
Map<String, String> types = null;
391+
Map<String, String> types = Collections.emptyMap();
392392
Header jsonTypes = source.lastHeader(JSON_TYPES);
393393
if (jsonTypes != null) {
394394
ObjectMapper headerObjectMapper = getObjectMapper();
395395
try {
396-
types = headerObjectMapper.readValue(jsonTypes.value(), Map.class);
396+
types = headerObjectMapper.readValue(jsonTypes.value(), new TypeReference<>() { });
397397
}
398398
catch (IOException e) {
399-
logger.error(e, () -> "Could not decode json types: " + new String(jsonTypes.value()));
399+
logger.error(e, () -> "Could not decode json types: " + new String(jsonTypes.value(), StandardCharsets.UTF_8));
400400
}
401401
}
402402
return types;

0 commit comments

Comments
 (0)