Commit 64ede98e authored by Pablo Gamito's avatar Pablo Gamito
Browse files

Added JSON API request to web server

parent 2259f800
Pipeline #65776 passed with stages
in 2 minutes and 55 seconds
......@@ -39,17 +39,21 @@ public class WebServer {
String answer = queryProcessor.process(query);
switch (format) {
case "md":
page = new MDResultPage(query, answer);
break;
case "md":
page = new MDResultPage(query, answer);
break;
case "pdf":
page = new PDFResultPage(query, answer);
break;
case "pdf":
page = new PDFResultPage(query, answer);
break;
default:
page = new HTMLResultPage(query, answer, backgroundColour);
break;
case "json":
page = new APIResultPage(query, answer);
break;
default:
page = new HTMLResultPage(query, answer, backgroundColour);
break;
}
}
......
package ic.doc.web;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class APIResultPage implements Page {
private final String query;
private final String answer;
public APIResultPage(String query, String answer) {
this.query = query;
this.answer = answer;
}
@Override
public void writeTo(HttpServletResponse resp) throws IOException {
resp.setContentType("application/json");
PrintWriter writer = resp.getWriter();
StringBuilder sb = new StringBuilder();
boolean success = !(answer == null || answer.isEmpty());
sb.append("{");
sb.append("\"success\": \"").append(success).append("\"");
if (success) {
sb.append(", ");
sb.append("\"result\":");
sb.append("{").append("\"query\": \"").append(query).append("\", ").append("\"answer\": \"")
.append(answer.replace("\n", "").replace("\r", "")).append("\"}");
}
sb.append("}");
writer.println(sb.toString());
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment