Skip to content

Commit e357cc1

Browse files
author
Malte Schink
authored
Merge pull request #31 from Jugendhackt/development
Development
2 parents db11f1c + 0b9a493 commit e357cc1

File tree

6 files changed

+217
-32
lines changed

6 files changed

+217
-32
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,6 @@
2121

2222
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
2323
hs_err_pid*
24+
25+
.idea
26+
*.iml

InstaNoteServer.iml

Lines changed: 0 additions & 2 deletions
This file was deleted.

pom.xml

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,14 @@
99
<version>DEV</version>
1010

1111
<dependencies>
12-
<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
12+
13+
<!-- https://mvnrepository.com/artifact/org.json/json -->
1314
<dependency>
14-
<groupId>com.googlecode.json-simple</groupId>
15-
<artifactId>json-simple</artifactId>
16-
<version>1.1.1</version>
15+
<groupId>org.json</groupId>
16+
<artifactId>json</artifactId>
17+
<version>20160810</version>
1718
</dependency>
19+
1820
</dependencies>
1921

2022
<build>

src/main/java/DataHandler.java

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import org.json.JSONArray;
2+
import org.json.JSONObject;
3+
import org.json.XML;
4+
5+
import java.io.IOException;
6+
import java.net.URL;
7+
import java.net.URLEncoder;
8+
import java.util.Scanner;
9+
10+
class DataHandler {
11+
12+
/**
13+
* @param query keyword for the wikidata query
14+
* @param lang language for wikidata dump
15+
* @return entityID
16+
*/
17+
private static String queryToEntity(String query, String lang) {
18+
try {
19+
//Get the data from the wikidata api using a search word and a language
20+
Scanner scanner = new Scanner(new URL("https://www.wikidata.org/w/api.php?action=wbsearchentities&format=json&uselang=" + lang + "&search=" + query + "&language=" + lang).openStream());
21+
StringBuilder stringBuilder = new StringBuilder();
22+
while (scanner.hasNextLine()) {
23+
stringBuilder.append(scanner.nextLine());
24+
}
25+
scanner.close();
26+
27+
//Convert the data to a JSONObject and return the entities id
28+
JSONObject jsonObject = new JSONObject(stringBuilder.toString()).getJSONArray("search").getJSONObject(0);
29+
Log.success("Received the entities id");
30+
return jsonObject.getString("id");
31+
32+
} catch (IOException e) {
33+
e.printStackTrace();
34+
}
35+
return null;
36+
}
37+
38+
static JSONObject queryCall(String query, String lang){
39+
//Get the entities id based on a query
40+
String entityId = queryToEntity(query, lang);
41+
String queryAufruf = "SELECT ?Name ?EinwohnerZahl ?Landeswappen ?Karte ?Bild ?Koordinaten ?Flagge ?description WHERE {\n" +
42+
" wd:"+entityId+" wdt:P1448 ?Name." +
43+
" OPTIONAL { wd:"+entityId+" wdt:P1082 ?EinwohnerZahl. }" +
44+
" OPTIONAL { wd:"+entityId+" wdt:P94 ?Landeswappen. }" +
45+
" OPTIONAL { wd:"+entityId+" wdt:P242 ?Karte. }" +
46+
" OPTIONAL { wd:"+entityId+" wdt:P18 ?Bild. }" +
47+
" OPTIONAL { wd:"+entityId+" wdt:P625 ?Koordinaten. }" +
48+
" OPTIONAL { wd:"+entityId+" wdt:P41 ?Flagge. }" +
49+
" OPTIONAL { wd:"+entityId+" schema:description ?description." +
50+
" FILTER(LANG(?description)=\"de\")}" +
51+
" SERVICE wikibase:label { bd:serviceParam wikibase:language \"" + lang + "\". }" +
52+
"}";
53+
try {
54+
//Encode the query to be used in an url
55+
String queryEncoded = URLEncoder.encode(queryAufruf, "UTF-8");
56+
57+
//Declare the scanner to later get data from wikidata
58+
Scanner scanner = new Scanner(new URL("https://query.wikidata.org/sparql?query=" + queryEncoded).openStream());
59+
60+
//Get all the data to be stored in a StringBuilder
61+
StringBuilder stringBuilder = new StringBuilder();
62+
while (scanner.hasNextLine()) {
63+
stringBuilder.append(scanner.nextLine());
64+
}
65+
scanner.close();
66+
//return the data as a JSONObject
67+
String s = stringBuilder.toString();
68+
return XML.toJSONObject(s);
69+
70+
71+
} catch (IOException e) {
72+
e.printStackTrace();
73+
}
74+
return null;
75+
}
76+
77+
static JSONObject convertJSON(JSONObject wikiData) {
78+
JSONObject result = wikiData.getJSONObject("sparql").getJSONObject("results");
79+
JSONObject resultObject = result.optJSONObject("result");
80+
if(resultObject == null){
81+
resultObject = result.getJSONArray("result").getJSONObject(0);
82+
}
83+
JSONArray results = resultObject.getJSONArray("binding");
84+
85+
JSONObject resultsObject = new JSONObject();
86+
87+
for (int i = 0; i < results.length(); i++) {
88+
JSONObject jsonObject = results.getJSONObject(i);
89+
90+
String key = jsonObject.getString("name");
91+
String value;
92+
93+
if(jsonObject.has("literal")) {
94+
value = String.valueOf(jsonObject.getJSONObject("literal").get("content"));
95+
} else {
96+
value = jsonObject.getString("uri");
97+
}
98+
99+
resultsObject.put(key, value);
100+
Log.status("added "+key);
101+
}
102+
103+
JSONObject newWikiDataset = new JSONObject();
104+
newWikiDataset.put("head", wikiData.getJSONObject("sparql").getJSONObject("head").getJSONArray("variable"));
105+
newWikiDataset.put("results", resultsObject);
106+
Log.success("formatting succesfull");
107+
return newWikiDataset;
108+
}
109+
}

