Commit 06ae44fa authored by Big Andy's avatar Big Andy
Browse files

Refactor for codestyle.

parent b7594dab
Pipeline #173252 passed with stages
in 4 minutes and 11 seconds
......@@ -4,6 +4,7 @@ import java.util.HashMap;
import java.util.Map;
public class Database {
private static Database instance;
private Map<String, String> queries;
......
......@@ -7,26 +7,26 @@ import java.util.Map;
public class QueryProcessor {
Map<String, String> dictionary = new HashMap<>();
Map<String, String> dictionary = new HashMap<>();
public String process(String query) {
// Splits request on comma
String[] queries = query.split(",");
Database database = Database.getQueries();
StringBuilder results = new StringBuilder();
public String process(String query) {
// Splits request on comma
String[] queries = query.split(",");
Database database = Database.getQueries();
StringBuilder results = new StringBuilder();
for (String q : queries) {
for (String qSplit : q.split(" ")) {
String result = database.getQuery(qSplit.toLowerCase());
if (result != null) {
results.append(result);
results.append(System.lineSeparator());
// Once first match is made, the rest of the information
// in a 'comma' chunk is considered irrelevant
break;
}
}
for (String q : queries) {
for (String qSplit : q.split(" ")) {
String result = database.getQuery(qSplit.toLowerCase());
if (result != null) {
results.append(result);
results.append(System.lineSeparator());
// Once first match is made, the rest of the information
// in a 'comma' chunk is considered irrelevant
break;
}
return results.toString();
}
}
return results.toString();
}
}
......@@ -14,36 +14,39 @@ import java.io.IOException;
public class WebServer {
public WebServer() throws Exception {
int port = Integer.parseInt(System.getenv("PORT"));
System.out.println("Creating server on port " + port);
Server server = new Server(port);
ServletHandler handler = new ServletHandler();
handler.addServletWithMapping(new ServletHolder(new Website()), "/*");
server.setHandler(handler);
server.start();
public WebServer() throws Exception {
int port = Integer.parseInt(System.getenv("PORT"));
System.out.println("Creating server on port " + port);
Server server = new Server(port);
ServletHandler handler = new ServletHandler();
handler.addServletWithMapping(new ServletHolder(new Website()), "/*");
server.setHandler(handler);
server.start();
}
static class Website extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String query = req.getParameter("q");
String format = req.getParameter("f");
if (query == null || format == null) {
new IndexPage().writeTo(resp);
} else if (format.equals("pdf")) {
new PDFResultPage(query, new QueryProcessor().process(query))
.writeTo(resp);
} else {
new HTMLResultPage(query, new QueryProcessor().process(query))
.writeTo(resp);
}
}
}
static class Website extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String query = req.getParameter("q");
String format = req.getParameter("f");
if (query == null || format == null) {
new IndexPage().writeTo(resp);
} else if (format.equals("pdf")) {
new PDFResultPage(query, new QueryProcessor().process(query)).writeTo(resp);
} else {
new HTMLResultPage(query, new QueryProcessor().process(query)).writeTo(resp);
}
}
}
public static void main(String[] args) throws Exception {
new WebServer();
}
public static void main(String[] args) throws Exception {
new WebServer();
}
}
......@@ -6,36 +6,36 @@ import java.io.PrintWriter;
public class HTMLResultPage implements Page {
private final String query;
private final String answer;
public HTMLResultPage(String query, String answer) {
this.query = query;
this.answer = answer;
private final String query;
private final String answer;
public HTMLResultPage(String query, String answer) {
this.query = query;
this.answer = answer;
}
public void writeTo(HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
// Header
writer.println("<html>");
writer.println("<head><title>" + query + "</title></head>");
writer.println("<body>");
// Content
if (answer == null || answer.isEmpty()) {
writer.println("<h1>Sorry</h1>");
writer.print("<p>Sorry, we didn't understand <em>" + query + "</em></p>");
} else {
writer.println("<h1>" + query + "</h1>");
writer.println("<p>" + answer.replace("\n", "<br>") + "</p>");
}
public void writeTo(HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
// Header
writer.println("<html>");
writer.println("<head><title>" + query + "</title></head>");
writer.println("<body>");
// Content
if (answer == null || answer.isEmpty()) {
writer.println("<h1>Sorry</h1>");
writer.print("<p>Sorry, we didn't understand <em>" + query + "</em></p>");
} else {
writer.println("<h1>" + query + "</h1>");
writer.println("<p>" + answer.replace("\n", "<br>") + "</p>");
}
writer.println("<p><a href=\"/\">Back to Search Page</a></p>");
// Footer
writer.println("</body>");
writer.println("</html>");
}
writer.println("<p><a href=\"/\">Back to Search Page</a></p>");
// Footer
writer.println("</body>");
writer.println("</html>");
}
}
......@@ -6,37 +6,37 @@ import java.io.PrintWriter;
public class IndexPage implements Page {
public void writeTo(HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
// Header
writer.println("<html>");
writer.println("<head><title>Welcome</title></head>");
writer.println("<body>");
// Content
writer.println(
"<h1>Welcome!!</h1>" +
"<p>Enter your query in the box below, and select " +
"your desired results format. <br>" +
"Make sure to comma separate multiple queries." +
"<form>" +
"<input type=\"text\" name=\"q\" /><br>" +
"<input type=\"radio\" name=\"f\" value=\"html\"/>" +
"<label for=\"html\"> HTML </label>" +
"<input type=\"radio\" name=\"f\" value=\"pdf\"/>" +
"<label for=\"pdf\"> PDF File </label>" +
"<br><br><input type=\"submit\">" +
"</form>" +
"</p>");
// Footer
writer.println("</body>");
writer.println("</html>");
}
public void writeTo(HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
// Header
writer.println("<html>");
writer.println("<head><title>Welcome</title></head>");
writer.println("<body>");
// Content
writer.println(
"<h1>Welcome!!</h1>" +
"<p>Enter your query in the box below, and select " +
"your desired results format. <br>" +
"Make sure to comma separate multiple queries." +
"<form>" +
"<input type=\"text\" name=\"q\" /><br>" +
"<input type=\"radio\" name=\"f\" value=\"html\"/>" +
"<label for=\"html\"> HTML </label>" +
"<input type=\"radio\" name=\"f\" value=\"pdf\"/>" +
"<label for=\"pdf\"> PDF File </label>" +
"<br><br><input type=\"submit\">" +
"</form>" +
"</p>");
// Footer
writer.println("</body>");
writer.println("</html>");
}
}
......@@ -9,54 +9,56 @@ import javax.servlet.http.HttpServletResponse;
public class PDFResultPage implements Page {
private final String query;
private final String answer;
private final String query;
private final String answer;
public PDFResultPage(String query, String answer) {
this.query = query;
this.answer = answer;
public PDFResultPage(String query, String answer) {
this.query = query;
this.answer = answer;
}
public void writeTo(HttpServletResponse resp) throws IOException {
resp.setContentType("application/pdf");
resp.setHeader("Content-Disposition", "attachment; filename=query.pdf");
// Create temporary markdown file (and delete on exit)
File markdownFile = File.createTempFile("simplewebapp-", ".md");
markdownFile.deleteOnExit();
// Populate markdown file
FileWriter fileWriter = new FileWriter(markdownFile, true);
if (answer == null || answer.isEmpty()) {
fileWriter.append("# Sorry\n");
fileWriter.append("Sorry, we didn't understand *")
.append(query).append("*\n");
} else {
fileWriter.append("# ").append(query).append("\n");
fileWriter.append(answer).append("\n");
}
public void writeTo(HttpServletResponse resp) throws IOException {
resp.setContentType("application/pdf");
resp.setHeader("Content-Disposition", "attachment; filename=query.pdf");
// Create temporary markdown file (and delete on exit)
File markdownFile = File.createTempFile("simplewebapp-", ".md");
markdownFile.deleteOnExit();
// Populate markdown file
FileWriter fileWriter = new FileWriter(markdownFile, true);
if (answer == null || answer.isEmpty()) {
fileWriter.append("# Sorry\n");
fileWriter.append("Sorry, we didn't understand *")
.append(query).append("*\n");
} else {
fileWriter.append("# ").append(query).append("\n");
fileWriter.append(answer).append("\n");
}
fileWriter.close();
// Create temporary (empty) PDF file (and delete on exit)
File pdfFile = File.createTempFile("simplewebapp-", ".pdf");
pdfFile.deleteOnExit();
ProcessBuilder processBuilder = new ProcessBuilder("pandoc", "-o",
pdfFile.getPath(), markdownFile.getPath()
);
try {
int ret = processBuilder.start().waitFor();
if (ret != 0) { throw new InterruptedException(); }
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(1);
}
// Create input stream from file and transfer to response output stream
InputStream in = new FileInputStream(pdfFile);
in.transferTo(resp.getOutputStream());
fileWriter.close();
// Create temporary (empty) PDF file (and delete on exit)
File pdfFile = File.createTempFile("simplewebapp-", ".pdf");
pdfFile.deleteOnExit();
ProcessBuilder processBuilder = new ProcessBuilder("pandoc", "-o",
pdfFile.getPath(), markdownFile.getPath()
);
try {
int ret = processBuilder.start().waitFor();
if (ret != 0) {
throw new InterruptedException();
}
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(1);
}
// Create input stream from file and transfer to response output stream
InputStream in = new FileInputStream(pdfFile);
in.transferTo(resp.getOutputStream());
}
}
......@@ -5,6 +5,6 @@ import java.io.IOException;
public interface Page {
void writeTo(HttpServletResponse resp) throws IOException;
void writeTo(HttpServletResponse resp) throws IOException;
}
......@@ -9,56 +9,61 @@ import static org.junit.Assert.assertThat;
public class QueryProcessorTest {
QueryProcessor queryProcessor = new QueryProcessor();
QueryProcessor queryProcessor = new QueryProcessor();
@Test
public void returnsEmptyStringIfCannotProcessQuery() throws Exception {
assertThat(queryProcessor.process("test"), is(""));
}
@Test
public void returnsEmptyStringIfCannotProcessQuery() throws Exception {
assertThat(queryProcessor.process("test"), is(""));
}
@Test
public void knowsAboutShakespeare() throws Exception {
assertThat(queryProcessor.process("Shakespeare"), containsString("playwright"));
}
@Test
public void knowsAboutShakespeare() throws Exception {
assertThat(queryProcessor.process("Shakespeare"),
containsString("playwright"));
}
@Test
public void knowsAboutAsimov() throws Exception {
assertThat(queryProcessor.process("Asimov"), containsString("science fiction"));
}
@Test
public void knowsAboutAsimov() throws Exception {
assertThat(queryProcessor.process("Asimov"),
containsString("science fiction"));
}
@Test
public void knowsAboutDarwin() throws Exception {
assertThat(queryProcessor.process("Darwin"), containsString("naturalist"));
}
@Test
public void knowsAboutDarwin() throws Exception {
assertThat(queryProcessor.process("Darwin"), containsString("naturalist"));
}
@Test
public void knowsAboutMandela() throws Exception {
assertThat(queryProcessor.process("Mandela"), containsString("political leader"));
}
@Test
public void knowsAboutMandela() throws Exception {
assertThat(queryProcessor.process("Mandela"),
containsString("political leader"));
}
@Test
public void isNotCaseSensitive() throws Exception {
assertThat(queryProcessor.process("shakespeare"), containsString("playwright"));
}
@Test
public void isNotCaseSensitive() throws Exception {
assertThat(queryProcessor.process("shakespeare"),
containsString("playwright"));
}
@Test
public void discardsIrrelevantInformation() throws Exception {
assertThat(queryProcessor.process("William Shakespeare England"),
containsString("playwright"));
}
@Test
public void discardsIrrelevantInformation() throws Exception {
assertThat(queryProcessor.process("William Shakespeare England"),
containsString("playwright"));
}
@Test
public void processesMultipleCommaSeparatedRequests() throws Exception {
String result = queryProcessor.process("Shakespeare, Mandela");
assertThat(result, containsString("playwright"));
assertThat(result, containsString("revolutionary"));
}
@Test
public void processesMultipleCommaSeparatedRequests() throws Exception {
String result = queryProcessor.process("Shakespeare, Mandela");
assertThat(result, containsString("playwright"));
assertThat(result, containsString("revolutionary"));
}
@Test
public void doesNotProcessesMultipleNonCommaSeparatedRequests() throws Exception {
String result = queryProcessor.process("Shakespeare Mandela");
assertThat(result, containsString("playwright"));
assertFalse(result.contains("revolutionary"));
}
@Test
public void doesNotProcessesMultipleNonCommaSeparatedRequests()
throws Exception {
String result = queryProcessor.process("Shakespeare Mandela");
assertThat(result, containsString("playwright"));
assertFalse(result.contains("revolutionary"));
}
}
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