Files
kebaAgent/src/kebaagent/Webserver.java
T
holz holz@unicon-gmbh.de 726936dada 2
2026-08-13 07:10:05 +02:00

230 lines
6.0 KiB
Java

/*
*/
package kebaagent;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
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 java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Optional;
import java.util.function.Predicate;
/**
*
* @author holz
*/
public class Webserver
{
private final int port;
private KebaAgent agent;
/**
* call start()
* @see #start()
* @param port
*/
public Webserver(int port)
{
this.port = port;
}
/**
* Start Webserver
* @param agent
* @throws IOException
*/
public void start(KebaAgent agent) throws IOException
{
this.agent = agent;
// Create an HttpServer instance on port
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
String defaultUri = "/keba";
Optional<String> pv = agent.getPropValue("webserver", "defaultUri");
if (pv.isPresent())
defaultUri = pv.get();
// Define a context that serves files from the current directory
// server.createContext("/", new com.sun.net.httpserver.HttpHandler()
// {
// @Override
// public void handle(com.sun.net.httpserver.HttpExchange exchange) throws IOException
// {
// // Handle requests here (simple file serving)
// System.out.println("recvd: " + exchange);
//// TODO: müsste jetzt die Response generieren. Wie genau, noch nicht nachvollzogen
//// ein komplexeres Bsp unter https://dzone.com/articles/simple-http-server-in-java
//// Daraus stammt die Klasse MyHttpHandler unten
// }
// });
// andere Variante für Handler am Bsp url http://localhost:8000/t/allowed oder http://localhost:8000/t<irgendwas anderes>
// Headers headers = new Headers();
// headers.set("Allow", "GET");
// headers.set("Content-Type", "text/plain");
//
// HttpHandler allowedResponse = HttpHandlers.of(200, headers, getBody()); // Statuscode, Headers, body
// Trivialhandler für einfache Antwort
HttpHandler deniedResponse = HttpHandlers.of(401, Headers.of("Deny", "GET"), "Denied");
JsonHandler allowedResponse = new JsonHandler(agent);
// welche URL ist erlaubt?
final String fDefUri = defaultUri;
Predicate<Request> findAllowedPath = r ->
// r.getRequestURI().getPath().equals("/t/allowed");
r.getRequestURI().getPath().equals(fDefUri);
HttpHandler handler = HttpHandlers.handleOrElse(findAllowedPath, allowedResponse, deniedResponse);
// context ist weiter oben angebunden (ab /t)
// server.createContext("/t", handler);
server.createContext(defaultUri, handler);
// ggf. 2. Handler für / bauen (Infoseite)
// mit MyHttpHandler, ziemlich buggy und unvollständig von https://dzone.com/articles/simple-http-server-in-java
// MyHttpHandler myHandler = new MyHttpHandler(agent);
// server.createContext("/m", myHandler);
// Start the server
server.start();
System.out.printf("Server started on port %d\n", port);
}
// private String getBody()
// {
// return "{ 'info': 'hello'}";
// }
//
private static class MyHttpHandler implements HttpHandler
{
private KebaAgent agent;
private MyHttpHandler(KebaAgent a)
{
agent = a;
}
/**
* zu implementierende Methode
* @param httpExchange
* @throws IOException
*/
@Override
public void handle(HttpExchange httpExchange) throws IOException
{
String requestParamValue = null;
System.out.println("MyHttpHandler.handle() httpExchange " + httpExchange);
String requestMethod = httpExchange.getRequestMethod();
System.out.println("MyHttpHandler.handle().getRequestMethod(): " + requestMethod);
if ("GET".equals(httpExchange.getRequestMethod()))
{
requestParamValue = handleGetRequest(httpExchange);
System.out.println("MyHttpHandler.handle() GET: requestParamValue = " + requestParamValue);
}
// TODO: nicht im Bsp.
// else if("POST".equals(httpExchange))
// {
// requestParamValue = handlePostRequest(httpExchange);
// }
handleResponse(httpExchange, requestParamValue);
}
/**
* hier hat der Autor Schwachsinn produziert
* @param httpExchange
* @return
*/
private String handleGetRequest(HttpExchange httpExchange)
{
String path = httpExchange.getRequestURI().toString();
try
{
// return path.split("\\?")[1]
return path.split("/")[1]
// .split("=")[1];
;
} catch (Exception e)
{
e.printStackTrace();
return e.getMessage();
}
}
private void handleResponse(HttpExchange httpExchange, String requestParamValue) throws IOException
{
System.out.println("MyHttpHandler.handleResponse ");
OutputStream outputStream = httpExchange.getResponseBody();
StringBuilder htmlBuilder = new StringBuilder();
htmlBuilder
.append("<html>")
.append("<body>")
.append("<h1>")
.append("Hello ")
.append(requestParamValue)
.append("</h1>")
.append("</body>")
.append("</html>");
// encode HTML content
// apache commons text + lang
try
{
// Schwachsinn: Anwendung auf den ganzen HTML-Code
// String htmlResponse = StringEscapeUtils.escapeHtml4(htmlBuilder.toString());
// So OK
String htmlResponse = htmlBuilder.toString();
// jaho: Header erweitern
Headers responseHeaders = httpExchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/plain");
// this line is a must (jaho: header senden)
httpExchange.sendResponseHeaders(200, htmlResponse.length());
outputStream.write(htmlResponse.getBytes());
outputStream.flush();
outputStream.close();
} catch (Throwable e)
{
e.printStackTrace();
}
}
} // MyHttpHandler
}