From 82f240ebf2ae717123fd726ea9ec1a9868ee1f8d Mon Sep 17 00:00:00 2001 From: Valerian Wintner <v.d.w@hotmail.com> Date: Sun, 14 Nov 2021 13:29:55 +0100 Subject: [PATCH] Cleanup fetching/writing. --- src/main/java/com/kgshape/app/Query.java | 33 ++++++++++++++---------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/kgshape/app/Query.java b/src/main/java/com/kgshape/app/Query.java index 3f40084..ca4c73b 100644 --- a/src/main/java/com/kgshape/app/Query.java +++ b/src/main/java/com/kgshape/app/Query.java @@ -13,12 +13,13 @@ import org.apache.logging.log4j.core.config.DefaultConfiguration; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; +import java.nio.file.FileSystemNotFoundException; /** - * See: https://jena.apache.org/documentation/query/app_api.html + * Queries a remote endpoint. */ public class Query { - public static void main(String[] args) { + public static void main(String[] args) throws IOException { // https://stackoverflow.com/questions/41442024/basicconfigurator-replacement-in-log4j2 Configurator.initialize(new DefaultConfiguration()); Configurator.setRootLevel(Level.INFO); @@ -45,23 +46,27 @@ public class Query { // You can also open this endpoint in the browser and test the above query String endpoint = "https://dbpedia.org/sparql"; + Model fetchedModel = fetchConstruct(endpoint, construct_query); + writeModel(fetchedModel, "rdf_file.ttl"); + } + + public static Model fetchConstruct(String endpoint, String query) { // https://jena.apache.org/documentation/query/sparql-remote.html - QueryExecution qexec = QueryExecutionFactory.sparqlService(endpoint, construct_query); + // Also see: https://jena.apache.org/documentation/query/app_api.html + QueryExecution qexec = QueryExecutionFactory.sparqlService(endpoint, query); Model resultModel = qexec.execConstruct(); + qexec.close(); + return resultModel; + } -// RDFDataMgr.write(System.out, resultModel, Lang.TURTLE); + public static void writeModel(Model model, String filename) throws FileSystemNotFoundException, IOException { +// RDFDataMgr.write(System.out, resultModel, Lang.TURTLE); // Write it to stdout - try (FileOutputStream fos = new FileOutputStream("rdf.ttl")) { + try (FileOutputStream fos = new FileOutputStream(filename)) { // See: https://jena.apache.org/documentation/io/rdf-output.html#opt-turtle-trig - RDFDataMgr.write(fos, resultModel, Lang.TURTLE); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); + RDFDataMgr.write(fos, model, Lang.TURTLE); + } catch (Exception e) { + throw e; } - - qexec.close(); - - System.out.println("Hello Query!"); } } -- GitLab