CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-seleniumhq-selenium--selenium-http

HTTP client and server abstractions for Selenium WebDriver communication

Pending
Overview
Eval results
Files

content-handling.mddocs/

Content Handling

Comprehensive content utilities for converting between different formats (strings, bytes, JSON) with charset support and streaming capabilities for HTTP message content management.

Capabilities

Contents Utility Class

Central utility class providing static methods for creating, converting, and manipulating HTTP message content with support for multiple formats and character encodings.

/**
 * Utility class for HTTP content handling and conversion
 * Provides static methods for creating and converting content suppliers
 */
public class Contents {
    /**
     * Creates empty content supplier with zero length
     * @return Empty Contents.Supplier
     */
    public static Supplier empty();
    
    /**
     * Creates UTF-8 encoded string content supplier
     * @param value Character sequence to convert
     * @return Contents.Supplier for UTF-8 string
     */
    public static Supplier utf8String(CharSequence value);
    
    /**
     * Creates string content supplier with specified charset
     * @param value Character sequence to convert
     * @param charset Character encoding to use
     * @return Contents.Supplier for encoded string
     */
    public static Supplier string(CharSequence value, Charset charset);
    
    /**
     * Creates content supplier from byte array
     * Makes defensive copy of input array
     * @param bytes Byte array to use as content
     * @return Contents.Supplier for byte data
     */
    public static Supplier bytes(byte[] bytes);
    
    /**
     * Converts content supplier to byte array
     * @param supplier Contents.Supplier to convert
     * @return Byte array containing all content
     */
    public static byte[] bytes(Supplier supplier);
    
    /**
     * Converts content supplier to UTF-8 string
     * @param supplier Contents.Supplier to convert
     * @return String decoded using UTF-8
     */
    public static String utf8String(Supplier supplier);
    
    /**
     * Converts content supplier to string with specified charset
     * @param supplier Contents.Supplier to convert
     * @param charset Character encoding for decoding
     * @return String decoded using specified charset
     */
    public static String string(Supplier supplier, Charset charset);
    
    /**
     * Extracts string content from HTTP message using detected encoding
     * Uses Content-Type header to determine charset, defaults to UTF-8
     * @param message HTTP message to extract content from
     * @return String content using detected encoding
     */
    public static String string(HttpMessage<?> message);
    
    /**
     * Creates UTF-8 reader from content supplier
     * @param supplier Contents.Supplier to read from
     * @return Reader for UTF-8 content
     */
    public static Reader utf8Reader(Supplier supplier);
    
    /**
     * Creates reader from content supplier with specified charset
     * @param supplier Contents.Supplier to read from
     * @param charset Character encoding for reading
     * @return Reader for content with specified encoding
     */
    public static Reader reader(Supplier supplier, Charset charset);
    
    /**
     * Creates reader from HTTP message using detected encoding
     * Uses Content-Type header to determine charset
     * @param message HTTP message to create reader for
     * @return Reader using detected charset
     */
    public static Reader reader(HttpMessage<?> message);
    
    /**
     * Converts object to JSON content supplier
     * Serializes object using JSON serialization
     * @param obj Object to serialize as JSON
     * @return Contents.Supplier for JSON content
     */
    public static Supplier asJson(Object obj);
    
    /**
     * Deserializes JSON content from HTTP message
     * @param message HTTP message containing JSON content
     * @param typeOfT Type to deserialize JSON into
     * @return Deserialized object of specified type
     */
    public static <T> T fromJson(HttpMessage<?> message, Type typeOfT);
    
    /**
     * Converts file to Base64 encoded string
     * @param input File to encode
     * @return Base64 encoded string representation
     */
    public static String string(File input);
}

Usage Examples:

import org.openqa.selenium.remote.http.*;
import java.nio.charset.StandardCharsets;
import java.io.File;
import java.util.Map;

// Create different types of content
Contents.Supplier emptyContent = Contents.empty();
Contents.Supplier textContent = Contents.utf8String("Hello World");
Contents.Supplier latinContent = Contents.string("Café", StandardCharsets.ISO_8859_1);
Contents.Supplier binaryContent = Contents.bytes("Binary data".getBytes());

// Set content on HTTP messages
HttpRequest request = new HttpRequest(HttpMethod.POST, "/api/data");
request.setContent(textContent);
request.addHeader("Content-Type", "text/plain; charset=UTF-8");

// Convert content to different formats
Contents.Supplier jsonData = Contents.asJson(Map.of(
    "name", "John Doe",
    "age", 30,
    "active", true
));

byte[] jsonBytes = Contents.bytes(jsonData);
String jsonString = Contents.utf8String(jsonData);

System.out.println("JSON as string: " + jsonString);
System.out.println("JSON size: " + jsonBytes.length + " bytes");

// Extract content from responses
HttpResponse response = client.execute(request);
String responseText = Contents.string(response); // Uses detected charset
byte[] responseBytes = Contents.bytes(response.getContent());

