or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-operations.mdcomponent-lifecycle.mdcore-utilities.mddata-structures.mdindex.mdresource-management.mdsecurity.mdstatistics.mdthreading.md

core-utilities.mddocs/

0

# Core Utilities

1

2

Essential utility classes for common operations including buffer manipulation, string processing, URI handling, and I/O operations. These utilities form the foundation of Jetty's high-performance processing capabilities.

3

4

## Capabilities

5

6

### BufferUtil

7

8

ByteBuffer manipulation utilities providing efficient buffer operations for I/O and data processing.

9

10

```java { .api }

11

/**

12

* ByteBuffer utility methods for allocation, conversion, and manipulation

13

*/

14

public class BufferUtil {

15

/** Allocate a new ByteBuffer with the specified capacity */

16

public static ByteBuffer allocate(int capacity);

17

18

/** Allocate a direct ByteBuffer with the specified capacity */

19

public static ByteBuffer allocateDirect(int capacity);

20

21

/** Convert ByteBuffer content to string using specified charset */

22

public static String toString(ByteBuffer buffer, Charset charset);

23

24

/** Convert ByteBuffer content to byte array */

25

public static byte[] toArray(ByteBuffer buffer);

26

27

/** Write ByteBuffer content to OutputStream */

28

public static void writeTo(ByteBuffer buffer, OutputStream out) throws IOException;

29

30

/** Append byte array to ByteBuffer */

31

public static void append(ByteBuffer buffer, byte[] array);

32

33

/** Clear ByteBuffer and reset position/limit */

34

public static void clear(ByteBuffer buffer);

35

36

/** Check if ByteBuffer is empty (no remaining bytes) */

37

public static boolean isEmpty(ByteBuffer buffer);

38

39

/** Check if ByteBuffer has remaining bytes */

40

public static boolean hasContent(ByteBuffer buffer);

41

42

/** Get remaining bytes count in ByteBuffer */

43

public static int length(ByteBuffer buffer);

44

45

/** Flip ByteBuffer from write mode to read mode */

46

public static void flipToFlush(ByteBuffer buffer, int position);

47

48

/** Compact ByteBuffer, removing consumed bytes */

49

public static void compact(ByteBuffer buffer);

50

}

51

```

52

53

**Usage Examples:**

54

55

```java

56

import org.eclipse.jetty.util.BufferUtil;

57

import java.nio.ByteBuffer;

58

import java.nio.charset.StandardCharsets;

59

60

// Basic buffer operations

61

ByteBuffer buffer = BufferUtil.allocate(1024);

62

BufferUtil.append(buffer, "Hello World".getBytes(StandardCharsets.UTF_8));

63

String result = BufferUtil.toString(buffer, StandardCharsets.UTF_8);

64

65

// I/O operations

66

ByteArrayOutputStream output = new ByteArrayOutputStream();

67

BufferUtil.writeTo(buffer, output);

68

byte[] data = output.toByteArray();

69

70

// Buffer state management

71

BufferUtil.flipToFlush(buffer, 0);

72

boolean hasData = BufferUtil.hasContent(buffer);

73

int remaining = BufferUtil.length(buffer);

74

```

75

76

### StringUtil

77

78

String processing utilities for efficient string manipulation and validation.

79

80

```java { .api }

81

/**

82

* String utility methods for validation, splitting, and manipulation

83

*/

84

public class StringUtil {

85

/** Check if string is null or contains only whitespace */

86

public static boolean isBlank(String str);

87

88

/** Check if string is null or empty */

89

public static boolean isEmpty(String str);

90

91

/** Check if string is not blank */

92

public static boolean isNotBlank(String str);

93

94

/** Split string by delimiter character */

95

public static String[] split(String str, char delimiter);

96

97

/** Split CSV string handling quoted values */

98

public static List<String> csvSplit(String str);

99

100

/** Join string array with delimiter */

101

public static String join(String[] array, String delimiter);

102

103

/** Replace all occurrences in string */

104

public static String replace(String str, String target, String replacement);

105

106

/** Convert string to lowercase using ASCII rules */

107

public static String asciiToLowerCase(String str);

108

109

/** Check if string starts with prefix (case sensitive) */

110

public static boolean startsWith(String str, String prefix);

111

112

/** Check if string ends with suffix (case sensitive) */

113

public static boolean endsWith(String str, String suffix);

114

115

/** Sanitize string for filename usage */

116

public static String sanitizeFileSystemName(String str);

117

}

118

```

119

120

**Usage Examples:**

121

