or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

functional-interfaces.mdindex.mdresource-management.mdtype-system.mdutility-classes.md

utility-classes.mddocs/

0

# Utility Classes

1

2

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.

3

4

## Capabilities

5

6

### IOUtils Class

7

8

I/O utilities based on Apache Lucene, providing safe resource cleanup and filesystem operations.

9

10

```java { .api }

11

/**

12

* I/O utilities for safe resource management and filesystem operations

13

*/

14

public final class IOUtils {

15

/** UTF-8 charset constant */

16

public static final String UTF_8 = "UTF-8";

17

18

/** Operating system detection constants */

19

public static final boolean WINDOWS;

20

public static final boolean LINUX;

21

public static final boolean MAC_OS_X;

22

23

/** Close multiple closeables, collecting exceptions */

24

public static void close(Closeable... objects) throws IOException;

25

26

/** Close single closeable safely */

27

public static void close(@Nullable Closeable closeable) throws IOException;

28

29

/** Close with existing exception context */

30

public static void close(Exception ex, Closeable... objects) throws IOException;

31

32

/** Close iterable of closeables */

33

public static void close(Iterable<? extends Closeable> objects) throws IOException;

34

35

/** Close while handling exceptions (suppresses close exceptions) */

36

public static void closeWhileHandlingException(Closeable... objects);

37

38

/** Close iterable while handling exceptions */

39

public static void closeWhileHandlingException(Iterable<? extends Closeable> objects);

40

41

/** Close single closeable while handling exceptions */

42

public static void closeWhileHandlingException(Closeable closeable);

43

44

/** Delete files ignoring any exceptions that occur */

45

public static void deleteFilesIgnoringExceptions(Path... files);

46

47

/** Remove files and directories recursively */

48

public static void rm(Path... locations) throws IOException;

49

50

/** Force filesystem sync */

51

public static void fsync(Path fileToSync, boolean isDir) throws IOException;

52

53

/** Force filesystem sync with metadata option */

54

public static void fsync(Path fileToSync, boolean isDir, boolean metaData) throws IOException;

55

}

56

```

57

58

**Usage Examples:**

59

60

```java

61

import org.elasticsearch.core.IOUtils;

62

import java.io.*;

63

import java.nio.file.Path;

64

65

// Safe resource cleanup

66

FileInputStream input = null;

67

FileOutputStream output = null;

68

try {

69

input = new FileInputStream("input.txt");

70

output = new FileOutputStream("output.txt");

71

// Process files...

72

} finally {

73

IOUtils.close(input, output); // Closes both, collects exceptions

74

}

75

76

// Exception handling during cleanup

77

try {

78

// Some operation that might fail

79

processFile();

80

} catch (Exception e) {

81

IOUtils.closeWhileHandlingException(resource1, resource2);

82

throw e;

83

}

84

85

// Filesystem operations

86

Path tempFile = Files.createTempFile("temp", ".dat");

87

IOUtils.fsync(tempFile, false); // Force sync to disk

88

IOUtils.deleteFilesIgnoringExceptions(tempFile); // Safe deletion

89

```

90

91

### TimeValue Class

92

93

Time duration representation with multiple time units and parsing capabilities.

94

95

```java { .api }

96

/**

97

* Time duration representation with support for multiple units

98

*/

99

public class TimeValue implements Comparable<TimeValue> {

100

/** Nanoseconds per millisecond constant */

101

public static final long NSEC_PER_MSEC = 1000000L;

102

103

/** Common time value constants */

104

public static final TimeValue MINUS_ONE;

105

public static final TimeValue ZERO;

106

public static final TimeValue MAX_VALUE;

107

public static final TimeValue THIRTY_SECONDS;

108

public static final TimeValue ONE_MINUTE;

109

110

/** Construct from milliseconds */

111

public TimeValue(long millis);

112

113

/** Construct from duration and time unit */

114

public TimeValue(long duration, TimeUnit timeUnit);

115

116

/** Get value in nanoseconds */

117

public long nanos();

118

119

/** Get value in microseconds */

120

public long micros();

121

122

/** Get value in milliseconds */

123

public long millis();

124

125

/** Get value in seconds */

126

public long seconds();

127

128

/** Get value in minutes */

129

public long minutes();

130

131

/** Get value in hours */

132

public long hours();

133

134

/** Get value in days */

135

public long days();

136

137

/** Get fractional microseconds */

138

public double microsFrac();

139

140

/** Get fractional milliseconds */

141

public double millisFrac();

142

143

/** Get fractional seconds */

144

public double secondsFrac();

145

146

/** Get fractional minutes */

147

public double minutesFrac();

148

149

/** Get fractional hours */

150

public double hoursFrac();

151

152

/** Get fractional days */

153

public double daysFrac();

154

155

/** Get the time unit */

156

public TimeUnit timeUnit();

157

158

/** Get the duration value */

159

public long duration();

160

161

/** Human readable string representation */

162

public String toHumanReadableString(int fractionPieces);

163

164

/** Get string representation */

165

public String getStringRep();

166

167

/** Compare to another TimeValue */

168

public int compareTo(TimeValue timeValue);

169

170

/** Factory methods */

171

public static TimeValue timeValueNanos(long nanos);

172

public static TimeValue timeValueMillis(long millis);

173

public static TimeValue timeValueSeconds(long seconds);

174

public static TimeValue timeValueMinutes(long minutes);

175

public static TimeValue timeValueHours(long hours);

176

public static TimeValue timeValueDays(long days);

177

178

/** Get minimum of two time values */

179

public static TimeValue min(TimeValue time1, TimeValue time2);

180

181

/** Parse time value from string */

182

public static TimeValue parseTimeValue(String sValue, String settingName);

183

public static TimeValue parseTimeValue(String sValue, TimeValue defaultValue, String settingName);

184

185

/** Convert nanoseconds to milliseconds */

186

public static long nsecToMSec(long ns);

187

}

188

```