// Work with readers for streaming
Reader reader = Contents.reader(response);
BufferedReader buffered = new BufferedReader(reader);
String line;
while ((line = buffered.readLine()) != null) {
    System.out.println("Line: " + line);
}
reader.close();

Contents.Supplier Interface

Interface extending both Supplier<InputStream> and AutoCloseable for providing HTTP content with length information and resource management.

/**
 * Content supplier interface providing InputStream and resource management
 * Extends Supplier<InputStream> and AutoCloseable for proper resource handling
 */
public interface Supplier extends java.util.function.Supplier<InputStream>, AutoCloseable {
    /**
     * Gets the content length in bytes
     * @return Content length, or -1 if unknown
     */
    int length();
    
    /**
     * Closes resources associated with this supplier
     * Should be called when content is no longer needed
     * @throws IOException if an I/O error occurs
     */
    void close() throws IOException;
}

Usage Examples:

import org.openqa.selenium.remote.http.*;
import java.io.InputStream;
import java.io.IOException;

// Create content supplier
Contents.Supplier supplier = Contents.utf8String("Sample content for length testing");

// Check content length
int contentLength = supplier.length();
System.out.println("Content length: " + contentLength + " bytes");

// Use as InputStream supplier
try (InputStream inputStream = supplier.get()) {
    byte[] buffer = new byte[1024];
    int bytesRead = inputStream.read(buffer);
    System.out.println("Read " + bytesRead + " bytes");
} catch (IOException e) {
    System.err.println("Error reading content: " + e.getMessage());
} finally {
    supplier.close(); // Always close resources
}

// Use with try-with-resources for automatic cleanup
try (Contents.Supplier autoCloseSupplier = Contents.utf8String("Auto-close content")) {
    InputStream stream = autoCloseSupplier.get();
    // Use stream...
} // Automatically closes supplier

// Custom supplier implementation
Contents.Supplier customSupplier = new Contents.Supplier() {
    private final byte[] data = "Custom data".getBytes();
    
    @Override
    public InputStream get() {
        return new ByteArrayInputStream(data);
    }
    
    @Override
    public int length() {
        return data.length;
    }
    
    @Override
    public void close() {
        // Custom cleanup if needed
        System.out.println("Custom supplier closed");
    }
};

Content Conversion Examples

String Content Handling

import org.openqa.selenium.remote.http.*;
import java.nio.charset.StandardCharsets;

// Create string content with different encodings
String message = "Hello, 世界! Café";

Contents.Supplier utf8Content = Contents.utf8String(message);
Contents.Supplier latinContent = Contents.string(message, StandardCharsets.ISO_8859_1);
Contents.Supplier utf16Content = Contents.string(message, StandardCharsets.UTF_16);

// Set on HTTP request
HttpRequest request = new HttpRequest(HttpMethod.PUT, "/messages");
request.setContent(utf8Content);
request.addHeader("Content-Type", "text/plain; charset=UTF-8");

// Convert back to string
String retrievedUtf8 = Contents.utf8String(utf8Content);
String retrievedLatin = Contents.string(latinContent, StandardCharsets.ISO_8859_1);

System.out.println("UTF-8: " + retrievedUtf8);
System.out.println("Latin-1: " + retrievedLatin);

// Extract from HTTP response with automatic charset detection
HttpResponse response = client.execute(request);
String responseContent = Contents.string(response); // Uses Content-Type charset

Binary Content Handling

import org.openqa.selenium.remote.http.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

// Handle binary data
byte[] imageData = loadImageFile();
Contents.Supplier binaryContent = Contents.bytes(imageData);

// Set binary content on request
HttpRequest uploadRequest = new HttpRequest(HttpMethod.POST, "/upload");
uploadRequest.setContent(binaryContent);
uploadRequest.addHeader("Content-Type", "image/jpeg");

// Extract binary data from response
HttpResponse uploadResponse = client.execute(uploadRequest);
byte[] responseData = Contents.bytes(uploadResponse.getContent());

System.out.println("Uploaded " + imageData.length + " bytes");
System.out.println("Response " + responseData.length + " bytes");

// File to Base64 conversion
File document = new File("document.pdf");
String base64Document = Contents.string(document);

HttpRequest documentRequest = new HttpRequest(HttpMethod.POST, "/documents");
documentRequest.setContent(Contents.utf8String(base64Document));
documentRequest.addHeader("Content-Type", "text/plain");

private byte[] loadImageFile() throws IOException {
    File imageFile = new File("image.jpg");
    try (FileInputStream fis = new FileInputStream(imageFile)) {
        return fis.readAllBytes();
    }
}

JSON Content Handling

import org.openqa.selenium.remote.http.*;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.List;

// Create JSON content from objects
Map<String, Object> userData = Map.of(
    "id", 123,
    "name", "John Doe",
    "email", "john@example.com",
    "roles", List.of("user", "admin"),
    "active", true
);

