org.apache.kafka.common.utils.Utils Maven / Gradle / Ivy
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.common.utils;
import java.nio.BufferUnderflowException;
import java.nio.ByteOrder;
import java.nio.file.StandardOpenOption;
import java.util.AbstractMap;
import java.util.EnumSet;
import java.util.Map.Entry;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.config.ConfigException;
import org.apache.kafka.common.network.TransferableChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
import java.io.Closeable;
import java.io.DataOutput;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public final class Utils {
private Utils() {}
// This matches URIs of formats: host:port and protocol:\\host:port
// IPv6 is supported with [ip] pattern
private static final Pattern HOST_PORT_PATTERN = Pattern.compile(".*?\\[?([0-9a-zA-Z\\-%._:]*)\\]?:([0-9]+)");
private static final Pattern VALID_HOST_CHARACTERS = Pattern.compile("([0-9a-zA-Z\\-%._:]*)");
// Prints up to 2 decimal digits. Used for human readable printing
private static final DecimalFormat TWO_DIGIT_FORMAT = new DecimalFormat("0.##",
DecimalFormatSymbols.getInstance(Locale.ENGLISH));
private static final String[] BYTE_SCALE_SUFFIXES = new String[] {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
public static final String NL = System.getProperty("line.separator");
private static final Logger log = LoggerFactory.getLogger(Utils.class);
/**
* Get a sorted list representation of a collection.
* @param collection The collection to sort
* @param The class of objects in the collection
* @return An unmodifiable sorted list with the contents of the collection
*/
public static > List sorted(Collection collection) {
List res = new ArrayList<>(collection);
Collections.sort(res);
return Collections.unmodifiableList(res);
}
/**
* Turn the given UTF8 byte array into a string
*
* @param bytes The byte array
* @return The string
*/
public static String utf8(byte[] bytes) {
return new String(bytes, StandardCharsets.UTF_8);
}
/**
* Read a UTF8 string from a byte buffer. Note that the position of the byte buffer is not affected
* by this method.
*
* @param buffer The buffer to read from
* @param length The length of the string in bytes
* @return The UTF8 string
*/
public static String utf8(ByteBuffer buffer, int length) {
return utf8(buffer, 0, length);
}
/**
* Read a UTF8 string from the current position till the end of a byte buffer. The position of the byte buffer is
* not affected by this method.
*
* @param buffer The buffer to read from
* @return The UTF8 string
*/
public static String utf8(ByteBuffer buffer) {
return utf8(buffer, buffer.remaining());
}
/**
* Read a UTF8 string from a byte buffer at a given offset. Note that the position of the byte buffer
* is not affected by this method.
*
* @param buffer The buffer to read from
* @param offset The offset relative to the current position in the buffer
* @param length The length of the string in bytes
* @return The UTF8 string
*/
public static String utf8(ByteBuffer buffer, int offset, int length) {
if (buffer.hasArray())
return new String(buffer.array(), buffer.arrayOffset() + buffer.position() + offset, length, StandardCharsets.UTF_8);
else
return utf8(toArray(buffer, offset, length));
}
/**
* Turn a string into a utf8 byte[]
*
* @param string The string
* @return The byte[]
*/
public static byte[] utf8(String string) {
return string.getBytes(StandardCharsets.UTF_8);
}
/**
* Get the absolute value of the given number. If the number is Int.MinValue return 0. This is different from
* java.lang.Math.abs or scala.math.abs in that they return Int.MinValue (!).
*/
public static int abs(int n) {
return (n == Integer.MIN_VALUE) ? 0 : Math.abs(n);
}
/**
* Get the minimum of some long values.
* @param first Used to ensure at least one value
* @param rest The remaining values to compare
* @return The minimum of all passed values
*/
public static long min(long first, long... rest) {
long min = first;
for (long r : rest) {
if (r < min)
min = r;
}
return min;
}
/**
* Get the maximum of some long values.
* @param first Used to ensure at least one value
* @param rest The remaining values to compare
* @return The maximum of all passed values
*/
public static long max(long first, long... rest) {
long max = first;
for (long r : rest) {
if (r > max)
max = r;
}
return max;
}
public static short min(short first, short second) {
return (short) Math.min(first, second);
}
/**
* Get the length for UTF8-encoding a string without encoding it first
*
* @param s The string to calculate the length for
* @return The length when serialized
*/
public static int utf8Length(CharSequence s) {
int count = 0;
for (int i = 0, len = s.length(); i < len; i++) {
char ch = s.charAt(i);
if (ch <= 0x7F) {
count++;
} else if (ch <= 0x7FF) {
count += 2;
} else if (Character.isHighSurrogate(ch)) {
count += 4;
++i;
} else {
count += 3;
}
}
return count;
}
/**
* Read the given byte buffer from its current position to its limit into a byte array.
* @param buffer The buffer to read from
*/
public static byte[] toArray(ByteBuffer buffer) {
return toArray(buffer, 0, buffer.remaining());
}
/**
* Read a byte array from its current position given the size in the buffer
* @param buffer The buffer to read from
* @param size The number of bytes to read into the array
*/
public static byte[] toArray(ByteBuffer buffer, int size) {
return toArray(buffer, 0, size);
}
/**
* Convert a ByteBuffer to a nullable array.
* @param buffer The buffer to convert
* @return The resulting array or null if the buffer is null
*/
public static byte[] toNullableArray(ByteBuffer buffer) {
return buffer == null ? null : toArray(buffer);
}
/**
* Wrap an array as a nullable ByteBuffer.
* @param array The nullable array to wrap
* @return The wrapping ByteBuffer or null if array is null
*/
public static ByteBuffer wrapNullable(byte[] array) {
return array == null ? null : ByteBuffer.wrap(array);
}
/**
* Read a byte array from the given offset and size in the buffer
* @param buffer The buffer to read from
* @param offset The offset relative to the current position of the buffer
* @param size The number of bytes to read into the array
*/
public static byte[] toArray(ByteBuffer buffer, int offset, int size) {
byte[] dest = new byte[size];
if (buffer.hasArray()) {
System.arraycopy(buffer.array(), buffer.position() + buffer.arrayOffset() + offset, dest, 0, size);
} else {
int pos = buffer.position();
buffer.position(pos + offset);
buffer.get(dest);
buffer.position(pos);
}
return dest;
}
/**
* Starting from the current position, read an integer indicating the size of the byte array to read,
* then read the array. Consumes the buffer: upon returning, the buffer's position is after the array
* that is returned.
* @param buffer The buffer to read a size-prefixed array from
* @return The array
*/
public static byte[] getNullableSizePrefixedArray(final ByteBuffer buffer) {
final int size = buffer.getInt();
return getNullableArray(buffer, size);
}
/**
* Read a byte array of the given size. Consumes the buffer: upon returning, the buffer's position
* is after the array that is returned.
* @param buffer The buffer to read a size-prefixed array from
* @param size The number of bytes to read out of the buffer
* @return The array
*/
public static byte[] getNullableArray(final ByteBuffer buffer, final int size) {
if (size > buffer.remaining()) {
// preemptively throw this when the read is doomed to fail, so we don't have to allocate the array.
throw new BufferUnderflowException();
}
final byte[] oldBytes = size == -1 ? null : new byte[size];
if (oldBytes != null) {
buffer.get(oldBytes);
}
return oldBytes;
}
/**
* Returns a copy of src byte array
* @param src The byte array to copy
* @return The copy
*/
public static byte[] copyArray(byte[] src) {
return Arrays.copyOf(src, src.length);
}
/**
* Compares two character arrays for equality using a constant-time algorithm, which is needed
* for comparing passwords. Two arrays are equal if they have the same length and all
* characters at corresponding positions are equal.
*
* All characters in the first array are examined to determine equality.
* The calculation time depends only on the length of this first character array; it does not
* depend on the length of the second character array or the contents of either array.
*
* @param first the first array to compare
* @param second the second array to compare
* @return true if the arrays are equal, or false otherwise
*/
public static boolean isEqualConstantTime(char[] first, char[] second) {
if (first == second) {
return true;
}
if (first == null || second == null) {
return false;
}
if (second.length == 0) {
return first.length == 0;
}
// time-constant comparison that always compares all characters in first array
boolean matches = first.length == second.length;
for (int i = 0; i < first.length; ++i) {
int j = i < second.length ? i : 0;
if (first[i] != second[j]) {
matches = false;
}
}
return matches;
}
/**
* Sleep for a bit
* @param ms The duration of the sleep
*/
public static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
// this is okay, we just wake up early
Thread.currentThread().interrupt();
}
}
/**
* Instantiate the class
*/
public static T newInstance(Class c) {
if (c == null)
throw new KafkaException("class cannot be null");
try {
return c.getDeclaredConstructor().newInstance();
} catch (NoSuchMethodException e) {
throw new KafkaException("Could not find a public no-argument constructor for " + c.getName(), e);
} catch (ReflectiveOperationException | RuntimeException e) {
throw new KafkaException("Could not instantiate class " + c.getName(), e);
}
}
/**
* Look up the class by name and instantiate it.
* @param klass class name
* @param base super class of the class to be instantiated
* @param the type of the base class
* @return the new instance
*/
public static T newInstance(String klass, Class base) throws ClassNotFoundException {
return Utils.newInstance(loadClass(klass, base));
}
/**
* Look up a class by name.
* @param klass class name
* @param base super class of the class for verification
* @param the type of the base class
* @return the new class
*/
public static Class extends T> loadClass(String klass, Class base) throws ClassNotFoundException {
return Class.forName(klass, true, Utils.getContextOrKafkaClassLoader()).asSubclass(base);
}
/**
* Cast {@code klass} to {@code base} and instantiate it.
* @param klass The class to instantiate
* @param base A know baseclass of klass.
* @param the type of the base class
* @throws ClassCastException If {@code klass} is not a subclass of {@code base}.
* @return the new instance.
*/
public static T newInstance(Class> klass, Class base) {
return Utils.newInstance(klass.asSubclass(base));
}
/**
* Construct a new object using a class name and parameters.
*
* @param className The full name of the class to construct.
* @param params A sequence of (type, object) elements.
* @param The type of object to construct.
* @return The new object.
* @throws ClassNotFoundException If there was a problem constructing the object.
*/
public static T newParameterizedInstance(String className, Object... params)
throws ClassNotFoundException {
Class>[] argTypes = new Class>[params.length / 2];
Object[] args = new Object[params.length / 2];
try {
Class> c = Class.forName(className, true, Utils.getContextOrKafkaClassLoader());
for (int i = 0; i < params.length / 2; i++) {
argTypes[i] = (Class>) params[2 * i];
args[i] = params[(2 * i) + 1];
}
@SuppressWarnings("unchecked")
Constructor constructor = (Constructor) c.getConstructor(argTypes);
return constructor.newInstance(args);
} catch (NoSuchMethodException e) {
throw new ClassNotFoundException(String.format("Failed to find " +
"constructor with %s for %s", Utils.join(argTypes, ", "), className), e);
} catch (InstantiationException e) {
throw new ClassNotFoundException(String.format("Failed to instantiate " +
"%s", className), e);
} catch (IllegalAccessException e) {
throw new ClassNotFoundException(String.format("Unable to access " +
"constructor of %s", className), e);
} catch (InvocationTargetException e) {
throw new KafkaException(String.format("The constructor of %s threw an exception", className), e.getCause());
}
}
/**
* Generates 32 bit murmur2 hash from byte array
* @param data byte array to hash
* @return 32 bit hash of the given array
*/
@SuppressWarnings("fallthrough")
public static int murmur2(final byte[] data) {
int length = data.length;
int seed = 0x9747b28c;
// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
final int m = 0x5bd1e995;
final int r = 24;
// Initialize the hash to a random value
int h = seed ^ length;
int length4 = length / 4;
for (int i = 0; i < length4; i++) {
final int i4 = i * 4;
int k = (data[i4 + 0] & 0xff) + ((data[i4 + 1] & 0xff) << 8) + ((data[i4 + 2] & 0xff) << 16) + ((data[i4 + 3] & 0xff) << 24);
k *= m;
k ^= k >>> r;
k *= m;
h *= m;
h ^= k;
}
// Handle the last few bytes of the input array
switch (length % 4) {
case 3:
h ^= (data[(length & ~3) + 2] & 0xff) << 16;
case 2:
h ^= (data[(length & ~3) + 1] & 0xff) << 8;
case 1:
h ^= data[length & ~3] & 0xff;
h *= m;
}
h ^= h >>> 13;
h *= m;
h ^= h >>> 15;
return h;
}
/**
* Extracts the hostname from a "host:port" address string.
* @param address address string to parse
* @return hostname or null if the given address is incorrect
*/
public static String getHost(String address) {
Matcher matcher = HOST_PORT_PATTERN.matcher(address);
return matcher.matches() ? matcher.group(1) : null;
}
/**
* Extracts the port number from a "host:port" address string.
* @param address address string to parse
* @return port number or null if the given address is incorrect
*/
public static Integer getPort(String address) {
Matcher matcher = HOST_PORT_PATTERN.matcher(address);
return matcher.matches() ? Integer.parseInt(matcher.group(2)) : null;
}
/**
* Basic validation of the supplied address. checks for valid characters
* @param address hostname string to validate
* @return true if address contains valid characters
*/
public static boolean validHostPattern(String address) {
return VALID_HOST_CHARACTERS.matcher(address).matches();
}
/**
* Formats hostname and port number as a "host:port" address string,
* surrounding IPv6 addresses with braces '[', ']'
* @param host hostname
* @param port port number
* @return address string
*/
public static String formatAddress(String host, Integer port) {
return host.contains(":")
? "[" + host + "]:" + port // IPv6
: host + ":" + port;
}
/**
* Formats a byte number as a human readable String ("3.2 MB")
* @param bytes some size in bytes
* @return
*/
public static String formatBytes(long bytes) {
if (bytes < 0) {
return String.valueOf(bytes);
}
double asDouble = (double) bytes;
int ordinal = (int) Math.floor(Math.log(asDouble) / Math.log(1024.0));
double scale = Math.pow(1024.0, ordinal);
double scaled = asDouble / scale;
String formatted = TWO_DIGIT_FORMAT.format(scaled);
try {
return formatted + " " + BYTE_SCALE_SUFFIXES[ordinal];
} catch (IndexOutOfBoundsException e) {
//huge number?
return String.valueOf(asDouble);
}
}
/**
* Create a string representation of an array joined by the given separator
* @param strs The array of items
* @param separator The separator
* @return The string representation.
*/
public static String join(T[] strs, String separator) {
return join(Arrays.asList(strs), separator);
}
/**
* Create a string representation of a collection joined by the given separator
* @param collection The list of items
* @param separator The separator
* @return The string representation.
*/
public static String join(Collection collection, String separator) {
Objects.requireNonNull(collection);
return mkString(collection.stream(), "", "", separator);
}
/**
* Create a string representation of a stream surrounded by `begin` and `end` and joined by `separator`.
*
* @return The string representation.
*/
public static String mkString(Stream stream, String begin, String end, String separator) {
Objects.requireNonNull(stream);
StringBuilder sb = new StringBuilder();
sb.append(begin);
Iterator iter = stream.iterator();
while (iter.hasNext()) {
sb.append(iter.next());
if (iter.hasNext())
sb.append(separator);
}
sb.append(end);
return sb.toString();
}
/**
* Converts a {@code Map} class into a string, concatenating keys and values
* Example:
* {@code mkString({ key: "hello", keyTwo: "hi" }, "|START|", "|END|", "=", ",")
* => "|START|key=hello,keyTwo=hi|END|"}
*/
public static String mkString(Map map, String begin, String end,
String keyValueSeparator, String elementSeparator) {
StringBuilder bld = new StringBuilder();
bld.append(begin);
String prefix = "";
for (Map.Entry entry : map.entrySet()) {
bld.append(prefix).append(entry.getKey()).
append(keyValueSeparator).append(entry.getValue());
prefix = elementSeparator;
}
bld.append(end);
return bld.toString();
}
/**
* Converts an extensions string into a {@code Map}.
*
* Example:
* {@code parseMap("key=hey,keyTwo=hi,keyThree=hello", "=", ",") => { key: "hey", keyTwo: "hi", keyThree: "hello" }}
*
*/
public static Map parseMap(String mapStr, String keyValueSeparator, String elementSeparator) {
Map map = new HashMap<>();
if (!mapStr.isEmpty()) {
String[] attrvals = mapStr.split(elementSeparator);
for (String attrval : attrvals) {
String[] array = attrval.split(keyValueSeparator, 2);
map.put(array[0], array[1]);
}
}
return map;
}
/**
* Read a properties file from the given path
* @param filename The path of the file to read
* @return the loaded properties
*/
public static Properties loadProps(String filename) throws IOException {
return loadProps(filename, null);
}
/**
* Read a properties file from the given path
* @param filename The path of the file to read
* @param onlyIncludeKeys When non-null, only return values associated with these keys and ignore all others
* @return the loaded properties
*/
public static Properties loadProps(String filename, List onlyIncludeKeys) throws IOException {
Properties props = new Properties();
if (filename != null) {
try (InputStream propStream = Files.newInputStream(Paths.get(filename))) {
props.load(propStream);
}
} else {
System.out.println("Did not load any properties since the property file is not specified");
}
if (onlyIncludeKeys == null || onlyIncludeKeys.isEmpty())
return props;
Properties requestedProps = new Properties();
onlyIncludeKeys.forEach(key -> {
String value = props.getProperty(key);
if (value != null)
requestedProps.setProperty(key, value);
});
return requestedProps;
}
/**
* Converts a Properties object to a Map, calling {@link #toString} to ensure all keys and values
* are Strings.
*/
public static Map propsToStringMap(Properties props) {
Map result = new HashMap<>();
for (Map.Entry
© 2015 - 2024 Weber Informatics LLC | Privacy Policy