122

```java

123

import org.eclipse.jetty.util.StringUtil;

124

import java.util.List;

125

126

// String validation

127

boolean isValid = !StringUtil.isBlank(userInput);

128

boolean hasContent = StringUtil.isNotBlank(data);

129

130

// String splitting

131

String[] parts = StringUtil.split("one,two,three", ',');

132

List<String> csvFields = StringUtil.csvSplit("\"quoted,field\",normal,field");

133

134

// String manipulation

135

String joined = StringUtil.join(new String[]{"a", "b", "c"}, "-");

136

String lower = StringUtil.asciiToLowerCase("HTTP/1.1");

137

String clean = StringUtil.sanitizeFileSystemName("file:name?.txt");

138

```

139

140

### TypeUtil

141

142

Type conversion and reflection utilities for working with Java types and classes.

143

144

```java { .api }

145

/**

146

* Type conversion and utility methods for reflection and type handling

147

*/

148

public class TypeUtil {

149

/** Convert string value to specified type */

150

public static <T> T valueOf(Class<T> type, String value);

151

152

/** Get location (JAR/directory) of a class */

153

public static String getLocationOfClass(Class<?> clazz);

154

155

/** Dump object information to appendable */

156

public static void dump(Appendable out, String indent, Object... objects);

157

158

/** Convert primitive type to wrapper class */

159

public static Class<?> wrapperFor(Class<?> primitiveType);

160

161

/** Check if class is a numeric type */

162

public static boolean isNumeric(Class<?> clazz);

163

164

/** Parse integer from string with bounds checking */

165

public static int parseInt(String str, int defaultValue);

166

167

/** Parse long from string with bounds checking */

168

public static long parseLong(String str, long defaultValue);

169

170

/** Parse boolean from string */

171

public static boolean parseBoolean(String str);

172

173

/** Get simple class name without package */

174

public static String toShortName(Class<?> clazz);

175

}

176

```

177

178

**Usage Examples:**

179

180

```java

181

import org.eclipse.jetty.util.TypeUtil;

182

183

// Type conversion

184

Integer value = TypeUtil.valueOf(Integer.class, "42");

185

Boolean flag = TypeUtil.valueOf(Boolean.class, "true");

186

187

// Safe parsing with defaults

188

int port = TypeUtil.parseInt(portString, 8080);

189

long timeout = TypeUtil.parseLong(timeoutString, 30000L);

190

191

// Class information

192

String location = TypeUtil.getLocationOfClass(MyClass.class);

193

String shortName = TypeUtil.toShortName(java.util.ArrayList.class); // "ArrayList"

194

195

// Debugging

196

StringBuilder debug = new StringBuilder();

197

TypeUtil.dump(debug, "", myObject, "with label");

198

```

199

200

### URIUtil

201

202

URI and URL manipulation utilities for path operations and encoding.

203

204

```java { .api }

205

/**

206

* URI utility methods for path manipulation and encoding

207

*/

208

public class URIUtil {

209

/** Canonicalize path by resolving . and .. segments */

210

public static String canonicalPath(String path);

211

212

/** Add two path segments together properly */

213

public static String addPaths(String path1, String path2);

214

215

/** Decode URL-encoded path */

216

public static String decodePath(String path);

217

218

/** URL-encode path for safe transmission */

219

public static String encodePath(String path);

220

221

/** Get parent path of given path */

222

public static String parentPath(String path);

223

224

/** Check if path is within base path (security check) */

225

public static boolean isValidPath(String path);

226

227

/** Convert file system path to URI path */

228

public static String pathToUriPath(String path);

229

230

/** Convert URI path to file system path */

231

public static String uriPathToPath(String uriPath);

232

233

/** Encode query parameter value */

234

public static String encodeQuery(String query);

235

236

/** Decode query parameter value */

237

public static String decodeQuery(String query);

238

}

239

```

240

241

**Usage Examples:**

242

243

```java

244

import org.eclipse.jetty.util.URIUtil;

245

246

// Path manipulation

247

String canonical = URIUtil.canonicalPath("/app/docs/../index.html"); // "/app/index.html"

248

String combined = URIUtil.addPaths("/api", "users/123"); // "/api/users/123"

249

String parent = URIUtil.parentPath("/api/users/123"); // "/api/users"

250

251

// Encoding/decoding

252

String encoded = URIUtil.encodePath("/docs/file with spaces.pdf");

253

String decoded = URIUtil.decodePath("/docs/file%20with%20spaces.pdf");

254

255

// Security validation

256

boolean isSafe = URIUtil.isValidPath(userProvidedPath);

257

258

// Query handling

259

String encodedQuery = URIUtil.encodeQuery("name=John Doe&age=30");

260

String decodedQuery = URIUtil.decodeQuery("name=John%20Doe&age=30");

261

```