Contents.Supplier jsonContent = Contents.asJson(userData);

// Send JSON request
HttpRequest jsonRequest = new HttpRequest(HttpMethod.POST, "/users");
jsonRequest.setContent(jsonContent);
jsonRequest.addHeader("Content-Type", "application/json");

HttpResponse jsonResponse = client.execute(jsonRequest);

// Deserialize JSON response
Map<String, Object> responseMap = Contents.fromJson(jsonResponse, Map.class);
System.out.println("Created user ID: " + responseMap.get("id"));

// Deserialize to custom types using anonymous ParameterizedType
Type listType = new ParameterizedType() {
    public Type[] getActualTypeArguments() { return new Type[]{Map.class}; }
    public Type getRawType() { return List.class; }
    public Type getOwnerType() { return null; }
};
List<Map<String, Object>> userList = Contents.fromJson(jsonResponse, listType);

// Complex object serialization
UserData user = new UserData("Jane Doe", "jane@example.com");
Contents.Supplier userJson = Contents.asJson(user);

HttpRequest createUser = new HttpRequest(HttpMethod.POST, "/users");
createUser.setContent(userJson);

HttpResponse createResponse = client.execute(createUser);
UserData createdUser = Contents.fromJson(createResponse, UserData.class);

System.out.println("Created user: " + createdUser.getName());

// Custom serialization class
public static class UserData {
    private String name;
    private String email;
    
    public UserData(String name, String email) {
        this.name = name;
        this.email = email;
    }
    
    // Getters and setters...
    public String getName() { return name; }
    public String getEmail() { return email; }
}

Stream-based Content Processing

import org.openqa.selenium.remote.http.*;
import java.io.*;
import java.nio.charset.StandardCharsets;

// Process large content using readers
HttpResponse largeResponse = client.execute(request);

try (Reader reader = Contents.reader(largeResponse);
     BufferedReader buffered = new BufferedReader(reader)) {
    
    String line;
    int lineCount = 0;
    while ((line = buffered.readLine()) != null) {
        processLine(line);
        lineCount++;
        
        if (lineCount % 1000 == 0) {
            System.out.println("Processed " + lineCount + " lines");
        }
    }
    
    System.out.println("Total lines processed: " + lineCount);
}

// Create reader with specific charset
try (Reader utf16Reader = Contents.reader(response.getContent(), StandardCharsets.UTF_16)) {
    char[] buffer = new char[1024];
    int charsRead;
    while ((charsRead = utf16Reader.read(buffer)) != -1) {
        String chunk = new String(buffer, 0, charsRead);
        processChunk(chunk);
    }
}

// Stream binary content
Contents.Supplier binarySupplier = Contents.bytes(largeBinaryData);
try (InputStream stream = binarySupplier.get();
     BufferedInputStream buffered = new BufferedInputStream(stream)) {
    
    byte[] buffer = new byte[8192];
    int bytesRead;
    long totalBytes = 0;
    
    while ((bytesRead = buffered.read(buffer)) != -1) {
        processBinaryChunk(buffer, bytesRead);
        totalBytes += bytesRead;
    }
    
    System.out.println("Processed " + totalBytes + " bytes");
} finally {
    binarySupplier.close();
}

private void processLine(String line) { /* process text line */ }
private void processChunk(String chunk) { /* process text chunk */ }
private void processBinaryChunk(byte[] data, int length) { /* process binary data */ }

Content Type Detection

import org.openqa.selenium.remote.http.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

// Automatic charset detection from Content-Type header
HttpResponse response = client.execute(request);

// Response has "Content-Type: text/html; charset=ISO-8859-1"
String content = Contents.string(response); // Uses ISO-8859-1 automatically

// Manual charset handling
Charset detectedCharset = response.getContentEncoding(); // ISO-8859-1
String manualContent = Contents.string(response.getContent(), detectedCharset);

// Override charset detection
String utf8Content = Contents.utf8String(response.getContent()); // Force UTF-8

// Set proper Content-Type when sending
HttpRequest request = new HttpRequest(HttpMethod.POST, "/submit");
request.setContent(Contents.string("Content with special chars: café", StandardCharsets.UTF_8));
request.addHeader("Content-Type", "text/plain; charset=UTF-8");

// Multiple charset handling
Contents.Supplier utf8Data = Contents.utf8String("UTF-8 content: 你好");
Contents.Supplier latinData = Contents.string("Latin-1 content: café", StandardCharsets.ISO_8859_1);

request.setContent(utf8Data);
request.setHeader("Content-Type", "text/plain; charset=UTF-8");

Install with Tessl CLI

npx tessl i tessl/maven-org-seleniumhq-selenium--selenium-http

docs

client-config.md

content-handling.md

filtering.md

http-client.md

index.md

request-response.md

routing.md

websocket.md

tile.json