Core utilities and common classes for Elasticsearch, providing fundamental building blocks like resource management, IO utilities, time handling, and reference counting.
—
Elasticsearch Core provides a comprehensive set of utility classes for common operations including I/O handling, time management, string processing, and data manipulation. These utilities follow static method patterns and are designed to be lightweight and efficient.
I/O utilities based on Apache Lucene, providing safe resource cleanup and filesystem operations.
/**
* I/O utilities for safe resource management and filesystem operations
*/
public final class IOUtils {
/** UTF-8 charset constant */
public static final String UTF_8 = "UTF-8";
/** Operating system detection constants */
public static final boolean WINDOWS;
public static final boolean LINUX;
public static final boolean MAC_OS_X;
/** Close multiple closeables, collecting exceptions */
public static void close(Closeable... objects) throws IOException;
/** Close single closeable safely */
public static void close(@Nullable Closeable closeable) throws IOException;
/** Close with existing exception context */
public static void close(Exception ex, Closeable... objects) throws IOException;
/** Close iterable of closeables */
public static void close(Iterable<? extends Closeable> objects) throws IOException;
/** Close while handling exceptions (suppresses close exceptions) */
public static void closeWhileHandlingException(Closeable... objects);
/** Close iterable while handling exceptions */
public static void closeWhileHandlingException(Iterable<? extends Closeable> objects);
/** Close single closeable while handling exceptions */
public static void closeWhileHandlingException(Closeable closeable);
/** Delete files ignoring any exceptions that occur */
public static void deleteFilesIgnoringExceptions(Path... files);
/** Remove files and directories recursively */
public static void rm(Path... locations) throws IOException;
/** Force filesystem sync */
public static void fsync(Path fileToSync, boolean isDir) throws IOException;
/** Force filesystem sync with metadata option */
public static void fsync(Path fileToSync, boolean isDir, boolean metaData) throws IOException;
}Usage Examples:
import org.elasticsearch.core.IOUtils;
import java.io.*;
import java.nio.file.Path;
// Safe resource cleanup
FileInputStream input = null;
FileOutputStream output = null;
try {
input = new FileInputStream("input.txt");
output = new FileOutputStream("output.txt");
// Process files...
} finally {
IOUtils.close(input, output); // Closes both, collects exceptions
}
// Exception handling during cleanup
try {
// Some operation that might fail
processFile();
} catch (Exception e) {
IOUtils.closeWhileHandlingException(resource1, resource2);
throw e;
}
// Filesystem operations
Path tempFile = Files.createTempFile("temp", ".dat");
IOUtils.fsync(tempFile, false); // Force sync to disk
IOUtils.deleteFilesIgnoringExceptions(tempFile); // Safe deletionTime duration representation with multiple time units and parsing capabilities.
/**
* Time duration representation with support for multiple units
*/
public class TimeValue implements Comparable<TimeValue> {
/** Nanoseconds per millisecond constant */
public static final long NSEC_PER_MSEC = 1000000L;
/** Common time value constants */
public static final TimeValue MINUS_ONE;
public static final TimeValue ZERO;
public static final TimeValue MAX_VALUE;
public static final TimeValue THIRTY_SECONDS;
public static final TimeValue ONE_MINUTE;
/** Construct from milliseconds */
public TimeValue(long millis);
/** Construct from duration and time unit */
public TimeValue(long duration, TimeUnit timeUnit);
/** Get value in nanoseconds */
public long nanos();
/** Get value in microseconds */
public long micros();
/** Get value in milliseconds */
public long millis();
/** Get value in seconds */
public long seconds();
/** Get value in minutes */
public long minutes();
/** Get value in hours */
public long hours();
/** Get value in days */
public long days();
/** Get fractional microseconds */
public double microsFrac();
/** Get fractional milliseconds */
public double millisFrac();
/** Get fractional seconds */
public double secondsFrac();
/** Get fractional minutes */
public double minutesFrac();
/** Get fractional hours */
public double hoursFrac();
/** Get fractional days */
public double daysFrac();
/** Get the time unit */
public TimeUnit timeUnit();
/** Get the duration value */
public long duration();
/** Human readable string representation */
public String toHumanReadableString(int fractionPieces);
/** Get string representation */
public String getStringRep();
/** Compare to another TimeValue */
public int compareTo(TimeValue timeValue);
/** Factory methods */
public static TimeValue timeValueNanos(long nanos);
public static TimeValue timeValueMillis(long millis);
public static TimeValue timeValueSeconds(long seconds);
public static TimeValue timeValueMinutes(long minutes);
public static TimeValue timeValueHours(long hours);
public static TimeValue timeValueDays(long days);
/** Get minimum of two time values */
public static TimeValue min(TimeValue time1, TimeValue time2);
/** Parse time value from string */
public static TimeValue parseTimeValue(String sValue, String settingName);
public static TimeValue parseTimeValue(String sValue, TimeValue defaultValue, String settingName);
/** Convert nanoseconds to milliseconds */
public static long nsecToMSec(long ns);
}Usage Examples:
import org.elasticsearch.core.TimeValue;
import java.util.concurrent.TimeUnit;
// Creating time values
TimeValue timeout = TimeValue.timeValueSeconds(30);
TimeValue interval = new TimeValue(5, TimeUnit.MINUTES);
TimeValue duration = TimeValue.timeValueMillis(1500);
// Time arithmetic and comparison
TimeValue longer = TimeValue.max(timeout, interval);
boolean isLonger = duration.compareTo(timeout) > 0;
// String parsing
TimeValue parsed = TimeValue.parseTimeValue("2h", "connection.timeout");
TimeValue withDefault = TimeValue.parseTimeValue("invalid", TimeValue.timeValueMinutes(1), "fallback");
// Human readable formatting
System.out.println(timeout.toHumanReadableString(2)); // "30s"
System.out.println(interval.toHumanReadableString(1)); // "5m"
// Unit conversion
long millis = timeout.millis(); // 30000
long seconds = timeout.seconds(); // 30
double minutes = timeout.minutesFrac(); // 0.5Generic two-element tuple (record) for pairing related values.
/**
* Generic two-element tuple for pairing related values
* @param v1 first element of the tuple
* @param v2 second element of the tuple
*/
public record Tuple<V1, V2>(V1 v1, V2 v2) {
/** Factory method for creating tuples */
public static <V1, V2> Tuple<V1, V2> tuple(V1 v1, V2 v2);
}Usage Examples:
import org.elasticsearch.core.Tuple;
// Creating tuples
Tuple<String, Integer> nameAge = Tuple.tuple("Alice", 30);
Tuple<String, String> keyValue = new Tuple<>("key", "value");
// Accessing elements
String name = nameAge.v1(); // "Alice"
Integer age = nameAge.v2(); // 30
// Common use cases
public Tuple<Boolean, String> validateInput(String input) {
if (input == null || input.trim().isEmpty()) {
return Tuple.tuple(false, "Input cannot be empty");
}
return Tuple.tuple(true, "Valid input");
}
// Map operations
Map<String, Tuple<String, Integer>> userProfiles = Map.of(
"user1", Tuple.tuple("Alice", 30),
"user2", Tuple.tuple("Bob", 25)
);String formatting utilities with safe parameter handling.
/**
* String formatting utilities
*/
public class Strings {
/** Format string with arguments, similar to String.format but safer */
public static String format(String format, Object... args);
}Boolean parsing utilities with various string representations supported.
/**
* Boolean parsing utilities supporting various string representations
*/
public final class Booleans {
/** Parse boolean from character array segment */
public static boolean parseBoolean(char[] text, int offset, int length, boolean defaultValue);
/** Check if character array segment represents a boolean */
public static boolean isBoolean(char[] text, int offset, int length);
/** Check if string represents a boolean value */
public static boolean isBoolean(String value);
/** Parse boolean from string */
public static boolean parseBoolean(String value);
/** Parse boolean with default value */
public static boolean parseBoolean(String value, boolean defaultValue);
/** Parse Boolean object with default value */
public static Boolean parseBoolean(String value, Boolean defaultValue);
/** Check if string represents false */
public static boolean isFalse(String value);
/** Check if string represents true */
public static boolean isTrue(String value);
}Character array conversion and manipulation utilities.
/**
* Character array conversion and manipulation utilities
*/
public final class CharArrays {
/** Convert UTF-8 bytes to character array */
public static char[] utf8BytesToChars(byte[] utf8Bytes);
/** Convert UTF-8 byte segment to character array */
public static char[] utf8BytesToChars(byte[] utf8Bytes, int offset, int len);
/** Convert character array to UTF-8 bytes */
public static byte[] toUtf8Bytes(char[] chars);
/** Check if character array begins with prefix */
public static boolean charsBeginsWith(String prefix, char[] chars);
/** Constant-time comparison of character arrays */
public static boolean constantTimeEquals(char[] a, char[] b);
/** Constant-time comparison of strings */
public static boolean constantTimeEquals(String a, String b);
}Stream copying utilities for efficient I/O operations.
/**
* Stream copying utilities for efficient I/O operations
*/
public class Streams {
/** Copy with buffer and close option */
public static long copy(final InputStream in, final OutputStream out, byte[] buffer, boolean close) throws IOException;
/** Copy with close option */
public static long copy(final InputStream in, final OutputStream out, boolean close) throws IOException;
/** Copy with buffer */
public static long copy(final InputStream in, final OutputStream out, byte[] buffer) throws IOException;
/** Simple copy operation */
public static long copy(final InputStream in, final OutputStream out) throws IOException;
/** Read into ByteBuffer */
public static int read(InputStream input, ByteBuffer buffer, int count) throws IOException;
/** Read fully into byte array */
public static int readFully(InputStream reader, byte[] dest) throws IOException;
/** Read fully with offset and length */
public static int readFully(InputStream reader, byte[] dest, int offset, int len) throws IOException;
/** Wrap stream to prevent closing */
public static OutputStream noCloseStream(OutputStream stream);
}Path manipulation utilities extending standard Java Path operations.
/**
* Path manipulation utilities
*/
public final class PathUtils {
/** Create Path from string components */
public static Path get(String first, String... more);
/** Create Path from URI */
public static Path get(URI uri);
/** Create Path with root resolution */
public static Path get(Path[] roots, String path);
/** Create Path with root resolution from URI */
public static Path get(Path[] roots, URI uri);
/** Get default filesystem */
public static FileSystem getDefaultFileSystem();
}Type manipulation utilities for generic type operations.
/**
* Type manipulation utilities
*/
public abstract class Types {
/** Forcibly cast object to target type (unsafe operation) */
public static <T> T forciblyCast(Object argument);
}Glob pattern matching utilities.
/**
* Glob pattern matching utilities
*/
public class Glob {
/** Match string against glob pattern */
public static boolean globMatch(String pattern, String str);
}Fast math functions optimized for performance over precision.
/**
* Fast math functions delegating to optimized implementations
*/
public class ESSloppyMath {
/** Fast hyperbolic sine */
public static double sinh(double value);
/** Fast arctangent */
public static double atan(double value);
/** Fast logarithm */
public static double log(double value);
}Assertion utilities for runtime checking.
/**
* Assertion utilities
*/
public final class Assertions {
/** Whether assertions are enabled in the JVM */
public static final boolean ENABLED;
}Install with Tessl CLI
npx tessl i tessl/maven-org-elasticsearch--elasticsearch-core