From ce26271629df5d36bb2fb352233bf4cdb135f4de Mon Sep 17 00:00:00 2001 From: Sam Gardner Date: Tue, 13 Feb 2024 14:27:10 +0000 Subject: [PATCH] BAEL-7522 Add code for Java 18 simple web server --- .../baeldung/simple_web_server/WebServer.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 core-java-modules/core-java-18/src/main/java/com/baeldung/simple_web_server/WebServer.java diff --git a/core-java-modules/core-java-18/src/main/java/com/baeldung/simple_web_server/WebServer.java b/core-java-modules/core-java-18/src/main/java/com/baeldung/simple_web_server/WebServer.java new file mode 100644 index 0000000000..db36477fdb --- /dev/null +++ b/core-java-modules/core-java-18/src/main/java/com/baeldung/simple_web_server/WebServer.java @@ -0,0 +1,59 @@ +package com.baeldung.simple_web_server; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.function.Predicate; + +import com.sun.net.httpserver.Filter; +import com.sun.net.httpserver.Headers; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpHandlers; +import com.sun.net.httpserver.HttpServer; +import com.sun.net.httpserver.Request; +import com.sun.net.httpserver.SimpleFileServer; + +public class WebServer { + + private final InetSocketAddress address = new InetSocketAddress(8080); + private final Path path = Path.of("/"); + + public static void main(String[] args) { + WebServer webServer = new WebServer(); + HttpServer server = webServer.createWithHandler_401Response(); + server.start(); + } + + private HttpServer createBasic() { + return SimpleFileServer.createFileServer(address, path, SimpleFileServer.OutputLevel.VERBOSE); + } + + private HttpServer createWithHandler() throws IOException { + HttpServer server = SimpleFileServer.createFileServer(address, path, SimpleFileServer.OutputLevel.VERBOSE); + HttpHandler handler = SimpleFileServer.createFileHandler(Path.of("/Users")); + server.createContext("/test", handler); + return server; + } + + private HttpServer createWithHandler_401Response() { + Predicate findAllowedPath = r -> r.getRequestURI() + .getPath() + .equals("/test/allowed"); + + HttpHandler allowedResponse = HttpHandlers.of(200, Headers.of("Allow", "GET"), "Welcome"); + HttpHandler deniedResponse = HttpHandlers.of(401, Headers.of("Deny", "GET"), "Denied"); + + HttpHandler handler = HttpHandlers.handleOrElse(findAllowedPath, allowedResponse, deniedResponse); + + HttpServer server = SimpleFileServer.createFileServer(address, path, SimpleFileServer.OutputLevel.VERBOSE); + server.createContext("/test", handler); + return server; + } + + private HttpServer createWithFilter() throws IOException { + Filter filter = SimpleFileServer.createOutputFilter(System.out, SimpleFileServer.OutputLevel.INFO); + HttpHandler handler = SimpleFileServer.createFileHandler(Path.of("/Users")); + return HttpServer.create(new InetSocketAddress(8080), 10, "/test", handler, filter); + } + +}