I have developed a Java desktop application that can receive HTTP requests using the embedded NanoHTTPD web server from https://github.com/NanoHttpd/nanohttpd. Once an HTTP request is received, my application performs certain tasks and logs the activity to a text file. Currently, when a client accesses the webpage, they have to wait until the entire process is completed, including viewing the log file. I am looking for a way to update the client with the log data in real-time as it is being added to the local log file.
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Map;
import common.Logging;
import common.TextFiles;
import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.ServerRunner;
import fi.iki.elonen.SimpleWebServer;
public class TestServer extends NanoHTTPD {
static boolean isExecutingJob = false;
public TestServer() {
super(8080);
}
@Override public Response serve(IHTTPSession session) {
Method method = session.getMethod();
Map<String,String> params = session.getParms();
String uri = session.getUri();
System.out.println(method + " '" + uri + "' ");
String msg = "<html><style>h1 { color: green; background-color: black;}p { color: gray; background-color: black;}div { color: gray; background-color: black;}body { color: gray; background-color: black;}</style><body><h1>Remote Test Service</h1>";
Map<String, String> parms = session.getParms();
for(String paramKey:parms.keySet()){
String job=params.get(paramKey);
msg+="Status: "+(isExecutingJob?"Waiting in queue.":"Immediate run.");
if ("tcl".equalsIgnoreCase(paramKey)){
try {
//if another request is being executed, wait until finished
while(isExecutingJob){
Thread.sleep(3000);
}
isExecutingJob=true;
SomeJobClass.doSomeWork(job.split(" "));
isExecutingJob=false;
ArrayList<String> lines=TextFiles.load(Logging.getLogFile().toString());
for(String line: lines){
msg+="<p>"+line+"</p>";
}
} catch (Exception e) {
e.printStackTrace();
}
} else{
ArrayList<String> lines=TextFiles.load("some help.txt");
for(String line: lines){
msg+="<p>"+line+"</p>";
}
}
}
if (parms.isEmpty()){
ArrayList<String> lines=TextFiles.load("some help.txt");
for(String line: lines){
msg+="<p>"+line+"</p>";
}
}
msg += "</body></html>";
return new NanoHTTPD.Response(msg);
}
public static void main(String[] args) {
ServerRunner.run(TestServer.class);
}
}
I came across this code snippet at , but unfortunately, it didn't work for my situation.
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="jquery.logviewer.js"></script>
<script type="text/javascript">
jQuery(document).bind("ready", function() {
jQuery('#logcontent').logViewer({logUrl: 'log.html'});
});
</script>
</head>
<body>
Live log:<br/>
<textarea id="logcontent" autocomplete="off">