189

190

**Usage Examples:**

191

192

```java

193

import org.elasticsearch.core.TimeValue;

194

import java.util.concurrent.TimeUnit;

195

196

// Creating time values

197

TimeValue timeout = TimeValue.timeValueSeconds(30);

198

TimeValue interval = new TimeValue(5, TimeUnit.MINUTES);

199

TimeValue duration = TimeValue.timeValueMillis(1500);

200

201

// Time arithmetic and comparison

202

TimeValue longer = TimeValue.max(timeout, interval);

203

boolean isLonger = duration.compareTo(timeout) > 0;

204

205

// String parsing

206

TimeValue parsed = TimeValue.parseTimeValue("2h", "connection.timeout");

207

TimeValue withDefault = TimeValue.parseTimeValue("invalid", TimeValue.timeValueMinutes(1), "fallback");

208

209

// Human readable formatting

210

System.out.println(timeout.toHumanReadableString(2)); // "30s"

211

System.out.println(interval.toHumanReadableString(1)); // "5m"

212

213

// Unit conversion

214

long millis = timeout.millis(); // 30000

215

long seconds = timeout.seconds(); // 30

216

double minutes = timeout.minutesFrac(); // 0.5

217

```

218

219

### Tuple Class

220

221

Generic two-element tuple (record) for pairing related values.

222

223

```java { .api }

224

/**

225

* Generic two-element tuple for pairing related values

226

* @param v1 first element of the tuple

227

* @param v2 second element of the tuple

228

*/

229

public record Tuple<V1, V2>(V1 v1, V2 v2) {

230

/** Factory method for creating tuples */

231

public static <V1, V2> Tuple<V1, V2> tuple(V1 v1, V2 v2);

232

}

233

```

234

235

**Usage Examples:**

236

237

```java

238

import org.elasticsearch.core.Tuple;

239

240

// Creating tuples

241

Tuple<String, Integer> nameAge = Tuple.tuple("Alice", 30);

242

Tuple<String, String> keyValue = new Tuple<>("key", "value");

243

244

// Accessing elements

245

String name = nameAge.v1(); // "Alice"

246

Integer age = nameAge.v2(); // 30

247

248

// Common use cases

249

public Tuple<Boolean, String> validateInput(String input) {

250

if (input == null || input.trim().isEmpty()) {

251

return Tuple.tuple(false, "Input cannot be empty");

252

}

253

return Tuple.tuple(true, "Valid input");

254

}

255

256

// Map operations

257

Map<String, Tuple<String, Integer>> userProfiles = Map.of(

258

"user1", Tuple.tuple("Alice", 30),

259

"user2", Tuple.tuple("Bob", 25)

260

);

261

```

262

263

### String Utilities

264

265

#### Strings Class

266

267

String formatting utilities with safe parameter handling.

268

269

```java { .api }

270

/**

271

* String formatting utilities

272

*/

273

public class Strings {

274

/** Format string with arguments, similar to String.format but safer */

275

public static String format(String format, Object... args);

276

}

277

```

278

279

#### Booleans Class

280

281

Boolean parsing utilities with various string representations supported.

282

283

```java { .api }

284

/**

285

* Boolean parsing utilities supporting various string representations

286

*/

287

public final class Booleans {

288

/** Parse boolean from character array segment */

289

public static boolean parseBoolean(char[] text, int offset, int length, boolean defaultValue);

290

291

/** Check if character array segment represents a boolean */

292

public static boolean isBoolean(char[] text, int offset, int length);

293

294

/** Check if string represents a boolean value */

295

public static boolean isBoolean(String value);

296

297

/** Parse boolean from string */

298

public static boolean parseBoolean(String value);

299

300

/** Parse boolean with default value */

301

public static boolean parseBoolean(String value, boolean defaultValue);

302

303

/** Parse Boolean object with default value */

304

public static Boolean parseBoolean(String value, Boolean defaultValue);

305

306

/** Check if string represents false */

307

public static boolean isFalse(String value);

308

309

/** Check if string represents true */

310

public static boolean isTrue(String value);

311

}

312

```

