Commit e6314519 authored by clc4217's avatar clc4217
Browse files

Created a database, and reimplemented map with database

parent a0597fe8
......@@ -22,6 +22,11 @@
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.23.1</version>
</dependency>
</dependencies>
<build>
<plugins>
......
......@@ -3,27 +3,27 @@ package ic.doc;
import java.util.List;
public class Query {
private List<String> query;
private String answer;
private String query;
private String description;
private String imgURL;
private String wikiURL;
public Query(List<String> query, String answer, String imgURL, String wikiURL) {
public Query(String query, String description, String imgURL, String wikiURL) {
this.query = query;
this.answer = answer;
this.description = description;
if(query != null) {
this.answer = this.answer.concat("\n");
this.description = this.description.concat("\n");
}
this.imgURL = imgURL;
this.wikiURL = wikiURL;
}
public List<String> getQuery() {
public String getQuery() {
return query;
}
public String getAnswer() {
return answer;
public String getDescription() {
return description;
}
public String getImgURL() {
......
package ic.doc;
import ic.doc.web.DBReader;
import java.sql.ResultSet;
import java.util.*;
public class QueryProcessor {
/*Add a map mapping query to answer; change if to switch?;*/
private final Map<List<String>, String> queryMap = new HashMap<>();
private final List<Query> queriesMap = new ArrayList<>();
public QueryProcessor() {
/*this.queryMap*/
this.queriesMap.add(new Query(Arrays.asList("william", "shakespeare"),
"William Shakespeare (26 April 1564 - 23 April 1616) was an\n" +
"English poet, playwright, and actor, widely regarded as the greatest\n" +
"writer in the English language and the world's pre-eminent dramatist. \n",
"https://upload.wikimedia.org/wikipedia/commons/thumb/a/a2/Shakespeare.jpg/702px-Shakespeare.jpg",
"https://en.wikipedia.org/wiki/William_Shakespeare"));
this.queriesMap.add(new Query(Arrays.asList("isaac", "asimov"),
"Isaac Asimov (2 January 1920 - 6 April 1992) was an\n" +
"American writer and professor of Biochemistry, famous for\n" +
"his works of hard science fiction and popular science. \n",
"https://upload.wikimedia.org/wikipedia/commons/thumb/3/34/Isaac.Asimov01.jpg/800px-Isaac.Asimov01.jpg",
"https://en.wikipedia.org/wiki/Isaac_Asimov"));
this.queriesMap.add(new Query(Arrays.asList("alan", "mathison", "turing"),
"Alan Mathison Turing (23 June 1912 - 7 June 1954) was an English\n" +
"mathematician, computer scientist, logician, cryptanalyst, philosopher\n" +
"and theoretical biologist. Turing was highly influential in the\n" +
"development of theoretical computer science, providing a formalisation\n" +
"of the concepts of algorithm and computation with the Turing machine,\n" +
"which can be considered a model of a general-purpose computer. Turing\n" +
"is widely considered to be the father of theoretical computer science\n" +
"and artificial intelligence. Despite these accomplishments, he was\n" +
"never fully recognized in his home country during his lifetime due to\n" +
"his homosexuality, which was then a crime in the UK.",
"https://upload.wikimedia.org/wikipedia/commons/a/a1/Alan_Turing_Aged_16.jpg",
"https://en.wikipedia.org/wiki/Alan_Turing"));
this.queriesMap.add(new Query(Arrays.asList("augusta", "ada", "king", "lovelace"),
"Augusta Ada King, Countess of Lovelace (10 December 1815 - 27 November\n" +
"November 1852) was an English mathematician and writer, chiefly\n" +
"known for her work on Charles Babbage's proposed mechanical\n" +
"general-purpose computer, the Analytical Engine. She was the first to\n" +
"recognise that the machine had applications beyond pure calculation,\n" +
"and published the first algorithm intended to be carried out by such\n" +
"a machine. As a result, she is sometimes regarded as the first to\n" +
"recognise the full potential of a \"computing machine\" and the first\n" +
"computer programmer.",
"https://upload.wikimedia.org/wikipedia/commons/0/0b/Ada_Byron_daguerreotype_by_Antoine_Claudet_1843_or_1850.jpg",
"https://en.wikipedia.org/wiki/Ada_Lovelace"));
this.queriesMap.add(new Query(Arrays.asList("blaise", "pascal"),
"Blaise Pascal (19 June 1623 - 19 August 1662) was a French\n" +
"mathematician, physicist, inventor, writer and Catholic theologian.\n" +
"He was a child prodigy who was educated by his father, a tax collector\n" +
"in Rouen. Pascal's earliest work was in the natural and applied\n" +
"sciences where he made important contributions to the study of fluids,\n" +
"and clarified the concepts of pressure and vacuum by generalising the\n" +
"work of Evangelista Torricelli. Pascal also wrote in defence of the\n" +
"scientific method.",
"https://upload.wikimedia.org/wikipedia/commons/thumb/9/98/Blaise_Pascal_Versailles.JPG/800px-Blaise_Pascal_Versailles.JPG",
"https://en.wikipedia.org/wiki/Blaise_Pascal"));
this.queriesMap.add(new Query(Arrays.asList("william", "wordsworth"),
"William Wordsworth (7 April 1770 – 23 April 1850) was a \n "+
"major English Romantic poet who, with Samuel Taylor Coleridge, \n " +
"helped to launch the Romantic Age in English literature with \n "+
"their joint publication Lyrical Ballads (1798). \n" +
"Wordsworth's magnum opus is generally considered to be \n " +
"The Prelude, a semi-autobiographical poem of his early years \n"+
" that he revised and expanded a number of times. \n" +
" It was posthumously titled and published, before which \n"+
"it was generally known as \"the poem to Coleridge\". \n"+
"Wordsworth was Britain's poet laureate from 1843 \n"+
"until his death from pleurisy on 23 April 1850.",
"https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Wordsworth_on_Helvellyn_by_Benjamin_Robert_Haydon.jpg/800px-Wordsworth_on_Helvellyn_by_Benjamin_Robert_Haydon.jpg",
"https://en.wikipedia.org/wiki/William_Wordsworth"));
final DBReader dbReader;
public QueryProcessor(DBReader dbReader) {
this.dbReader = dbReader;
}
public List<Query> process(String query) {
List<Query> possibilities = new ArrayList<>();
for(Query q : queriesMap) {
List<String> name = q.getQuery();
boolean found = true;
StringTokenizer queryTokens = new StringTokenizer(query);
// this.queriesMap.add(new Query(Arrays.asList("augusta", "ada", "king", "lovelace"),
// "Augusta Ada King, Countess of Lovelace (10 December 1815 - 27 November\n" +
// "November 1852) was an English mathematician and writer, chiefly\n" +
// "known for her work on Charles Babbage's proposed mechanical\n" +
// "general-purpose computer, the Analytical Engine. She was the first to\n" +
// "recognise that the machine had applications beyond pure calculation,\n" +
// "and published the first algorithm intended to be carried out by such\n" +
// "a machine. As a result, she is sometimes regarded as the first to\n" +
// "recognise the full potential of a \"computing machine\" and the first\n" +
// "computer programmer.",
// "https://upload.wikimedia.org/wikipedia/commons/0/0b/Ada_Byron_daguerreotype_by_Antoine_Claudet_1843_or_1850.jpg",
// "https://en.wikipedia.org/wiki/Ada_Lovelace"));
public ResultSet process(String query) {
ResultSet possibilities = null;
StringTokenizer queryTokens = new StringTokenizer(query);
StringBuilder sqlQueryBuilder = new StringBuilder();
if (queryTokens.hasMoreTokens()) {
String token = queryTokens.nextToken().toLowerCase();
sqlQueryBuilder.append("SELECT * FROM PEOPLE WHERE identifier LIKE '%" + token + "%'");
while (queryTokens.hasMoreTokens()) {
found &= name.contains(queryTokens.nextToken().toLowerCase());
}
if (found) {
possibilities.add(q);
token = queryTokens.nextToken().toLowerCase();
sqlQueryBuilder.append(" AND identifier LIKE '%" + token+"%'");
}
sqlQueryBuilder.append(";");
String sqlQuery = sqlQueryBuilder.toString();
possibilities = dbReader.executeSQLQuery(sqlQuery);
}
if (possibilities.isEmpty()) {
List<Query> noQueryFound = new ArrayList<>();
noQueryFound.add(new Query(null, "", "", ""));
return noQueryFound;
}
return possibilities;
}
}
......@@ -9,6 +9,8 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class WebServer {
......@@ -24,6 +26,15 @@ public class WebServer {
}
static class Website extends HttpServlet {
final DBReader dbReader;
final QueryProcessor queryProcessor;
public Website(){
dbReader = new DBReader();
queryProcessor = new QueryProcessor(dbReader);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String query = req.getParameter("q");
......@@ -31,18 +42,32 @@ public class WebServer {
if (query == null || type == null) {
new IndexPage().writeTo(resp);
} else {
QueryProcessor queryProcessor = new QueryProcessor();
List<Query> possibilities = queryProcessor.process(query);
if (possibilities.size() == 1) {
Query answer = possibilities.get(0);
if (type.equals("html")) {
new HTMLResultPage(query, answer).writeTo(resp);
ResultSet queryRes = queryProcessor.process(query);
List<Query> possibilities = new ArrayList<>();
if (queryRes != null) {
try {
while (queryRes.next()) {
String name = queryRes.getString("name");
String description = queryRes.getString("description");
String imgUrl = queryRes.getString("imgUrl");
String wikiUrl = queryRes.getString("wikiUrl");
possibilities.add(new Query(name, description, imgUrl, wikiUrl));
}
}
catch (Exception e) {
System.out.println("Unknown error occurred");
}
if (possibilities.size() == 1) {
Query answer = possibilities.get(0);
if (type.equals("html")) {
new HTMLResultPage(query, answer).writeTo(resp);
} else {
new DownloadPage(query, answer, type).writeTo(resp);
}
} else {
new DownloadPage(query, answer, type).writeTo(resp);
new ChoicePage(query, possibilities).writeTo(resp);
// may not need a choice page class, just put code here
}
} else {
new ChoicePage(query, possibilities).writeTo(resp);
// may not need a choice page class, just put code here
}
}
}
......
......@@ -31,9 +31,9 @@ public class ChoicePage implements Page {
"<p>" + ambiguousQuery + " gave many results. Select which result you would like to view " +
"<br><br>");
while (!possibilities.isEmpty()) {
List<String> nameStrings = possibilities.get(0).getQuery();
String name = String.join(" ", nameStrings);
String ref = String.join("+", nameStrings);
String nameString = possibilities.get(0).getQuery();
String name = String.join(" ", nameString);
String ref = String.join("+", nameString);
writer.print("<a href=\"/?q=" + ref + "&type=html\">" + name + "</a>" +
"<br><br>");
possibilities.remove(0);
......
package ic.doc.web;
import java.sql.*;
public class DBReader {
Connection wiki;
Statement state;
public DBReader(){
try {
Class.forName("org.sqlite.JDBC");
wiki = DriverManager.getConnection("jdbc:sqlite:wiki.db");
state = wiki.createStatement();
} catch (Exception e) {
System.out.println("Failed to open database/statement");
System.exit(0);
}
}
public ResultSet executeSQLQuery(String query) {
ResultSet resultSet = null;
try {
resultSet = state.executeQuery(query);
} catch (SQLException e) {
System.out.println("Failed to execute query");
System.exit(0);
}
return resultSet;
}
}
......@@ -26,7 +26,7 @@ public class DownloadPage implements Page{
resp.setContentType("text/markdown");
}
if (answer == null || answer.getAnswer() == null || answer.getAnswer().isEmpty()) {
if (answer == null || answer.getDescription() == null || answer.getDescription().isEmpty()) {
resp.setHeader("Content-Disposition", "attachment;filename=\"sorry." + format + "\"");
PrintWriter writer = resp.getWriter();
writer.println("#Sorry");
......@@ -50,7 +50,7 @@ public class DownloadPage implements Page{
tmp.deleteOnExit();
FileWriter fw = new FileWriter(tmp);
fw.write("#" + query + "\n");
fw.write(answer.getAnswer());
fw.write(answer.getDescription());
fw.write("![alt text]("+answer.getImgURL()+" \"Pic\")");
fw.write("[Learn More!]("+answer.getWikiURL()+")");
fw.close();
......
......@@ -27,12 +27,12 @@ public class HTMLResultPage implements Page {
writer.println("<body>");
// Content
if (answer == null || answer.getAnswer() == null || answer.getAnswer().isEmpty()) {
if (answer == null || answer.getDescription() == null || answer.getDescription().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.getAnswer().replace("\n", "<br>") + "</p>");
writer.println("<p>" + answer.getDescription().replace("\n", "<br>") + "</p>");
writer.println("<p> <img src=\"" + answer.getImgURL() + "\"> </p>");
writer.println("<p><a href=\""+answer.getWikiURL()+"\" target=\"_blank" +
"\">Learn More!</a></p>");
......
......@@ -7,94 +7,94 @@ import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class QueryProcessorTest {
QueryProcessor queryProcessor = new QueryProcessor();
@Test
public void returnsEmptyStringIfCannotProcessQuery() throws Exception {
assertThat(queryProcessor.process("test").get(0).getAnswer(), is(""));
}
@Test
public void knowsAboutShakespeare() throws Exception {
assertThat(queryProcessor.process("Shakespeare").get(0).getAnswer(), containsString(
"playwright"));
}
@Test
public void knowsAboutAsimov() throws Exception {
assertThat(queryProcessor.process("Asimov").get(0).getAnswer(), containsString("science " +
"fiction"));
}
@Test
public void knowsAboutTuring() throws Exception {
assertThat(queryProcessor.process("Turing").get(0).getAnswer(), containsString("logician"));
}
@Test
public void knowsAboutLovelace() throws Exception {
assertThat(queryProcessor.process("Lovelace").get(0).getAnswer(), containsString(
"Countess of Lovelace"));
}
@Test
public void knowsAboutPascal() throws Exception {
assertThat(queryProcessor.process("Pascal").get(0).getAnswer(), containsString(
"clarified the concepts of pressure and vacuum"));
}
@Test
public void isNotCaseSensitive() throws Exception {
assertThat(queryProcessor.process("shakespeare").get(0).getAnswer(), containsString(
"playwright"));
}
@Test
public void knowsAboutWilliam() throws Exception {
assertThat(queryProcessor.process("william").get(0).getAnswer(), containsString(
"playwright"));
}
@Test
public void knowsAboutAda() throws Exception {
assertThat(queryProcessor.process("Ada").get(0).getAnswer(), containsString(
"Countess of Lovelace"));
}
@Test
public void knowsAboutIsaacAsimov() throws Exception {
assertThat(queryProcessor.process("Isaac Asimov").get(0).getAnswer(),
containsString(
"science " +
"fiction"));
}
@Test
public void knowsAboutAlanTuring() throws Exception {
assertThat(queryProcessor.process("Alan Turing").get(0).getAnswer(),
containsString(
"logician"));
}
@Test
public void knowsAboutAdaLovelace() throws Exception {
assertThat(queryProcessor.process("Ada Lovelace").get(0).getAnswer(),
containsString(
"Countess of Lovelace"));
}
@Test
public void recognisesDisorderedName() throws Exception {
assertThat(queryProcessor.process("Lovelace Ada Augusta").get(0).getAnswer(),
containsString(
"Countess of Lovelace"));
}
@Test
public void recognisesFalseName() throws Exception {
assertThat(queryProcessor.process("William Pascal Lovelace").get(0).getAnswer(),
is(""));
}
//
// QueryProcessor queryProcessor = new QueryProcessor();
//
// @Test
// public void returnsEmptyStringIfCannotProcessQuery() throws Exception {
// assertThat(queryProcessor.process("test").get(0).getAnswer(), is(""));
// }
//
// @Test
// public void knowsAboutShakespeare() throws Exception {
// assertThat(queryProcessor.process("Shakespeare").get(0).getAnswer(), containsString(
// "playwright"));
// }
//
// @Test
// public void knowsAboutAsimov() throws Exception {
// assertThat(queryProcessor.process("Asimov").get(0).getAnswer(), containsString("science " +
// "fiction"));
// }
//
// @Test
// public void knowsAboutTuring() throws Exception {
// assertThat(queryProcessor.process("Turing").get(0).getAnswer(), containsString("logician"));
// }
//
// @Test
// public void knowsAboutLovelace() throws Exception {
// assertThat(queryProcessor.process("Lovelace").get(0).getAnswer(), containsString(
// "Countess of Lovelace"));
// }
//
// @Test
// public void knowsAboutPascal() throws Exception {
// assertThat(queryProcessor.process("Pascal").get(0).getAnswer(), containsString(
// "clarified the concepts of pressure and vacuum"));
// }
//
// @Test
// public void isNotCaseSensitive() throws Exception {
// assertThat(queryProcessor.process("shakespeare").get(0).getAnswer(), containsString(
// "playwright"));
// }
//
// @Test
// public void knowsAboutWilliam() throws Exception {
// assertThat(queryProcessor.process("william").get(0).getAnswer(), containsString(
// "playwright"));
// }
//
// @Test
// public void knowsAboutAda() throws Exception {
// assertThat(queryProcessor.process("Ada").get(0).getAnswer(), containsString(
// "Countess of Lovelace"));
// }
//
//
// @Test
// public void knowsAboutIsaacAsimov() throws Exception {
// assertThat(queryProcessor.process("Isaac Asimov").get(0).getAnswer(),
// containsString(
// "science " +
// "fiction"));
// }
//
// @Test
// public void knowsAboutAlanTuring() throws Exception {
// assertThat(queryProcessor.process("Alan Turing").get(0).getAnswer(),
// containsString(
// "logician"));
// }
//
// @Test
// public void knowsAboutAdaLovelace() throws Exception {
// assertThat(queryProcessor.process("Ada Lovelace").get(0).getAnswer(),
// containsString(
// "Countess of Lovelace"));
// }
//
// @Test
// public void recognisesDisorderedName() throws Exception {
// assertThat(queryProcessor.process("Lovelace Ada Augusta").get(0).getAnswer(),
// containsString(
// "Countess of Lovelace"));
// }
//
// @Test
// public void recognisesFalseName() throws Exception {
// assertThat(queryProcessor.process("William Pascal Lovelace").get(0).getAnswer(),
// is(""));
// }
}
File added
File added
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