262

263

### IO

264

265

Input/Output stream utilities for efficient I/O operations.

266

267

```java { .api }

268

/**

269

* I/O utility methods for stream operations

270

*/

271

public class IO {

272

/** Copy data from InputStream to OutputStream */

273

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

274

275

/** Copy data with specified buffer size */

276

public static void copy(InputStream in, OutputStream out, int bufferSize) throws IOException;

277

278

/** Read entire InputStream into String */

279

public static String toString(InputStream in) throws IOException;

280

281

/** Read entire InputStream into String with charset */

282

public static String toString(InputStream in, Charset charset) throws IOException;

283

284

/** Read entire InputStream into byte array */

285

public static byte[] readBytes(InputStream in) throws IOException;

286

287

/** Close resource silently (ignoring exceptions) */

288

public static void close(Closeable closeable);

289

290

/** Close multiple resources silently */

291

public static void close(Closeable... closeables);

292

293

/** Get NullOutputStream that discards all data */

294

public static OutputStream getNullOutputStream();

295

296

/** Get NullInputStream that returns no data */

297

public static InputStream getNullInputStream();

298

}

299

```

300

301

**Usage Examples:**

302

303

```java

304

import org.eclipse.jetty.util.IO;

305

import java.io.*;

306

import java.nio.charset.StandardCharsets;

307

308

// Stream copying

309

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

310

FileOutputStream out = new FileOutputStream("output.txt")) {

311

IO.copy(in, out);

312

}

313

314

// Reading content

315

try (FileInputStream in = new FileInputStream("data.txt")) {

316

String content = IO.toString(in, StandardCharsets.UTF_8);

317

byte[] bytes = IO.readBytes(in);

318

}

319

320

// Safe resource cleanup

321

FileInputStream stream = null;

322

try {

323

stream = new FileInputStream("file.txt");

324

// ... use stream

325

} finally {

326

IO.close(stream); // Safe even if stream is null

327

}

328

```

329

330

### Scanner

331

332

File system monitoring and change detection utilities.

333

334

```java { .api }

335

/**

336

* File system scanner for monitoring file changes

337

*/

338

public class Scanner extends AbstractLifeCycle {

339

/** Create new scanner */

340

public Scanner();

341

342

/** Add directory to scan */

343

public void addDirectory(Path directory);

344

345

/** Add specific file to monitor */

346

public void addFile(Path file);

347

348

/** Set scan interval in milliseconds */

349

public void setScanInterval(long intervalMs);

350

351

/** Add listener for scan events */

352

public void addListener(Scanner.Listener listener);

353

354

/** Remove listener */

355

public void removeListener(Scanner.Listener listener);

356

357

/** Perform one-time scan */

358

public void scan();

359

360

/** Scan listener interface */

361

public interface Listener {

362

void filesChanged(Set<String> changedFiles);

363

default void scanStarted(int cycle) {}

364

default void scanEnded(int cycle) {}

365

}

366

}

367

```

368

369

**Usage Examples:**

370

371

```java

372

import org.eclipse.jetty.util.Scanner;

373

import java.nio.file.Paths;

374

import java.util.Set;

375

376

// Create and configure scanner

377

Scanner scanner = new Scanner();

378

scanner.addDirectory(Paths.get("/app/config"));

379

scanner.addFile(Paths.get("/app/settings.properties"));

380

scanner.setScanInterval(5000); // 5 seconds

381

382

// Add change listener

383

scanner.addListener(new Scanner.Listener() {

384

@Override

385

public void filesChanged(Set<String> changedFiles) {

386

System.out.println("Files changed: " + changedFiles);

387

// Reload configuration or restart components

388

}

389

});

390

391

// Start monitoring

392

scanner.start();

393

394

// Later, stop monitoring

395

scanner.stop();

396

```

397

398

## Error Handling

399

400

Core utilities generally throw standard Java exceptions:

401

402

- `IOException` - for I/O operations that fail

403

- `IllegalArgumentException` - for invalid method parameters

404

- `NullPointerException` - for null parameters where not allowed

405

- `RuntimeException` - for unexpected runtime errors

406

407

Most utility methods are designed to be safe and handle edge cases gracefully, often returning sensible defaults rather than throwing exceptions.