313

314

#### CharArrays Class

315

316

Character array conversion and manipulation utilities.

317

318

```java { .api }

319

/**

320

* Character array conversion and manipulation utilities

321

*/

322

public final class CharArrays {

323

/** Convert UTF-8 bytes to character array */

324

public static char[] utf8BytesToChars(byte[] utf8Bytes);

325

326

/** Convert UTF-8 byte segment to character array */

327

public static char[] utf8BytesToChars(byte[] utf8Bytes, int offset, int len);

328

329

/** Convert character array to UTF-8 bytes */

330

public static byte[] toUtf8Bytes(char[] chars);

331

332

/** Check if character array begins with prefix */

333

public static boolean charsBeginsWith(String prefix, char[] chars);

334

335

/** Constant-time comparison of character arrays */

336

public static boolean constantTimeEquals(char[] a, char[] b);

337

338

/** Constant-time comparison of strings */

339

public static boolean constantTimeEquals(String a, String b);

340

}

341

```

342

343

### Stream and Path Utilities

344

345

#### Streams Class

346

347

Stream copying utilities for efficient I/O operations.

348

349

```java { .api }

350

/**

351

* Stream copying utilities for efficient I/O operations

352

*/

353

public class Streams {

354

/** Copy with buffer and close option */

355

public static long copy(final InputStream in, final OutputStream out, byte[] buffer, boolean close) throws IOException;

356

357

/** Copy with close option */

358

public static long copy(final InputStream in, final OutputStream out, boolean close) throws IOException;

359

360

/** Copy with buffer */

361

public static long copy(final InputStream in, final OutputStream out, byte[] buffer) throws IOException;

362

363

/** Simple copy operation */

364

public static long copy(final InputStream in, final OutputStream out) throws IOException;

365

366

/** Read into ByteBuffer */

367

public static int read(InputStream input, ByteBuffer buffer, int count) throws IOException;

368

369

/** Read fully into byte array */

370

public static int readFully(InputStream reader, byte[] dest) throws IOException;

371

372

/** Read fully with offset and length */

373

public static int readFully(InputStream reader, byte[] dest, int offset, int len) throws IOException;

374

375

/** Wrap stream to prevent closing */

376

public static OutputStream noCloseStream(OutputStream stream);

377

}

378

```

379

380

#### PathUtils Class

381

382

Path manipulation utilities extending standard Java Path operations.

383

384

```java { .api }

385

/**

386

* Path manipulation utilities

387

*/

388

public final class PathUtils {

389

/** Create Path from string components */

390

public static Path get(String first, String... more);

391

392

/** Create Path from URI */

393

public static Path get(URI uri);

394

395

/** Create Path with root resolution */

396

public static Path get(Path[] roots, String path);

397

398

/** Create Path with root resolution from URI */

399

public static Path get(Path[] roots, URI uri);

400

401

/** Get default filesystem */

402

public static FileSystem getDefaultFileSystem();

403

}

404

```

405

406

### Additional Utilities

407

408

#### Types Class

409

410

Type manipulation utilities for generic type operations.

411

412

```java { .api }

413

/**

414

* Type manipulation utilities

415

*/

416

public abstract class Types {

417

/** Forcibly cast object to target type (unsafe operation) */

418

public static <T> T forciblyCast(Object argument);

419

}

420

```

421

422

#### Glob Class

423

424

Glob pattern matching utilities.

425

426

```java { .api }

427

/**

428

* Glob pattern matching utilities

429

*/

430

public class Glob {

431

/** Match string against glob pattern */

432

public static boolean globMatch(String pattern, String str);

433

}

434

```

435

436

#### ESSloppyMath Class

437

438

Fast math functions optimized for performance over precision.

439

440

```java { .api }

441

/**

442

* Fast math functions delegating to optimized implementations

443

*/

444

public class ESSloppyMath {

445

/** Fast hyperbolic sine */

446

public static double sinh(double value);

447

448

/** Fast arctangent */

449

public static double atan(double value);

450

451

/** Fast logarithm */

452

public static double log(double value);

453

}

454

```

455

456

#### Assertions Class

457

458

Assertion utilities for runtime checking.

459

460

```java { .api }

461

/**

462

* Assertion utilities

463

*/

464

public final class Assertions {

465

/** Whether assertions are enabled in the JVM */

466

public static final boolean ENABLED;

467

}

468

```