101 lines
2.2 KiB
Java
101 lines
2.2 KiB
Java
/*
|
|
*/
|
|
package kebaagent;
|
|
|
|
import com.sun.net.httpserver.Headers;
|
|
import com.sun.net.httpserver.HttpExchange;
|
|
import com.sun.net.httpserver.HttpHandler;
|
|
import java.io.IOException;
|
|
import java.io.OutputStream;
|
|
import java.util.ArrayList;
|
|
import java.util.HashMap;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
|
|
|
|
/**
|
|
*
|
|
* @author holz
|
|
*/
|
|
class JsonHandler implements HttpHandler
|
|
{
|
|
private final KebaAgent agent;
|
|
|
|
JsonHandler(KebaAgent agent)
|
|
{
|
|
this.agent = agent;
|
|
}
|
|
|
|
|
|
@Override
|
|
public void handle(HttpExchange httpExchange) throws IOException
|
|
{
|
|
// nur GET
|
|
if (!"GET".equals(httpExchange.getRequestMethod()))
|
|
{
|
|
return;
|
|
}
|
|
|
|
// Parameter ermitteln: path ist Teil hinter Domain: "/t/allowed?..."
|
|
String uri = httpExchange.getRequestURI().toString();
|
|
Map<String, String> params = getParams(uri);
|
|
|
|
String callData = agent.getDataAsJson(params);
|
|
// response
|
|
OutputStream outputStream = httpExchange.getResponseBody();
|
|
// StringBuilder sb = new StringBuilder();
|
|
// sb
|
|
// .append("<html>")
|
|
// .append("<body>")
|
|
// .append("<h1>")
|
|
// .append("Hello ")
|
|
// .append(callData)
|
|
// .append("</h1>")
|
|
// .append("</body>")
|
|
// .append("</html>");
|
|
try
|
|
{
|
|
// String htmlResponse = sb.toString();
|
|
String htmlResponse = callData;
|
|
|
|
// jaho: Header erweitern
|
|
Headers responseHeaders = httpExchange.getResponseHeaders();
|
|
responseHeaders.set("Content-Type", "application/json");
|
|
|
|
// 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();
|
|
}
|
|
}
|
|
|
|
|
|
|
|
private Map<String, String> getParams(String uri)
|
|
{
|
|
// split bei ?
|
|
List<String> l = new ArrayList<>(List.of(uri.split("\\?")));
|
|
final Map<String, String> paramsMap = new HashMap();
|
|
|
|
l.removeFirst();
|
|
l.forEach(xparam ->
|
|
{
|
|
// key/value extrahieren
|
|
String[] split = xparam.split("=");
|
|
String k = split[0];
|
|
String v = split.length > 1 ? split[1] : "";
|
|
paramsMap.put(k, v);
|
|
});
|
|
|
|
System.out.println("");
|
|
return paramsMap;
|
|
}
|
|
|
|
}
|