0
# Utility Classes
1
2
Comprehensive utility libraries for HTTP parsing, byte/character buffers, character encoding, networking, threading, URI encoding, MIME type handling, collections, and common operations used throughout Tomcat.
3
4
## Capabilities
5
6
### Byte Buffers
7
8
Efficient byte buffer management.
9
10
```java { .api }
11
public final class ByteChunk implements Cloneable, Serializable {
12
public ByteChunk();
13
public ByteChunk(int initial);
14
15
// Buffer management
16
public void setBytes(byte[] b, int off, int len);
17
public byte[] getBytes();
18
public byte[] getBuffer();
19
public int getStart();
20
public void setStart(int start);
21
public int getEnd();
22
public void setEnd(int end);
23
public int getLength();
24
public void setLimit(int limit);
25
public int getLimit();
26
27
// Operations
28
public void recycle();
29
public void reset();
30
public void allocate(int initial, int limit);
31
public void append(byte b) throws IOException;
32
public void append(ByteChunk src) throws IOException;
33
public int subtract() throws IOException;
34
public int subtract(byte[] dest, int off, int len) throws IOException;
35
36
// Comparison
37
public boolean equals(String s);
38
public boolean equalsIgnoreCase(String s);
39
public boolean startsWith(String s, int pos);
40
public boolean startsWithIgnoreCase(String s, int pos);
41
42
// Conversion
43
public String toString();
44
public String toStringInternal();
45
public long getLong();
46
}
47
```
48
49
### Character Buffers
50
51
Character buffer for efficient string handling.
52
53
```java { .api }
54
public final class CharChunk implements Cloneable, Serializable {
55
public CharChunk();
56
public CharChunk(int initial);
57
58
// Buffer management
59
public void setChars(char[] c, int off, int len);
60
public char[] getChars();
61
public char[] getBuffer();
62
public int getStart();
63
public void setStart(int start);
64
public int getEnd();
65
public void setEnd(int end);
66
public int getLength();
67
68
// Operations
69
public void recycle();
70
public void reset();
71
public void allocate(int initial, int limit);
72
public void append(char b) throws IOException;
73
public void append(CharChunk src) throws IOException;
74
public void append(String s) throws IOException;
75
public void append(String s, int off, int len) throws IOException;
76
77
// Comparison
78
public boolean equals(String s);
79
public boolean equalsIgnoreCase(String s);
80
public boolean startsWith(String s, int pos);
81
public int indexOf(String src, int start);
82
83
// Conversion
84
public String toString();
85
public String toStringInternal();
86
}
87
```
88
89
### MessageBytes
90
91
Efficient representation of strings as bytes or chars.
92
93
```java { .api }
94
public final class MessageBytes implements Cloneable, Serializable {
95
// Type constants
96
public static final int T_NULL = 0;
97
public static final int T_STR = 1;
98
public static final int T_BYTES = 2;
99
public static final int T_CHARS = 3;
100
101
public static MessageBytes newInstance();
102
103
// Type management
104
public int getType();
105
public boolean isNull();
106
107
// String operations
108
public void setString(String s);
109
public String getString();
110
public String toString();
111
public String toStringType();
112
113
// Byte operations
114
public ByteChunk getByteChunk();
115
public void setBytes(byte[] b, int off, int len);
116
117
// Char operations
118
public CharChunk getCharChunk();
119
public void setChars(char[] c, int off, int len);
120
121
// Conversion
122
public void toBytes();
123
public void toChars();
124
125
// Operations
126
public void recycle();
127
public void duplicate(MessageBytes src) throws IOException;
128
129
// Comparison
130
public boolean equals(String s);
131
public boolean equalsIgnoreCase(String s);
132
public boolean equals(MessageBytes mb);
133
public boolean equals(byte[] b, int off, int len);
134
public boolean equals(CharChunk cc);
135
public boolean equals(char[] c, int off, int len);
136
public boolean startsWithIgnoreCase(String s, int pos);
137
public int indexOf(String s, int starting);
138
public int indexOf(String s);
139
140
// Numeric conversion
141
public long getLong();
142
}
143
```
144
145
### B2CConverter
146
147
Byte-to-character encoding conversion.
148
149
```java { .api }
150
public class B2CConverter {
151
public B2CConverter(Charset charset);
152
public B2CConverter(String encoding) throws UnsupportedEncodingException;
153
154
public void convert(ByteChunk bb, CharChunk cb) throws IOException;
155
public void convert(ByteChunk bb, CharChunk cb, boolean endOfInput) throws IOException;
156
157
public void recycle();
158
159
public Charset getCharset();
160
}
161
```
162
163
### HTTP Utilities
164
165
Utilities for parsing HTTP headers, cookies, and parameters.
166
167
```java { .api }
168
// MIME headers management
169
public class MimeHeaders {
170
public MimeHeaders();
171
172
// Header management
173
public void addValue(String name);
174
public MessageBytes addValue(byte[] b, int startN, int len);
175
public MessageBytes getValue(String name);
176
public MessageBytes getUniqueValue(String name);
177
public int size();
178
public MessageBytes getName(int n);
179
public MessageBytes getValue(int n);
180
181
// Operations
182
public void recycle();
183
public void removeHeader(String name);
184
public int findHeader(String name, int starting);
185
186
// Iteration
187
public Enumeration<String> names();
188
public Enumeration<String> values(String name);
189
}
190
191
// Request parameters
192
public final class Parameters {
193
public Parameters();
194
195
// Parameter management
196
public void addParameter(String name, String value);
197
public String getParameter(String name);
198
public Enumeration<String> getParameterNames();
199
public String[] getParameterValues(String name);
200
201
// Processing
202
public void processParameters(MessageBytes data, Charset charset);
203
public void processParameters(byte[] bytes, int start, int len);
204
205
public void recycle();
206
public void setLimit(int limit);
207
public int getLimit();
208
}
209
210
// Cookie processing
211
public abstract class CookieProcessor {
212
public abstract void parseCookieHeader(MimeHeaders headers, ServerCookies serverCookies);
213
public abstract String generateHeader(Cookie cookie);
214
public abstract String generateHeader(Cookie cookie, HttpServletRequest request);
215
}
216
217
public class Rfc6265CookieProcessor extends CookieProcessor {
218
public Rfc6265CookieProcessor();
219
220
public void parseCookieHeader(MimeHeaders headers, ServerCookies serverCookies);
221
public String generateHeader(Cookie cookie);
222
public String generateHeader(Cookie cookie, HttpServletRequest request);
223
224
// Configuration
225
public void setPartitioned(boolean partitioned);
226
public boolean getPartitioned();
227
}
228
229
public class ServerCookie {
230
// Cookie management
231
public MessageBytes getName();
232
public MessageBytes getValue();
233
public void setVersion(int version);
234
public int getVersion();
235
}
236
237
public class ServerCookies {
238
public ServerCookies(int initialSize);
239
240
public ServerCookie getCookie(int idx);
241
public int getCookieCount();
242
public void recycle();
243
}
244
245
// HTTP date formatting
246
public final class FastHttpDateFormat {
247
public static long parseDate(String value);
248
public static long parseDate(MessageBytes value);
249
public static String formatDate(long value);
250
public static String getCurrentDate();
251
}
252
253
// HTTP parsing
254
public class HttpParser {
255
public static boolean isToken(int c);
256
public static boolean isHex(int c);
257
public static boolean isNotRequestTarget(int c);
258
public static boolean isAbsolutePathRelaxed(int c);
259
public static boolean isQueryRelaxed(int c);
260
261
// Media type parsing
262
public static String unquote(String input);
263
public static String unquoteOnly(String input);
264
}
265
```
266
267
### URI Utilities
268
269
URI encoding and decoding.
270
271
```java { .api }
272
public final class UDecoder {
273
public UDecoder();
274
275
public void convert(ByteChunk mb) throws IOException;
276
public void convert(ByteChunk mb, boolean query) throws IOException;
277
public void convert(CharChunk mb) throws IOException;
278
public void convert(CharChunk mb, boolean query) throws IOException;
279
280
public void setAllowEncodedSlash(boolean allowEncodedSlash);
281
}
282
283
public final class UEncoder {
284
public static final BitSet DEFAULT_ALLOWED;
285
286
public UEncoder();
287
public UEncoder(SafeCharsSet safeCharsSet);
288
289
public void urlEncode(CharChunk cb, CharChunk out);
290
public void urlEncode(String s, CharChunk out);
291
}
292
293
public final class UriUtil {
294
public static boolean hasScheme(CharChunk uri);
295
public static int getSchemeLength(String uri);
296
public static String buildJarUrl(File jarFile) throws MalformedURLException;
297
public static String buildJarUrl(File jarFile, String entryPath) throws MalformedURLException;
298
public static String buildJarUrl(String fileUrlString) throws MalformedURLException;
299
public static String buildJarUrl(String fileUrlString, String entryPath) throws MalformedURLException;
300
public static URL buildJarSafeUrl(File file) throws MalformedURLException;
301
public static String warToJar(String warUrl);
302
}
303
```
304
305
### Security Utilities
306
307
Security-related utility classes.
308
309
```java { .api }
310
// Concurrent message digest for thread-safe hashing
311
public class ConcurrentMessageDigest {
312
public static byte[] digestMD5(byte[]... input);
313
public static byte[] digestSHA1(byte[]... input);
314
public static byte[] digest(String algorithm, byte[]... input);
315
public static byte[] digest(String algorithm, int iterations, byte[]... input);
316
}
317
318
// MD5 encoding
319
public final class MD5Encoder {
320
public static String encode(byte[] binaryData);
321
}
322
323
// Base64 encoding/decoding
324
public class Base64 {
325
public Base64();
326
public Base64(int lineLength);
327
public Base64(int lineLength, byte[] lineSeparator);
328
329
public static byte[] encodeBase64(byte[] binaryData);
330
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked);
331
public static byte[] encodeBase64URLSafe(byte[] binaryData);
332
public static byte[] decodeBase64(byte[] base64Data);
333
public static byte[] decodeBase64(String base64String);
334
public static boolean isBase64(byte[] octets);
335
public static boolean isBase64(String base64);
336
}
337
338
// Escape utilities
339
public class Escape {
340
public static String htmlElementContent(String content);
341
public static String htmlElementContext(String context);
342
public static String xml(String input);
343
public static String xml(String org, String dest);
344
}
345
```
346
347
### Threading Utilities
348
349
Thread pool and task management.
350
351
```java { .api }
352
public class ThreadPoolExecutor extends java.util.concurrent.ThreadPoolExecutor {
353
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
354
TimeUnit unit, BlockingQueue<Runnable> workQueue,
355
ThreadFactory threadFactory);
356
357
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
358
TimeUnit unit, BlockingQueue<Runnable> workQueue,
359
RejectedExecutionHandler handler);
360
361
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
362
TimeUnit unit, BlockingQueue<Runnable> workQueue,
363
ThreadFactory threadFactory, RejectedExecutionHandler handler);
364
365
// Tomcat-specific extensions
366
public void contextStopping();
367
public long getStopTimeout();
368
public void setStopTimeout(long stopTimeout, TimeUnit timeUnit);
369
}
370
371
public class TaskQueue extends LinkedBlockingQueue<Runnable> {
372
public TaskQueue();
373
public TaskQueue(int capacity);
374
375
public boolean offer(Runnable o);
376
public boolean offer(Runnable o, long timeout, TimeUnit unit) throws InterruptedException;
377
public boolean force(Runnable o);
378
public boolean force(Runnable o, long timeout, TimeUnit unit) throws InterruptedException;
379
380
public void setParent(ThreadPoolExecutor tp);
381
}
382
383
public class TaskThreadFactory implements ThreadFactory {
384
public TaskThreadFactory(String namePrefix, boolean daemon, int priority);
385
386
public Thread newThread(Runnable r);
387
388
public String getNamePrefix();
389
public void setNamePrefix(String namePrefix);
390
public boolean isDaemon();
391
public void setDaemon(boolean daemon);
392
public int getPriority();
393
public void setPriority(int priority);
394
}
395
396
public class VirtualThreadExecutor implements Executor {
397
public VirtualThreadExecutor(String namePrefix);
398
399
public void execute(Runnable command);
400
401
public String getName();
402
}
403
```
404
405
### JAR Scanning
406
407
Utilities for scanning JAR files for annotations and resources.
408
409
```java { .api }
410
public interface JarScanner {
411
void scan(JarScanType scanType, ServletContext context, JarScannerCallback callback);
412
413
JarScanFilter getJarScanFilter();
414
void setJarScanFilter(JarScanFilter jarScanFilter);
415
}
416
417
public interface JarScannerCallback {
418
void scan(Jar jar, String webappPath, boolean isWebapp) throws IOException;
419
void scan(File file, String webappPath, boolean isWebapp) throws IOException;
420
void scanWebInfClasses() throws IOException;
421
}
422
423
public interface JarScanFilter {
424
boolean check(JarScanType jarScanType, String jarName);
425
}
426
427
public class StandardJarScanner implements JarScanner {
428
public StandardJarScanner();
429
430
public void scan(JarScanType scanType, ServletContext context, JarScannerCallback callback);
431
432
// Configuration
433
public void setScanManifest(boolean scanManifest);
434
public boolean isScanManifest();
435
public void setScanAllFiles(boolean scanAllFiles);
436
public boolean isScanAllFiles();
437
public void setScanAllDirectories(boolean scanAllDirectories);
438
public boolean isScanAllDirectories();
439
public void setScanClassPath(boolean scanClassPath);
440
public boolean isScanClassPath();
441
public void setScanBootstrapClassPath(boolean scanBootstrapClassPath);
442
public boolean isScanBootstrapClassPath();
443
444
public JarScanFilter getJarScanFilter();
445
public void setJarScanFilter(JarScanFilter jarScanFilter);
446
}
447
448
public class StandardJarScanFilter implements JarScanFilter {
449
public StandardJarScanFilter();
450
451
public boolean check(JarScanType jarScanType, String jarName);
452
453
// Configuration
454
public void setTldSkip(String tldSkip);
455
public String getTldSkip();
456
public void setTldScan(String tldScan);
457
public String getTldScan();
458
public void setPluggabilitySkip(String pluggabilitySkip);
459
public String getPluggabilitySkip();
460
public void setPluggabilityScan(String pluggabilityScan);
461
public String getPluggabilityScan();
462
}
463
464
public enum JarScanType {
465
TLD,
466
PLUGGABILITY,
467
OTHER
468
}
469
```
470
471
### Instance Management
472
473
Object lifecycle and dependency injection support.
474
475
```java { .api }
476
public interface InstanceManager {
477
Object newInstance(Class<?> clazz) throws ReflectiveOperationException, NamingException;
478
Object newInstance(String className) throws ReflectiveOperationException, NamingException;
479
Object newInstance(String className, ClassLoader classLoader)
480
throws ReflectiveOperationException, NamingException;
481
482
void newInstance(Object o) throws ReflectiveOperationException, NamingException;
483
484
void destroyInstance(Object o) throws ReflectiveOperationException;
485
486
void backgroundProcess();
487
}
488
489
public class SimpleInstanceManager implements InstanceManager {
490
public SimpleInstanceManager();
491
492
public Object newInstance(Class<?> clazz) throws ReflectiveOperationException, NamingException;
493
public Object newInstance(String className) throws ReflectiveOperationException, NamingException;
494
public Object newInstance(String className, ClassLoader classLoader)
495
throws ReflectiveOperationException, NamingException;
496
497
public void newInstance(Object o) throws ReflectiveOperationException, NamingException;
498
499
public void destroyInstance(Object o) throws ReflectiveOperationException;
500
501
public void backgroundProcess();
502
}
503
```
504
505
### String and Collection Utilities
506
507
```java { .api }
508
// String utilities
509
public class StringUtils {
510
public static String join(String[] array);
511
public static String join(Collection<?> collection);
512
public static String join(String[] array, char separator);
513
public static String join(Collection<?> collection, char separator);
514
}
515
516
public final class Ascii {
517
public static int toLower(int c);
518
public static long parseLong(byte[] b, int off, int len) throws NumberFormatException;
519
}
520
521
public class HexUtils {
522
public static int getDec(int index);
523
public static byte getHex(int index);
524
public static String toHexString(byte[] bytes);
525
public static byte[] fromHexString(String input);
526
}
527
528
// Case insensitive maps
529
public class CaseInsensitiveKeyMap<V> extends HashMap<String,V> {
530
public CaseInsensitiveKeyMap();
531
}
532
533
// Synchronized collections
534
public class SynchronizedQueue<T> {
535
public SynchronizedQueue();
536
public SynchronizedQueue(int initialSize);
537
538
public boolean offer(T t);
539
public T poll();
540
public T poll(long timeout) throws InterruptedException;
541
public int size();
542
public void clear();
543
}
544
545
public class SynchronizedStack<T> {
546
public SynchronizedStack();
547
public SynchronizedStack(int size, int limit);
548
549
public boolean push(T obj);
550
public T pop();
551
public int size();
552
public void clear();
553
}
554
```
555
556
### I/O and File Utilities
557
558
```java { .api }
559
public class IOTools {
560
public static void flow(InputStream is, OutputStream os) throws IOException;
561
public static void flow(Reader reader, Writer writer) throws IOException;
562
public static long flow(InputStream is, OutputStream os, byte[] buf) throws IOException;
563
public static long flow(Reader reader, Writer writer, char[] buf) throws IOException;
564
}
565
566
public interface ConfigurationSource {
567
Resource getResource(String name) throws IOException;
568
URI getURI(String name);
569
}
570
571
public class ConfigFileLoader {
572
public static InputStream getInputStream(String path) throws IOException;
573
public static InputStream getSource(String path) throws IOException;
574
}
575
576
public final class Matcher {
577
public static boolean matchName(String[] patternArray, String name, boolean caseSensitive);
578
public static boolean match(String pattern, String input, boolean caseSensitive);
579
}
580
```
581
582
## Usage Examples
583
584
### Using MessageBytes
585
586
```java
587
import org.apache.tomcat.util.buf.MessageBytes;
588
import org.apache.tomcat.util.buf.ByteChunk;
589
590
public class MessageBytesExample {
591
public void processHeader() {
592
MessageBytes mb = MessageBytes.newInstance();
593
mb.setString("Content-Type");
594
595
// Convert to bytes
596
mb.toBytes();
597
ByteChunk bc = mb.getByteChunk();
598
599
System.out.println("Length: " + bc.getLength());
600
System.out.println("Value: " + mb.toString());
601
602
// Comparison
603
if (mb.equalsIgnoreCase("content-type")) {
604
System.out.println("Match found");
605
}
606
607
// Recycle for reuse
608
mb.recycle();
609
}
610
}
611
```
612