|
| 1 | +/* |
| 2 | + * Copyright OpenSearch Contributors |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + * |
| 5 | + * The OpenSearch Contributors require contributions made to |
| 6 | + * this file be licensed under the Apache-2.0 license or a |
| 7 | + * compatible open source license. |
| 8 | + */ |
| 9 | + |
| 10 | +package org.opensearch.dataprepper.plugins.kafka.consumer; |
| 11 | + |
| 12 | +import org.apache.kafka.common.header.Header; |
| 13 | +import org.apache.kafka.common.header.Headers; |
| 14 | + |
| 15 | +import java.nio.charset.StandardCharsets; |
| 16 | +import java.util.Arrays; |
| 17 | +import java.util.HashMap; |
| 18 | +import java.util.Map; |
| 19 | + |
| 20 | +public class KafkaHeadersExtractor { |
| 21 | + public static Map<String, Object> extractMessageHeaders(Headers headers) { |
| 22 | + if (headers == null) { |
| 23 | + return null; |
| 24 | + } |
| 25 | + Map<String, Object> headerData = new HashMap<>(); |
| 26 | + for (Header header : headers) { |
| 27 | + byte[] headerValue = header.value(); |
| 28 | + if (headerValue == null) { |
| 29 | + headerData.put(header.key(), null); |
| 30 | + continue; |
| 31 | + } |
| 32 | + String strValue = new String(headerValue, StandardCharsets.UTF_8); |
| 33 | + if (Arrays.equals(headerValue, strValue.getBytes(StandardCharsets.UTF_8)) |
| 34 | + && isPrintableString(strValue)) { |
| 35 | + headerData.put(header.key(), strValue); |
| 36 | + } else { |
| 37 | + headerData.put(header.key(), headerValue); |
| 38 | + } |
| 39 | + } |
| 40 | + return headerData; |
| 41 | + } |
| 42 | + |
| 43 | + private static boolean isPrintableString(String value) { |
| 44 | + for (int i = 0; i < value.length(); i++) { |
| 45 | + char c = value.charAt(i); |
| 46 | + if (Character.isISOControl(c) && c != '\t' && c != '\n' && c != '\r') { |
| 47 | + return false; |
| 48 | + } |
| 49 | + } |
| 50 | + return true; |
| 51 | + } |
| 52 | +} |
0 commit comments