Comprehensive Java utility library providing infrastructure and helper classes for the Eclipse Jetty web server
—
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.
ByteBuffer manipulation utilities providing efficient buffer operations for I/O and data processing.
/**
* ByteBuffer utility methods for allocation, conversion, and manipulation
*/
public class BufferUtil {
/** Allocate a new ByteBuffer with the specified capacity */
public static ByteBuffer allocate(int capacity);
/** Allocate a direct ByteBuffer with the specified capacity */
public static ByteBuffer allocateDirect(int capacity);
/** Convert ByteBuffer content to string using specified charset */
public static String toString(ByteBuffer buffer, Charset charset);
/** Convert ByteBuffer content to byte array */
public static byte[] toArray(ByteBuffer buffer);
/** Write ByteBuffer content to OutputStream */
public static void writeTo(ByteBuffer buffer, OutputStream out) throws IOException;
/** Append byte array to ByteBuffer */
public static void append(ByteBuffer buffer, byte[] array);
/** Clear ByteBuffer and reset position/limit */
public static void clear(ByteBuffer buffer);
/** Check if ByteBuffer is empty (no remaining bytes) */
public static boolean isEmpty(ByteBuffer buffer);
/** Check if ByteBuffer has remaining bytes */
public static boolean hasContent(ByteBuffer buffer);
/** Get remaining bytes count in ByteBuffer */
public static int length(ByteBuffer buffer);
/** Flip ByteBuffer from write mode to read mode */
public static void flipToFlush(ByteBuffer buffer, int position);
/** Compact ByteBuffer, removing consumed bytes */
public static void compact(ByteBuffer buffer);
}Usage Examples:
import org.eclipse.jetty.util.BufferUtil;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
// Basic buffer operations
ByteBuffer buffer = BufferUtil.allocate(1024);
BufferUtil.append(buffer, "Hello World".getBytes(StandardCharsets.UTF_8));
String result = BufferUtil.toString(buffer, StandardCharsets.UTF_8);
// I/O operations
ByteArrayOutputStream output = new ByteArrayOutputStream();
BufferUtil.writeTo(buffer, output);
byte[] data = output.toByteArray();
// Buffer state management
BufferUtil.flipToFlush(buffer, 0);
boolean hasData = BufferUtil.hasContent(buffer);
int remaining = BufferUtil.length(buffer);String processing utilities for efficient string manipulation and validation.
/**
* String utility methods for validation, splitting, and manipulation
*/
public class StringUtil {
/** Check if string is null or contains only whitespace */
public static boolean isBlank(String str);
/** Check if string is null or empty */
public static boolean isEmpty(String str);
/** Check if string is not blank */
public static boolean isNotBlank(String str);
/** Split string by delimiter character */
public static String[] split(String str, char delimiter);
/** Split CSV string handling quoted values */
public static List<String> csvSplit(String str);
/** Join string array with delimiter */
public static String join(String[] array, String delimiter);
/** Replace all occurrences in string */
public static String replace(String str, String target, String replacement);
/** Convert string to lowercase using ASCII rules */
public static String asciiToLowerCase(String str);
/** Check if string starts with prefix (case sensitive) */
public static boolean startsWith(String str, String prefix);
/** Check if string ends with suffix (case sensitive) */
public static boolean endsWith(String str, String suffix);
/** Sanitize string for filename usage */
public static String sanitizeFileSystemName(String str);
}Usage Examples:
import org.eclipse.jetty.util.StringUtil;
import java.util.List;
// String validation
boolean isValid = !StringUtil.isBlank(userInput);
boolean hasContent = StringUtil.isNotBlank(data);
// String splitting
String[] parts = StringUtil.split("one,two,three", ',');
List<String> csvFields = StringUtil.csvSplit("\"quoted,field\",normal,field");
// String manipulation
String joined = StringUtil.join(new String[]{"a", "b", "c"}, "-");
String lower = StringUtil.asciiToLowerCase("HTTP/1.1");
String clean = StringUtil.sanitizeFileSystemName("file:name?.txt");Type conversion and reflection utilities for working with Java types and classes.
/**
* Type conversion and utility methods for reflection and type handling
*/
public class TypeUtil {
/** Convert string value to specified type */
public static <T> T valueOf(Class<T> type, String value);
/** Get location (JAR/directory) of a class */
public static String getLocationOfClass(Class<?> clazz);
/** Dump object information to appendable */
public static void dump(Appendable out, String indent, Object... objects);
/** Convert primitive type to wrapper class */
public static Class<?> wrapperFor(Class<?> primitiveType);
/** Check if class is a numeric type */
public static boolean isNumeric(Class<?> clazz);
/** Parse integer from string with bounds checking */
public static int parseInt(String str, int defaultValue);
/** Parse long from string with bounds checking */
public static long parseLong(String str, long defaultValue);
/** Parse boolean from string */
public static boolean parseBoolean(String str);
/** Get simple class name without package */
public static String toShortName(Class<?> clazz);
}Usage Examples:
import org.eclipse.jetty.util.TypeUtil;
// Type conversion
Integer value = TypeUtil.valueOf(Integer.class, "42");
Boolean flag = TypeUtil.valueOf(Boolean.class, "true");
// Safe parsing with defaults
int port = TypeUtil.parseInt(portString, 8080);
long timeout = TypeUtil.parseLong(timeoutString, 30000L);
// Class information
String location = TypeUtil.getLocationOfClass(MyClass.class);
String shortName = TypeUtil.toShortName(java.util.ArrayList.class); // "ArrayList"
// Debugging
StringBuilder debug = new StringBuilder();
TypeUtil.dump(debug, "", myObject, "with label");URI and URL manipulation utilities for path operations and encoding.
/**
* URI utility methods for path manipulation and encoding
*/
public class URIUtil {
/** Canonicalize path by resolving . and .. segments */
public static String canonicalPath(String path);
/** Add two path segments together properly */
public static String addPaths(String path1, String path2);
/** Decode URL-encoded path */
public static String decodePath(String path);
/** URL-encode path for safe transmission */
public static String encodePath(String path);
/** Get parent path of given path */
public static String parentPath(String path);
/** Check if path is within base path (security check) */
public static boolean isValidPath(String path);
/** Convert file system path to URI path */
public static String pathToUriPath(String path);
/** Convert URI path to file system path */
public static String uriPathToPath(String uriPath);
/** Encode query parameter value */
public static String encodeQuery(String query);
/** Decode query parameter value */
public static String decodeQuery(String query);
}Usage Examples:
import org.eclipse.jetty.util.URIUtil;
// Path manipulation
String canonical = URIUtil.canonicalPath("/app/docs/../index.html"); // "/app/index.html"
String combined = URIUtil.addPaths("/api", "users/123"); // "/api/users/123"
String parent = URIUtil.parentPath("/api/users/123"); // "/api/users"
// Encoding/decoding
String encoded = URIUtil.encodePath("/docs/file with spaces.pdf");
String decoded = URIUtil.decodePath("/docs/file%20with%20spaces.pdf");
// Security validation
boolean isSafe = URIUtil.isValidPath(userProvidedPath);
// Query handling
String encodedQuery = URIUtil.encodeQuery("name=John Doe&age=30");
String decodedQuery = URIUtil.decodeQuery("name=John%20Doe&age=30");Input/Output stream utilities for efficient I/O operations.
/**
* I/O utility methods for stream operations
*/
public class IO {
/** Copy data from InputStream to OutputStream */
public static void copy(InputStream in, OutputStream out) throws IOException;
/** Copy data with specified buffer size */
public static void copy(InputStream in, OutputStream out, int bufferSize) throws IOException;
/** Read entire InputStream into String */
public static String toString(InputStream in) throws IOException;
/** Read entire InputStream into String with charset */
public static String toString(InputStream in, Charset charset) throws IOException;
/** Read entire InputStream into byte array */
public static byte[] readBytes(InputStream in) throws IOException;
/** Close resource silently (ignoring exceptions) */
public static void close(Closeable closeable);
/** Close multiple resources silently */
public static void close(Closeable... closeables);
/** Get NullOutputStream that discards all data */
public static OutputStream getNullOutputStream();
/** Get NullInputStream that returns no data */
public static InputStream getNullInputStream();
}Usage Examples:
import org.eclipse.jetty.util.IO;
import java.io.*;
import java.nio.charset.StandardCharsets;
// Stream copying
try (FileInputStream in = new FileInputStream("input.txt");
FileOutputStream out = new FileOutputStream("output.txt")) {
IO.copy(in, out);
}
// Reading content
try (FileInputStream in = new FileInputStream("data.txt")) {
String content = IO.toString(in, StandardCharsets.UTF_8);
byte[] bytes = IO.readBytes(in);
}
// Safe resource cleanup
FileInputStream stream = null;
try {
stream = new FileInputStream("file.txt");
// ... use stream
} finally {
IO.close(stream); // Safe even if stream is null
}File system monitoring and change detection utilities.
/**
* File system scanner for monitoring file changes
*/
public class Scanner extends AbstractLifeCycle {
/** Create new scanner */
public Scanner();
/** Add directory to scan */
public void addDirectory(Path directory);
/** Add specific file to monitor */
public void addFile(Path file);
/** Set scan interval in milliseconds */
public void setScanInterval(long intervalMs);
/** Add listener for scan events */
public void addListener(Scanner.Listener listener);
/** Remove listener */
public void removeListener(Scanner.Listener listener);
/** Perform one-time scan */
public void scan();
/** Scan listener interface */
public interface Listener {
void filesChanged(Set<String> changedFiles);
default void scanStarted(int cycle) {}
default void scanEnded(int cycle) {}
}
}Usage Examples:
import org.eclipse.jetty.util.Scanner;
import java.nio.file.Paths;
import java.util.Set;
// Create and configure scanner
Scanner scanner = new Scanner();
scanner.addDirectory(Paths.get("/app/config"));
scanner.addFile(Paths.get("/app/settings.properties"));
scanner.setScanInterval(5000); // 5 seconds
// Add change listener
scanner.addListener(new Scanner.Listener() {
@Override
public void filesChanged(Set<String> changedFiles) {
System.out.println("Files changed: " + changedFiles);
// Reload configuration or restart components
}
});
// Start monitoring
scanner.start();
// Later, stop monitoring
scanner.stop();Core utilities generally throw standard Java exceptions:
IOException - for I/O operations that failIllegalArgumentException - for invalid method parametersNullPointerException - for null parameters where not allowedRuntimeException - for unexpected runtime errorsMost utility methods are designed to be safe and handle edge cases gracefully, often returning sensible defaults rather than throwing exceptions.
Install with Tessl CLI
npx tessl i tessl/maven-org-eclipse-jetty--jetty-util