src/main/java/Log.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import java.time.LocalDateTime;
2+
import java.time.format.DateTimeFormatter;
3+
4+
public class Log {
5+
6+
private static void write(String text) {
7+
System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm")) + " > " + text);
8+
}
9+
10+
static void status(String text) {
11+
write(text);
12+
}
13+
14+
static void success(String text) {
15+
write(ANSI_GREEN + text + ANSI_RESET);
16+
}
17+
18+
static void error(String text) {
19+
write(ANSI_RED + "Error: " + text + ANSI_RESET);
20+
}
21+
22+
static void warning(String text) {
23+
write(ANSI_YELLOW + "Warning: " + text + ANSI_RESET);
24+
}
25+
26+
static void critical(String text) {
27+
write(ANSI_RED_BACKGROUND + ANSI_BLACK + "CRITICAL: " + text + ANSI_RESET);
28+
}
29+
30+
private static final String ANSI_BLACK = "\u001B[30m";
31+
private static final String ANSI_RESET = "\u001B[0m";
32+
private static final String ANSI_RED = "\u001B[31m";
33+
private static final String ANSI_GREEN = "\u001B[32m";
34+
private static final String ANSI_YELLOW = "\u001B[33m";
35+
private static final String ANSI_BLUE = "\u001B[34m";
36+
private static final String ANSI_PURPLE = "\u001B[35m";
37+
private static final String ANSI_CYAN = "\u001B[36m";
38+
private static final String ANSI_WHITE = "\u001B[37m";
39+
40+
private static final String ANSI_BLACK_BACKGROUND = "\u001B[40m";
41+
private static final String ANSI_RED_BACKGROUND = "\u001B[41m";
42+
private static final String ANSI_GREEN_BACKGROUND = "\u001B[42m";
43+
private static final String ANSI_YELLOW_BACKGROUND = "\u001B[43m";
44+
private static final String ANSI_BLUE_BACKGROUND = "\u001B[44m";
45+
private static final String ANSI_PURPLE_BACKGROUND = "\u001B[45m";
46+
private static final String ANSI_CYAN_BACKGROUND = "\u001B[46m";
47+
private static final String ANSI_WHITE_BACKGROUND = "\u001B[47m";
48+
}

src/main/java/Main.java

Lines changed: 51 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,61 @@
11
import com.sun.net.httpserver.Headers;
22
import com.sun.net.httpserver.HttpExchange;
3+
import com.sun.net.httpserver.HttpHandler;
34
import com.sun.net.httpserver.HttpServer;
45

56
import java.io.IOException;
67
import java.net.InetSocketAddress;
8+
import java.util.HashMap;
9+
import java.util.LinkedHashMap;
710

811
public class Main {
9-
private Main() {
10-
try {
11-
HttpServer httpServer = HttpServer.create(new InetSocketAddress(2000), 0);
12-
13-
14-
httpServer.start();
15-
} catch (IOException e) {
16-
e.printStackTrace();
17-
}
18-
}
19-
20-
public static void main(String[] args) {
21-
new Main();
22-
}
23-
24-
25-
void write(String text, int rCode, HttpExchange exchange) throws IOException {
26-
Headers responseHeaders = exchange.getResponseHeaders();
27-
responseHeaders.add("Content-Type", "application/json");
28-
29-
exchange.sendResponseHeaders(rCode, text.length());
30-
exchange.getResponseBody().write(text.getBytes());
31-
exchange.getResponseBody().close();
32-
}
33-
34-
12+
private Main() {
13+
try {
14+
HttpServer httpServer = HttpServer.create(new InetSocketAddress(1337), 0);
15+
16+
httpServer.createContext("/search", new searchHandler());
17+
18+
httpServer.start();
19+
} catch (IOException e) {
20+
e.printStackTrace();
21+
}
22+
}
23+
24+
public static void main(String[] args) {
25+
Log.status("starting http-server...");
26+
new Main();
27+
Log.success("started http-server");
28+
}
29+
30+
private class searchHandler implements HttpHandler {
31+
@Override
32+
public void handle(HttpExchange exchange) throws IOException {
33+
HashMap<String, String> query = queryToMap(exchange.getRequestURI().getQuery());
34+
35+
Log.status("Received a request for a search");
36+
write(DataHandler.convertWikiData(DataHandler.queryCall(query.get("key"), query.get("lang"))).toString(), 200, exchange);
37+
}
38+
}
39+
40+
41+
private HashMap<String, String> queryToMap(String query) {
42+
LinkedHashMap<String, String> result = new LinkedHashMap<>();
43+
44+
for (String arg : query.split("&")) {
45+
String[] keyAndValue = arg.split("=");
46+
result.put(keyAndValue[0], keyAndValue[1]);
47+
}
48+
return result;
49+
}
50+
51+
52+
private void write(String text, int rCode, HttpExchange exchange) throws IOException {
53+
Headers responseHeaders = exchange.getResponseHeaders();
54+
responseHeaders.add("Content-Type", "application/json");
55+
responseHeaders.add("Access-Control-Allow-Origin", "*");
56+
exchange.sendResponseHeaders(rCode, text.getBytes().length);
57+
exchange.getResponseBody().write(text.getBytes());
58+
exchange.getResponseBody().close();
59+
}
3560
}
3661

0 commit comments

Comments
 (0)