Interface RouteCommand

Functional Interface:
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

@FunctionalInterface public interface RouteCommand
Functional interface representing a command to handle HTTP requests for a specific route.

This interface provides a functional abstraction for route handlers, allowing them to be defined as lambda expressions, method references, or traditional implementations. It follows the Command pattern, encapsulating the request processing logic for individual routes.

As a functional interface, RouteCommand can be implemented using various Java 8+ constructs:

  • Lambda expressions: (request) -> new HTTPResponse(200, "OK")
  • Method references: MyClass::handleRequest
  • Anonymous classes: Traditional implementation approach
  • Named classes: Full-featured implementations with additional state

The single abstract method run(HTTPRequest) processes an incoming HTTP request and produces an appropriate HTTP response. Implementations should:

  • Parse and validate the request data
  • Execute the business logic for the route
  • Construct and return an appropriate HTTPResponse
  • Throw exceptions for error conditions (handled by the framework)

Usage examples:

// Lambda expression
RouteCommand helloRoute = (request) -> {
    HTTPResponse response = new HTTPResponse(200, "OK");
    response.setBody("Hello, World!".getBytes(), "text/plain");
    return response;
};

// Method reference
RouteCommand userRoute = UserHandler::handleUserRequest;

// Registration with router
router.register("/api/hello", helloRoute);

Thread-safety: Implementations should be stateless or thread-safe, as the same RouteCommand instance may be invoked concurrently by multiple request processing threads.

See Also:
  • Method Summary

    Modifier and Type
    Method
    Description
    run(HTTPRequest request)
    Executes the route command to process an HTTP request and generate a response.
  • Method Details

    • run

      HTTPResponse run(HTTPRequest request) throws Exception
      Executes the route command to process an HTTP request and generate a response.

      This method is invoked by the routing framework when an incoming HTTP request matches the route associated with this command. Implementations should process the request according to their specific business logic and return an appropriate HTTP response.

      The method should handle various aspects of request processing:

      • Request validation: Verify request method, headers, and body format
      • Parameter extraction: Parse path parameters, query strings, and body data
      • Business logic: Execute the core functionality for this route
      • Response construction: Create an HTTPResponse with appropriate status, headers, and body content

      Error handling: Rather than catching exceptions internally, implementations should typically allow exceptions to propagate to the framework, which will convert them to appropriate HTTP error responses via HTTPErrorHandler. Common exceptions:

      • BadRequestException - Invalid or malformed request data
      • NotFoundException - Requested resource doesn't exist
      • InternalServerErrorException - Unexpected server errors

      Example implementation:

      public HTTPResponse run(HTTPRequest request) throws Exception {
          // Validate request method
          if (request.getMethod() != HTTPMethode.GET) {
              throw new MethodNotAllowedException("Only GET is supported");
          }
      
          // Process request
          String data = fetchData();
      
          // Build response
          HTTPResponse response = new HTTPResponse(200, "OK");
          response.setBody(data.getBytes(), "application/json");
          return response;
      }
      
      Parameters:
      request - The HTTP request to process. Contains method, path, headers, and body. Must not be null.
      Returns:
      An HTTPResponse object containing the status code, headers, and body to send to the client. Must not be null.
      Throws:
      Exception - If an error occurs during request processing. The framework will catch these exceptions and convert them to appropriate HTTP error responses. Specific exception types (BadRequestException, NotFoundException, etc.) will be mapped to their corresponding HTTP status codes.