### Create and Start an HTTP Server Source: https://github.com/fusionauth/java-http/blob/main/README.md This example demonstrates how to create a basic HTTP server with a handler and a listener configuration. The server is started and then closed. ```java import io.fusionauth.http.server.HTTPListenerConfiguration; import io.fusionauth.http.server.HTTPServer; import io.fusionauth.http.server.HTTPHandler; public class Example { public static void main(String... args) { HTTPHandler handler = (req, res) -> { // Handler code goes here }; HTTPServer server = new HTTPServer().withHandler(handler) .withListener(new HTTPListenerConfiguration(4242)); server.start(); // Use server server.close(); } } ``` -------------------------------- ### Complete Server Implementation Example Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/11-module-exports.md Demonstrates how to set up and start a complete HTTP server using all available features, including handlers, listeners, logging, and compression. ```java import io.fusionauth.http.server.*; import io.fusionauth.http.*; import io.fusionauth.http.log.*; import io.fusionauth.http.util.*; import java.nio.file.Path; import java.time.Duration; public class CompleteServer { public static void main(String[] args) throws Exception { // All public classes available via imports HTTPServer server = new HTTPServer() .withHandler((request, response) -> { HTTPMethod method = request.getMethod(); String path = request.getPath(); if (method.is("POST")) { Map> params = request.getParameters(); List files = request.getFiles(); } Cookie cookie = new Cookie("id", "123"); cookie.setSameSite(Cookie.SameSite.Strict); response.addCookie(cookie); response.setStatus(Status.OK); }) .withListener(new HTTPListenerConfiguration(8080)) .withLoggerFactory(new SystemOutLoggerFactory()) .withCompressByDefault(true); server.start(); } } ``` -------------------------------- ### HTTP Server Configuration Example Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/08-logging-and-instrumentation.md A comprehensive example showing how to configure the HTTP server with a file logger, a thread-safe counting instrumenter, and a basic request handler. It also demonstrates starting the server and accessing metrics afterwards. ```java // Use file logging LoggerFactory loggerFactory = new FileLoggerFactory("./logs", "http-server", 10 * 1024 * 1024, 10); // Track metrics ThreadSafeCountingInstrumenter counter = new ThreadSafeCountingInstrumenter(); HTTPServerConfiguration config = new HTTPServerConfiguration() .withHandler((request, response) -> { response.setStatus(200); response.getWriter().write("OK"); }) .withListener(new HTTPListenerConfiguration(8080)) .withLoggerFactory(loggerFactory) .withInstrumenter(counter); HTTPServer server = new HTTPServer().withConfiguration(config); server.start(); // Later: check metrics System.out.println("Total requests: " + counter.getTotalCount()); System.out.println("200 responses: " + counter.getCount(200)); System.out.println("404 responses: " + counter.getCount(404)); ``` -------------------------------- ### start() Method Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/01-httpserver.md Starts all configured HTTP listeners, initializing the server and its request handling mechanisms. It returns the server instance for chaining. ```APIDOC ## start() ### Description Starts all configured HTTP listeners. The method initializes the logger, sets up the HTTP context, and starts a thread for each configured listener. If the server is already started, this method returns immediately without re-starting. ### Method ```java public HTTPServer start() ``` ### Returns `HTTPServer` - Returns this instance for method chaining ### Throws | Error Type | Condition | |-----------|-----------| | Exception | If any listener fails to start; cleanup is performed for listeners that did start | ### Example ```java HTTPServer server = new HTTPServer() .withHandler((req, res) -> res.setStatus(200)) .withListener(new HTTPListenerConfiguration(8080)); server.start(); ``` ``` -------------------------------- ### Setup HTTPS Server with TLS Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/00-API-OVERVIEW.md Configure and start an HTTPS server using TLS certificates and keys. Ensure the certificate and key files are accessible. ```java String cert = Files.readString(Paths.get("cert.pem")); String key = Files.readString(Paths.get("key.pem")); HTTPListenerConfiguration listener = new HTTPListenerConfiguration(8443, cert, key); HTTPServer server = new HTTPServer() .withListener(listener) .start(); ``` -------------------------------- ### Install wrk Source: https://github.com/fusionauth/java-http/blob/main/docs/plans/load-testing-spec.md Install the wrk benchmark tool. Use 'brew install wrk' on macOS or 'apt install wrk' on Linux. ```bash brew install wrk ``` ```bash apt install wrk ``` -------------------------------- ### HTTPServer Configuration Example Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/04-configuration.md A comprehensive example demonstrating how to configure an HTTPServer with various settings including handlers, listeners, context path, timeouts, request sizes, and throughput. ```java HTTPServerConfiguration config = new HTTPServerConfiguration() .withHandler((request, response) -> { response.setStatus(200); response.setContentType("application/json"); response.getWriter().write("{\"status\": \"ok\"}"); }) .withListener(new HTTPListenerConfiguration(8080)) .withListener(new HTTPListenerConfiguration(8443, cert, key)) .withContextPath("/api") .withCompressByDefault(true) .withShutdownDuration(Duration.ofSeconds(10)) .withInitialReadTimeout(Duration.ofSeconds(5)) .withKeepAliveTimeoutDuration(Duration.ofSeconds(30)) .withProcessingTimeoutDuration(Duration.ofSeconds(30)) .withMaxRequestBodySize(Map.of( "*", 128 * 1024 * 1024, "application/json", 50 * 1024 * 1024 )) .withMinimumReadThroughput(16 * 1024) .withMinimumWriteThroughput(16 * 1024) .withRequestBufferSize(32 * 1024) .withResponseBufferSize(128 * 1024); HTTPServer server = new HTTPServer().withConfiguration(config).start(); ``` -------------------------------- ### Start a Server Manually Source: https://github.com/fusionauth/java-http/blob/main/load-tests/README.md Start a specific server manually after building it. Navigate to the build distribution directory and execute './start.sh'. ```bash cd load-tests//build/dist && ./start.sh ``` -------------------------------- ### Start HTTPServer and Configure Handler/Listener Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/01-httpserver.md Starts the HTTP server, initializing listeners and handlers. Use this to begin processing incoming requests. The server can be configured with a handler and listener before starting. ```java public HTTPServer start() ``` ```java HTTPServer server = new HTTPServer() .withHandler((req, res) -> res.setStatus(200)) .withListener(new HTTPListenerConfiguration(8080)); server.start(); ``` -------------------------------- ### Start a Basic HTTP Server Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/README.md This snippet demonstrates how to start a simple HTTP server with a "Hello World" handler and a listener on port 8080. It utilizes the HTTPServer and HTTPListenerConfiguration classes. ```java HTTPServer server = new HTTPServer() .withHandler((request, response) -> { response.setStatus(200); response.getWriter().write("Hello World"); }) .withListener(new HTTPListenerConfiguration(8080)) .start(); ``` -------------------------------- ### Example HTTP Handler Implementation Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/03-httpresponse.md A comprehensive example demonstrating how to set status, content type, headers, cookies, send redirects, and write to the response body within an HTTP handler. ```java HTTPHandler handler = (request, response) -> { // Set status and content type response.setStatus(200); response.setContentType("application/json; charset=UTF-8"); // Add headers response.setHeader("X-Custom-Header", "value"); response.addHeader("Set-Cookie", "sessionId=abc123; Path=/"); // Add a cookie Cookie cookie = new Cookie("theme", "dark"); cookie.setPath("/"); cookie.setMaxAge(86400L); // 1 day response.addCookie(cookie); // Send redirect if (request.getParameter("old") != null) { response.sendRedirect("/new"); return; } // Write response body response.setCompress(true); try (Writer writer = response.getWriter()) { writer.write("{\"status\": \"ok\"}"); } }; ``` -------------------------------- ### Cookie Usage Example Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/06-cookies-and-types.md Demonstrates how to get, set, and delete cookies using the Cookie class and the HTTP request/response objects. ```APIDOC ## Cookie Usage Example This code snippet illustrates the usage of the `Cookie` class for managing cookies within an HTTP request and response. ### Code Example ```java HTTPHandler handler = (request, response) -> { // Get request cookies Cookie sessionCookie = request.getCookie("sessionId"); if (sessionCookie != null) { String sessionId = sessionCookie.getValue(); } // Set response cookie Cookie newSession = new Cookie("sessionId", "new-id-123"); newSession.setPath("/"); newSession.setDomain(".example.com"); newSession.setSecure(true); // HTTPS only newSession.setHttpOnly(true); // No JavaScript access newSession.setMaxAge(86400L); // 1 day newSession.setSameSite(Cookie.SameSite.Strict); response.addCookie(newSession); // Delete cookie Cookie delete = new Cookie("oldSessionId", ""); delete.setPath("/"); delete.setMaxAge(0L); response.addCookie(delete); response.setStatus(200); }; ``` ``` -------------------------------- ### Multipart Stream Processing Example Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/09-advanced-io.md An example demonstrating how to extract the boundary from the Content-Type header and use MultipartStreamProcessor to parse parameters and files from an input stream. ```java String contentType = request.getHeader("Content-Type"); String boundary = extractBoundary(contentType); Map> params = new HashMap<>(); List files = new ArrayList<>(); MultipartStreamProcessor processor = new MultipartStreamProcessor(); processor.process(request.getInputStream(), params, files, boundary.getBytes()); // params and files are now populated ``` -------------------------------- ### Response Compression Example Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/09-advanced-io.md Example showing how to conditionally enable response compression based on the client's 'Accept-Encoding' header. Sets content type and writes JSON data. ```java HTTPHandler handler = (request, response) -> { List accepts = request.getHeaders("Accept-Encoding"); boolean clientSupportsGzip = accepts != null && accepts.stream() .anyMatch(e -> e.contains("gzip")); response.setCompress(clientSupportsGzip); response.setContentType("application/json"); response.getWriter().write("{\"data\": \"...large content...\"}"); }; ``` -------------------------------- ### Run Benchmarks with Custom Options Source: https://github.com/fusionauth/java-http/blob/main/load-tests/README.md Execute benchmarks with specified scenarios and duration. This example runs the 'hello' scenario for 10 seconds. ```bash ./run-benchmarks.sh --scenarios hello --duration 10s ``` -------------------------------- ### Get HTTPServer Context Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/01-httpserver.md Retrieves the HTTP context after the server has started. The context provides access to server-level configurations like the base directory. ```java public HTTPContext getContext() ``` ```java server.start(); HTTPContext context = server.getContext(); if (context != null) { Path baseDir = context.getBaseDir(); } ``` -------------------------------- ### Configure HTTP Server Options Source: https://github.com/fusionauth/java-http/blob/main/README.md This example illustrates setting various server options, such as the shutdown duration, alongside the handler and listener configuration. ```java import java.time.Duration; import io.fusionauth.http.server.HTTPListenerConfiguration; import io.fusionauth.http.server.HTTPServer; import io.fusionauth.http.server.HTTPHandler; public class Example { public static void main(String... args) { HTTPHandler handler = (req, res) -> { // Handler code goes here }; HTTPServer server = new HTTPServer().withHandler(handler) .withShutdownDuration(Duration.ofSeconds(10L)) .withListener(new HTTPListenerConfiguration(4242)); server.start(); // Use server server.close(); } } ``` -------------------------------- ### Example of creating and formatting a cookie for a request Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/06-cookies-and-types.md Demonstrates creating a simple cookie and converting it to the format used in HTTP request headers. ```java Cookie cookie = new Cookie("sessionId", "abc123"); String header = cookie.toRequestHeader(); // "sessionId=abc123" ``` -------------------------------- ### Logger Info Method Example Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/08-logging-and-instrumentation.md Demonstrates how to log informational messages using the info method with and without format arguments. ```java logger.info("HTTP server listening on port [{} ]", 8080); logger.info("Request handler completed successfully"); ``` -------------------------------- ### ChunkedOutputStream Example Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/09-advanced-io.md Demonstrates how to use ChunkedOutputStream to stream a large response by writing data in chunks. ```APIDOC ## ChunkedOutputStream Example ### Description Encodes data into chunked format as it writes. Useful for responses with unknown content length. ### Example: Streaming Large Response ```java HTTPHandler handler = (request, response) -> { response.setStatus(200); response.setContentType("text/plain"); response.addHeader("Transfer-Encoding", "chunked"); OutputStream out = response.getOutputStream(); // Write data in chunks for (int i = 0; i < 1000; i++) { out.write(("Chunk " + i + "\n").getBytes()); out.flush(); // Send chunk to client } out.close(); // Send final zero-length chunk }; ``` ``` -------------------------------- ### Example of creating and formatting a cookie for a response Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/06-cookies-and-types.md Shows how to set various attributes on a cookie and format it for use in an HTTP response 'Set-Cookie' header. ```java Cookie cookie = new Cookie("sessionId", "abc123"); cookie.setPath("/"); cookie.setSecure(true); cookie.setHttpOnly(true); cookie.setMaxAge(86400L); String header = cookie.toResponseHeader(); // "sessionId=abc123; Path=/; Secure; HttpOnly; Max-Age=86400" ``` -------------------------------- ### HTTP Content Type Usage Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/10-utilities.md Examples demonstrating how to set the Content-Type for HTTP responses and check the Content-Type of incoming requests. ```java response.setContentType(ContentTypes.JSON); response.setContentType(ContentTypes.HTML + "; charset=UTF-8"); if (request.getContentType().equals(ContentTypes.Form)) { Map> formData = request.getFormData(); } ``` -------------------------------- ### Instrumenter Interface Methods Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/08-logging-and-instrumentation.md The Instrumenter interface provides methods to start and end request processing for metric tracking. The start method returns a context ID. ```java long start(HTTPRequest request, HTTPResponse response) void end(HTTPRequest request, HTTPResponse response, long context) ``` -------------------------------- ### HTTP Server with Try-Resource Block Source: https://github.com/fusionauth/java-http/blob/main/README.md This example shows how to use a try-resource block for the HTTPServer, ensuring it is automatically shut down when the block is exited. ```java import io.fusionauth.http.server.HTTPListenerConfiguration; import io.fusionauth.http.server.HTTPServer; import io.fusionauth.http.server.HTTPHandler; public class Example { public static void main(String... args) { HTTPHandler handler = (req, res) -> { // Handler code goes here }; try (HTTPServer server = new HTTPServer().withHandler(handler) .withListener(new HTTPListenerConfiguration(4242))) { server.start(); // When this block exits, the server will be shutdown } } } ``` -------------------------------- ### Configure HTTPServer with TLS Certificate Source: https://github.com/fusionauth/java-http/blob/main/README.md Load the generated certificate and private key into the HTTPServer configuration. This example assumes the certificate and key are stored in the user's home directory. ```java import java.nio.file.Files; import java.nio.file.Paths; import java.time.Duration; import io.fusionauth.http.server.HTTPHandler; import io.fusionauth.http.server.HTTPServer; public class Example { private static String certificate; private static String privateKey; public static void main(String[] args) throws Exception { String homeDir = System.getProperty("user.home"); certificate = Files.readString(Paths.get(homeDir + "/dev/certificates/example.org.pem")); privateKey = Files.readString(Paths.get(homeDir + "/dev/certificates/example.org.key")); HTTPHandler handler = (req, res) -> { // Handler code goes here }; HTTPServer server = new HTTPServer().withHandler(handler) .withListener(new HTTPListenerConfiguration(4242, certificate, privateKey)); // Use server server.close(); } } ``` -------------------------------- ### getContext() Method Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/01-httpserver.md Retrieves the HTTP context associated with the server, which holds server-level configurations. This is available only after the server has been started. ```APIDOC ## getContext() ### Description Returns the HTTP context, which contains server-level configuration like the base directory. Returns null if the server has not been started yet. ### Method ```java public HTTPContext getContext() ``` ### Returns `HTTPContext` or null - The HTTP context if the server has been started, null otherwise ### Example ```java server.start(); HTTPContext context = server.getContext(); if (context != null) { Path baseDir = context.getBaseDir(); } ``` ``` -------------------------------- ### Get All Locales Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/02-httprequest.md Retrieves all locales from the Accept-Language header in order of preference. ```java public List getLocales() ``` -------------------------------- ### HTTP Request Handling Example Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/02-httprequest.md Demonstrates how to access various parts of an HTTP request within an HTTPHandler, including method, path, headers, parameters, form data, files, and attributes. Also shows how to set the response status. ```java HTTPHandler handler = (request, response) -> { // Get method and path HTTPMethod method = request.getMethod(); String path = request.getPath(); // Get headers String userAgent = request.getHeader("User-Agent"); // Get URL parameters String id = request.getURLParameter("id"); // Get form data (if POST) if (request.getMethod().is("POST")) { Map> formData = request.getFormData(); String name = formData.get("name").stream().findFirst().orElse(null); } // Get files from multipart upload List files = request.getFiles(); for (FileInfo file : files) { Path uploadedFile = file.getFile(); } // Get and set attributes request.setAttribute("userId", 123); Integer userId = (Integer) request.getAttribute("userId"); response.setStatus(200); }; ``` -------------------------------- ### Generate Self-Signed Certificate with mkcert Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/05-listeners-and-tls.md Installs mkcert and generates a self-signed certificate and private key for local development. Adds the certificate's domain to the system's hosts file for easy access. ```bash # Install mkcert brew install mkcert # macOS # or: sudo apt install mkcert # Linux # Create certificate directory mkdir -p ~/dev/certificates # Generate self-signed certificate mkcert -cert-file ~/dev/certificates/example.org.pem \ -key-file ~/dev/certificates/example.org.key \ example.org # Add to /etc/hosts sudo echo "127.0.0.1 example.org" >> /etc/hosts ``` -------------------------------- ### Get Acceptable Encodings Source: https://github.com/fusionauth/java-http/blob/main/_autodocs/02-httprequest.md Retrieves a list of encodings the client accepts, as specified in the Accept-Encoding header. ```java public List getAcceptEncodings() ``` -------------------------------- ### Run Benchmarks Script Options Source: https://github.com/fusionauth/java-http/blob/main/docs/plans/load-testing-spec.md The main orchestrator script 'run-benchmarks.sh' builds and starts servers, runs benchmarks, stops servers, and aggregates results. It accepts various options to customize the benchmark execution. ```bash ./run-benchmarks.sh [OPTIONS] Options: --servers Comma-separated server list (default: all) --scenarios Comma-separated scenario list (default: all) --tool Benchmark tool: wrk, fusionauth, or both (default: wrk) --label Label for the results file --output Output directory (default: load-tests/results/) --duration