Context in Squirrel

Here’s the translation of the Go code to Java, with explanations in Markdown format suitable for Hugo:

Our example demonstrates the usage of Context for controlling cancellation in an HTTP server. In Java, we can achieve similar functionality using CompletableFuture and thread interruption. Here’s the full source code:

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class ContextExample {
    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(8090), 0);
        server.createContext("/hello", new HelloHandler());
        server.start();
        System.out.println("Server started on port 8090");
    }

    static class HelloHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            System.out.println("server: hello handler started");

            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                try {
                    TimeUnit.SECONDS.sleep(10);
                    String response = "hello\n";
                    exchange.sendResponseHeaders(200, response.length());
                    try (OutputStream os = exchange.getResponseBody()) {
                        os.write(response.getBytes());
                    }
                } catch (InterruptedException | IOException e) {
                    System.out.println("server: " + e.getMessage());
                    try {
                        exchange.sendResponseHeaders(500, 0);
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                }
            });

            future.exceptionally(throwable -> {
                System.out.println("server: " + throwable.getMessage());
                try {
                    exchange.sendResponseHeaders(500, 0);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            });

            exchange.getResponseBody().close();
            System.out.println("server: hello handler ended");
        }
    }
}

In this Java version, we use HttpServer to create a simple HTTP server. The HelloHandler class implements the HttpHandler interface to handle requests to the “/hello” endpoint.

Instead of using context.Context, we use CompletableFuture to manage the asynchronous operation. The runAsync method simulates work that the server is doing.

We use TimeUnit.SECONDS.sleep(10) to wait for 10 seconds before sending a reply to the client. This simulates some work the server is doing.

Error handling is done using the exceptionally method of CompletableFuture. If an error occurs during the execution of the async task, it will be caught and handled here.

To run the server:

$ javac ContextExample.java
$ java ContextExample

To simulate a client request and cancellation:

$ curl localhost:8090/hello
server: hello handler started
^C
server: hello handler ended

In this example, pressing Ctrl+C will interrupt the client request, but the server will continue running. To fully replicate the behavior of the Go example, you would need to implement a way to propagate the cancellation to the server-side operation, which is more complex in Java and typically involves custom implementations or third-party libraries.