|
1 | | -// https://github.com/BorderCloud/SPARQL-JAVA |
2 | | -import com.bordercloud.sparql.Endpoint; |
3 | | -import com.bordercloud.sparql.EndpointException; |
4 | | -import java.util.ArrayList; |
5 | | -import java.util.HashMap; |
| 1 | +// https://github.com/eclipse/rdf4j |
| 2 | +import org.eclipse.rdf4j.query.resultio.sparqljson.SPARQLResultsJSONWriter; |
| 3 | +import org.eclipse.rdf4j.repository.RepositoryException; |
| 4 | +import org.eclipse.rdf4j.repository.sparql.SPARQLRepository; |
| 5 | +import java.util.Collections; |
6 | 6 |
|
7 | | -public class Main { |
| 7 | +/** |
| 8 | + * Wikidata RDF4J SPARQL example |
| 9 | + */ |
| 10 | +public class App |
| 11 | +{ |
| 12 | + public static void main( String[] args ) |
| 13 | + { |
| 14 | + String sparqlEndpoint = "{ENDPOINT_URL}"; |
| 15 | + SPARQLRepository repo = new SPARQLRepository(sparqlEndpoint); |
8 | 16 |
|
9 | | - public static void main(String[] args) { |
10 | | - String endpointUrl = "{ENDPOINT_URL}"; |
| 17 | + String userAgent = "Wikidata RDF4J Java Example/0.1 (https://query.wikidata.org/)"; |
| 18 | + repo.setAdditionalHttpHeaders( Collections.singletonMap("User-Agent", userAgent ) ); |
11 | 19 |
|
12 | 20 | String querySelect = {SPARQL_QUERY}; |
13 | 21 |
|
14 | | - try { |
15 | | - HashMap data = retrieveData(endpointUrl, querySelect); |
16 | | - printResult(data, 30); |
17 | | - } catch (EndpointException eex) { |
18 | | - eex.printStackTrace(); |
| 22 | + try{ |
| 23 | + repo.getConnection().prepareTupleQuery(querySelect).evaluate(new SPARQLResultsJSONWriter(System.out)); |
| 24 | + } catch ( Exception exception ) { |
| 25 | + exception.printStackTrace(); |
19 | 26 | } |
20 | | - } |
21 | | - |
22 | | - public static HashMap<String, HashMap> retrieveData(String endpointUrl, String query) throws EndpointException { |
23 | | - Endpoint sp = new Endpoint(endpointUrl, false); |
24 | | - sp.setUserAgentRequestHeader("WDQS-Example Java"); // TODO adjust this; see https://w.wiki/CX6 |
25 | | - HashMap<String, HashMap> rs = sp.query(query); |
26 | | - return rs; |
27 | | - } |
28 | 27 |
|
29 | | - public static void printResult(HashMap<String, HashMap> rs , int size) { |
30 | | - for (String variable : (ArrayList<String>) rs.get("result").get("variables")) { |
31 | | - System.out.print(String.format("%-"+size+"."+size+"s", variable ) + " | "); |
32 | | - } |
33 | | - System.out.print("\n"); |
34 | | - for (HashMap value : (ArrayList<HashMap>) rs.get("result").get("rows")) { |
35 | | - for (String variable : (ArrayList<String>) rs.get("result").get("variables")) { |
36 | | - System.out.print(String.format("%-"+size+"."+size+"s", value.get(variable)) + " | "); |
37 | | - } |
38 | | - System.out.print("\n"); |
39 | | - } |
40 | 28 | } |
41 | | -} |
| 29 | +} |
0 commit comments