Skip to content

Instantly share code, notes, and snippets.

@krisrice
Created February 16, 2017 20:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save krisrice/c0f0e9e9f6eccb82e30bd787064b6fad to your computer and use it in GitHub Desktop.
Save krisrice/c0f0e9e9f6eccb82e30bd787064b6fad to your computer and use it in GitHub Desktop.
var Thread = java.lang.Thread;
var ServerSocket = java.net.ServerSocket;
var PrintWriter = java.io.PrintWriter;
var InputStreamReader = java.io.InputStreamReader;
var BufferedReader = java.io.BufferedReader;
var FileInputStream = java.io.FileInputStream;
var ByteArray = Java.type("byte[]");
var PORT = 8080;
var CRLF = "\r\n";
var FOUROHFOUR = ""+
"<HTML> "+
" <HEAD> "+
" <TITLE>404 Not Found</TITLE> "+
" </HEAD> "+
" <BODY> "+
" <P>404 Not Found</P> "+
" </BODY> "+
"</HTML> "
var serverSocket = new ServerSocket(PORT);
while (true) {
var socket = serverSocket.accept();
try {
var thread = new Thread(function() { httpRequestHandler(socket); });
thread.start();
Thread.sleep(100);
} catch (e) {
print(e);
}
}
function httpRequestHandler(socket) {
var out = socket.getOutputStream();
var output = new PrintWriter(out);
var inReader = new InputStreamReader(socket.getInputStream(), 'utf-8');
var bufReader = new BufferedReader(inReader);
var lines = readLines(bufReader);
if (lines.length > 0) {
var header = lines[0].split(/\b\s+/);
if (header[0] == "GET") {
var URI = header[1].split(/\?/);
var table = URI[0].substring(1);
try {
sendTable(output, out, table);
} catch (e) {
System.out.println( e + "\n")
respond(output, "HTTP/1.0 404 Not Found", "text/html", FOUROHFOUR);
}
}
}
output.flush();
bufReader.close();
socket.close();
}
function respond(output, status, type, body) {
sendBytes(output, status + CRLF);
sendBytes(output, "Server: Simple SQLcl Nashorn HTTP Server" + CRLF);
sendBytes(output, "Content-type: ${type}" + CRLF);
sendBytes(output, "Content-Length: ${body.length}" + CRLF);
sendBytes(output, CRLF);
sendBytes(output, body);
}
function readLines(bufReader) {
var lines = [];
try {
var line;
while (line = bufReader.readLine()) {
lines.push(line);
}
} catch (e) {
}
return lines;
}
function sendBytes(output, line) {
output.write(String(line));
}
function sendTable(output, out, table) {
sendBytes(output, "HTTP/1.0 200 OK" + CRLF);
sendBytes(output, "Server: Simple Nashorn HTTP Server" + CRLF);
sendBytes(output, "Content-type: application/json" + CRLF);
sendBytes(output, CRLF);
output.flush();
var ObjectMapper = Java.type("com.fasterxml.jackson.databind.ObjectMapper")
var mapper = new ObjectMapper();
var ret = util.executeReturnListofList("select * from " + table,null);
var json = mapper.writeValueAsString(ret);
sendBytes(output,json);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment