import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.net.InetSocketAddress;
import java.util.Scanner;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class SmallHttpServer {

    public static void main(String[] args) throws Exception {
        int POOL_SIZE = 1;
        String HOST = args.length < 1 ? "127.0.0.1" : args[0];
        int PORT = args.length < 2 ? 8080 : Integer.valueOf(args[1]);

        // Setup a minimum thread pool to rise RejectExecutionException in httpserver
        ThreadPoolExecutor miniHttpPoolExecutor
                = new ThreadPoolExecutor(POOL_SIZE, POOL_SIZE, 0L, TimeUnit.MICROSECONDS,
                        new LinkedBlockingQueue<>(1), (Runnable r) -> {
                            return new Thread(r);
                        });
        HttpServer httpServer = HttpServer.create(new InetSocketAddress(HOST, PORT), 0);
        httpServer.setExecutor(miniHttpPoolExecutor);

        HttpHandler res200handler = (HttpExchange exchange) -> {
            exchange.sendResponseHeaders(200, 0);
            exchange.close();
        };
        httpServer.createContext("/", res200handler);

        httpServer.start();
        // Wait stdin to exit
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            System.out.println(in.nextLine());
        }
        httpServer.stop(0);
        miniHttpPoolExecutor.shutdownNow();
    }
}
