forked from kafbat/kafka-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHexSerde.java
89 lines (75 loc) · 2.41 KB
/
HexSerde.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package io.kafbat.ui.serdes.builtin;
import io.kafbat.ui.serde.api.DeserializeResult;
import io.kafbat.ui.serde.api.PropertyResolver;
import io.kafbat.ui.serde.api.SchemaDescription;
import io.kafbat.ui.serdes.BuiltInSerde;
import java.util.HexFormat;
import java.util.Map;
import java.util.Optional;
public class HexSerde implements BuiltInSerde {
private HexFormat deserializeHexFormat;
public static String name() {
return "Hex";
}
@Override
public void autoConfigure(PropertyResolver kafkaClusterProperties, PropertyResolver globalProperties) {
configure(" ", true);
}
@Override
public void configure(PropertyResolver serdeProperties,
PropertyResolver kafkaClusterProperties,
PropertyResolver globalProperties) {
String delim = serdeProperties.getProperty("delimiter", String.class).orElse(" ");
boolean uppercase = serdeProperties.getProperty("uppercase", Boolean.class).orElse(true);
configure(delim, uppercase);
}
private void configure(String delim, boolean uppercase) {
deserializeHexFormat = HexFormat.ofDelimiter(delim);
if (uppercase) {
deserializeHexFormat = deserializeHexFormat.withUpperCase();
}
}
@Override
public Optional<String> getDescription() {
return Optional.empty();
}
@Override
public Optional<SchemaDescription> getSchema(String topic, Target type) {
return Optional.empty();
}
@Override
public boolean canDeserialize(String topic, Target type) {
return true;
}
@Override
public boolean canSerialize(String topic, Target type) {
return true;
}
@Override
public Serializer serializer(String topic, Target type) {
return input -> {
input = input.trim();
// it is a hack to provide ability to sent empty array as a key/value
if (input.isEmpty()) {
return new byte[] {};
}
return HexFormat.of().parseHex(prepareInputForParse(input));
};
}
// removing most-common delimiters and prefixes
private static String prepareInputForParse(String input) {
return input
.replaceAll(" ", "")
.replaceAll("#", "")
.replaceAll(":", "");
}
@Override
public Deserializer deserializer(String topic, Target type) {
return (headers, data) ->
new DeserializeResult(
deserializeHexFormat.formatHex(data),
DeserializeResult.Type.STRING,
Map.of()
);
}
}