public static void main(String[] args) { // populate SPARQL SELECT Query string StringBuilder sb = new StringBuilder(); sb.append("PREFIX books: <http://example.org/book/>").append(NEWLINE); sb.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>").append(NEWLINE); sb.append("SELECT ?book ?title").append(NEWLINE); sb.append("WHERE {").append(NEWLINE); sb.append(" ?book dc:title ?title").append(NEWLINE); sb.append("}").append(NEWLINE); // query from remote service QueryExecution qexec = QueryExecutionFactory.sparqlService(SERVICE_URL, sb.toString()); System.out.println("Plan to run remote SPARQL query: "); System.out.println(BOUNDARY); System.out.println(sb.toString()); System.out.println(BOUNDARY); ResultSet rs = qexec.execSelect(); // use result set formatter ResultSetFormatter.out(rs); qexec.close(); }
public void queryExecute(Integer testNumber) throws Exception { String queryString = readFile(path + queryFolder + "/test" + testNumber + "/query.txt", Charset.defaultCharset()); String queryResultString = readFile(path + queryFolder + "/test"+ testNumber + "/queryresult.txt", Charset.defaultCharset()); RemediatorQuery query = RemediatorQueryFactory.create(queryString); RemediatorFederatedQuery federatedQuery = RemediatorFederatedQueryFactory.create(query, voidModel, false); QueryExecution queryExecution = RemediatorQueryExecutionFactory.create(federatedQuery); try { ResultSet results = queryExecution.execSelect(); String resultString = ResultSetFormatter.asText(results); writeFile(path + queryFolder + "/test" + testNumber + "/queryresult.res.txt", resultString.toString() ); assertEquals(resultString.toString(), queryResultString.replaceAll("\\s+", ""), resultString.toString().replaceAll("\\s+", "")); } catch (Exception e) { fail(e.getMessage()); } finally { queryExecution.close(); } }
public void queryExecute(Integer testNumber) throws Exception { String rewrittenQueryString = readFile(path + queryFolder + "/test" + testNumber + "/rewrite.txt", Charset.defaultCharset()); String queryResultString = readFile(path + queryFolder + "/test"+ testNumber + "/queryresult.txt", Charset.defaultCharset()); QueryExecution queryExecution = RemediatorQueryExecutionFactory.create(rewrittenQueryString); try { ResultSet results = queryExecution.execSelect(); String resultString = ResultSetFormatter.asText(results); writeFile(path + queryFolder + "/test" + testNumber + "/queryresult.res.txt", resultString.toString() ); assertEquals(resultString.toString(), queryResultString.replaceAll("\\s+", ""), resultString.toString().replaceAll("\\s+", "")); } catch (Exception e) { fail(e.getStackTrace().toString()); } finally { queryExecution.close(); } }
public static void main(String[] args) throws Exception { try { SolRDF solrdf = SolRDF.newBuilder() .withEndpoint("http://127.0.0.1:8080/solr/store") .withGraphStoreProtocolEndpointPath("/rdf-graph-store") .withSPARQLEndpointPath("/sparql") .build(); solrdf.add(new FileReader("/work/workspaces/solrdf/solrdf/solrdf/solrdf-integration-tests/src/test/resources/sample_data/faceting_test_dataset.nt"), "N-TRIPLES"); solrdf.commit(); CloseableResultSet rs = null; try { rs = solrdf.select("SELECT * WHERE {?s ?p ?o}"); System.out.println(ResultSetFormatter.asText(rs)); Model m = solrdf.construct("DESCRIBE <http://example.org/book4>"); System.out.println(m); } finally { rs.close(); } } catch (final UnableToBuildSolRDFClientException exception) { exception.printStackTrace(); } }
public static void main(String[] args) throws Exception { Dataset memoryDataset = DatasetFactory.createMem(); Model memoryModel = ModelFactory.createDefaultModel(); memoryModel.read(new FileReader("/work/workspaces/rdf/SolRDF/solrdf/src/test/resources/sample_data/one_triple_1.ttl"), "http://e.org", "TTL"); memoryDataset.addNamedModel("http://grapha.com", memoryModel); memoryModel = ModelFactory.createDefaultModel(); memoryModel.read(new FileReader("/work/workspaces/rdf/SolRDF/solrdf/src/test/resources/sample_data/one_triple_2.ttl"), "http://e.org", "TTL"); memoryDataset.addNamedModel("http://graphb.com", memoryModel); memoryModel = ModelFactory.createDefaultModel(); memoryModel.read(new FileReader("/work/workspaces/rdf/SolRDF/solrdf/src/test/resources/sample_data/one_triple_3.ttl"), "http://e.org", "TTL"); memoryDataset.addNamedModel("http://graphc.com", memoryModel); memoryModel = ModelFactory.createDefaultModel(); memoryModel.read(new FileReader("/work/workspaces/rdf/SolRDF/solrdf/src/test/resources/sample_data/one_triple_4.ttl"), "http://e.org", "TTL"); memoryDataset.addNamedModel("http://graphd.com", memoryModel); final Query query = QueryFactory.create(q2());//"SELECT ?s FROM <http://grapha.com> WHERE { ?s <http://example.org/title> ?o }"); System.out.println(ResultSetFormatter.asText(QueryExecutionFactory.create(query, memoryDataset).execSelect())); }
/** * Executes a given SELECT query against a given dataset. * * @param data the mistery guest containing test data (query and dataset) * @throws Exception never, otherwise the test fails. */ protected void selectTest(final MisteryGuest data) throws Exception { load(data); try { assertTrue( Arrays.toString(data.datasets) + ", " + data.query, ResultSetCompare.isomorphic( SOLRDF_CLIENT.select(queryString(data.query)), (inMemoryExecution = QueryExecutionFactory.create( QueryFactory.create(queryString(data.query)), memoryDataset)).execSelect())); } catch (final Throwable error) { log.debug("JNS\n" + ResultSetFormatter.asText(SOLRDF_CLIENT.select(queryString(data.query)))); QueryExecution debugExecution = null; log.debug("MEM\n" + ResultSetFormatter.asText( (debugExecution = (QueryExecutionFactory.create( QueryFactory.create(queryString(data.query)), memoryDataset))).execSelect())); debugExecution.close(); throw error; } }
public void doit() { Dataset dataset = DatasetFactory.createMem(); Model model = dataset.getDefaultModel(); model.read("category_labels_en.nq"); if (model.READ){ System.out.println("right!!"); } Query q = QueryFactory.create(query); QueryExecution qe = QueryExecutionFactory.create(q, model); ResultSet rs = qe.execSelect(); ResultSetFormatter.out(rs); }
/** * Gets code assoctaied with the specified label. * @param label label * @param locale locale * @return code or empty string if no label found */ public String getCode(String label, Locale locale) { QueryExecution queryExecutor = null; try { Query query = createQuery(label, locale); queryExecutor = QueryExecutionFactory.create(query, model); ResultSet results = queryExecutor.execSelect(); String codeList = ResultSetFormatter.toList(results).toString(); return codeList.indexOf("<") >= 0 ? codeList.substring(codeList.indexOf("<") + 1, codeList.indexOf(">")) : ""; } finally { if (queryExecutor != null) { queryExecutor.close(); } } }
private static void out(Map<String, String> commands, ResultSet rs) { if(commands.containsKey(SPARQL_QUERY_JSON_OUTPUT_FORMAT_COMMAND)) { ResultSetFormatter.outputAsJSON(System.out, rs); } else { ResultSetFormatter.out(System.out, rs); } }
public List<String> getResult(InputStream in, String query){ Model model=ModelFactory.createDefaultModel(); model.read(in,null,"TTL"); Query q = QueryFactory.create(query); QueryExecution qe = QueryExecutionFactory.create(q, model); ResultSet qresults = qe.execSelect(); List<QuerySolution> solutions=ResultSetFormatter.toList(qresults); List<String> results=new ArrayList<String>(); for(QuerySolution qs:solutions){ results.add(qs.toString()); } return results; }
public static void executeQuery(String query){ System.out.println("Load model..."); OntModel ontModel=loadDefaultModel(); System.out.println("Start to query..."); long start=System.currentTimeMillis(); Query q = QueryFactory.create(prefixes+query); QueryExecution qe = QueryExecutionFactory.create(q, ontModel); ResultSet qresults = qe.execSelect(); ResultSetFormatter.out(qresults); long end=System.currentTimeMillis(); System.out.println("Query time: "+((float)(end-start))/1000+ " s"); }
public static void main(String[] args) throws ClassNotFoundException, IOException, ParserConfigurationException, SAXException, URISyntaxException { Model model = ModelFactory.createDefaultModel(); InputStream in = FireSeparationDistance.class.getClassLoader().getResourceAsStream("lifeline_final.ttl"); model.read(in, null, "TTL"); System.out.println(model.size()); Model geometryModel = ModelFactory.createDefaultModel(); InputStream ing = FireSeparationDistance.class.getClassLoader().getResourceAsStream("lifeline_final_geometry.ttl"); geometryModel.read(ing, null, "TTL"); System.out.println(geometryModel.size()); Model schema=loadModel("IFC2X3_TC1.ttl","TTL"); BimSPARQL.init(model, geometryModel); Model ibcspin = ModelFactory.createDefaultModel(); addMagicProperty(ibcspin, IBC+"hasFireSeparationDistance", prefixes+hasFireSeparationDistance, 1); addMagicProperty(ibcspin, IBC+"hasProtectedOpeningArea", prefixes+hasProtectedOpeningArea, 1); addMagicProperty(ibcspin, IBC+"hasUnprotectedOpeningArea", prefixes+hasUnprotectedOpeningArea, 1); addMagicProperty(ibcspin, IBC+"hasAp", prefixes+hasAp, 1); addMagicProperty(ibcspin, IBC+"hasAu", prefixes+hasAu, 1); Model ibc=loadIbcData(); SPINModuleRegistry.get().registerAll(ibc, null); for (Function f:SPINModuleRegistry.get().getFunctions()) { System.out.println(f.getURI()); } com.hp.hpl.jena.query.Query query = QueryFactory.create(prefixes + mainQuery); OntModel union = ModelFactory.createOntologyModel(); union.add(schema); union.add(model); union.add(geometryModel); union.add(ibc); System.out.println(union.size()); QueryExecution qe = QueryExecutionFactory.create(query, union); com.hp.hpl.jena.query.ResultSet result = qe.execSelect(); ResultSetFormatter.out(result); }
public static void main(String[] args) throws FileNotFoundException{ Model model=ModelFactory.createDefaultModel(); InputStream in=new FileInputStream("BimSPARQL_example.ttl"); model.read(in,null,"TTL"); String query=prefixes+"SELECT ?s\n"+ "WHERE{?s ?p ?o .}"; Query q = QueryFactory.create(query); QueryExecution qe = QueryExecutionFactory.create(q, model); ResultSet qresults = qe.execSelect(); ResultSetFormatter.out(qresults); }
private void getInstances() { File metricFile = new File( System.getProperty("user.dir") + "/sparql/queries/getInstances.sparql"); List<String> lines = null; try { lines = Files.readAllLines(metricFile.toPath()); } catch (IOException ex) { Logger.getLogger(Ontogui.class.getName()).log(Level.SEVERE, null, ex); } String queryString = ""; for (String line : lines) { queryString += line + System.lineSeparator(); } ParameterizedSparqlString pss = new ParameterizedSparqlString(); pss.setCommandText(queryString); pss.setLiteral("typename", typename); data.begin(ReadWrite.READ); List<QuerySolution> rlist = null; try (QueryExecution qe = QueryExecutionFactory.create(pss.asQuery(), data)) { ResultSet results = qe.execSelect(); rlist = ResultSetFormatter.toList(results); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Writting to textarea failed!"); e.printStackTrace(); } instances = new String[rlist.size()]; for(int j = 0; j < rlist.size(); j++){ instances[j] = rlist.get(j).getLiteral("iname").getString(); } data.end(); }
private void getSubtypes() { File metricFile = new File( System.getProperty("user.dir") + "/sparql/queries/getSubtypes.sparql"); List<String> lines = null; try { lines = Files.readAllLines(metricFile.toPath()); } catch (IOException ex) { Logger.getLogger(Ontogui.class.getName()).log(Level.SEVERE, null, ex); } String queryString = ""; for (String line : lines) { queryString += line + System.lineSeparator(); } ParameterizedSparqlString pss = new ParameterizedSparqlString(); pss.setCommandText(queryString); pss.setLiteral("typename", typename); data.begin(ReadWrite.READ); List<QuerySolution> rlist = null; try (QueryExecution qe = QueryExecutionFactory.create(pss.asQuery(), data)) { ResultSet results = qe.execSelect(); rlist = ResultSetFormatter.toList(results); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Writting to textarea failed!"); e.printStackTrace(); } data.end(); subtypes= new String[rlist.size()]; for(int j = 0; j < rlist.size(); j++){ subtypes[j] = rlist.get(j).getLiteral("sname").getString(); } }
private void getDistantEntities(){ File metricFile = new File( System.getProperty("user.dir") + "/sparql/smells/SemanticallyDistantEntity.sparql"); List<String> lines = null; try { lines = Files.readAllLines(metricFile.toPath()); } catch (IOException ex) { Logger.getLogger(Ontogui.class.getName()).log(Level.SEVERE, null, ex); } String queryString = ""; for (String line : lines) { queryString += line + System.lineSeparator(); } data.begin(ReadWrite.READ); List<QuerySolution> rlist = null; Query query = QueryFactory.create(queryString, Syntax.syntaxARQ); try (QueryExecution qe = QueryExecutionFactory.create(query, data)) { ResultSet results = qe.execSelect(); rlist = ResultSetFormatter.toList(results); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Writting to textarea failed!"); e.printStackTrace(); } instances = new String[rlist.size()]; for(int j = 0; j < rlist.size(); j++){ instances[j] = rlist.get(j).getLiteral("entityname").getString(); } data.end(); }
private void getDistantTypes(){ File metricFile = new File( System.getProperty("user.dir") + "/sparql/smells/SemanticallyDistantType.sparql"); List<String> lines = null; try { lines = Files.readAllLines(metricFile.toPath()); } catch (IOException ex) { Logger.getLogger(Ontogui.class.getName()).log(Level.SEVERE, null, ex); } String queryString = ""; for (String line : lines) { queryString += line + System.lineSeparator(); } data.begin(ReadWrite.READ); List<QuerySolution> rlist = null; Query query = QueryFactory.create(queryString, Syntax.syntaxARQ); try (QueryExecution qe = QueryExecutionFactory.create(query, data)) { ResultSet results = qe.execSelect(); rlist = ResultSetFormatter.toList(results); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Writting to textarea failed!"); e.printStackTrace(); } subtypes = new String[rlist.size()]; for(int j = 0; j < rlist.size(); j++){ subtypes[j] = rlist.get(j).getLiteral("typename").getString(); } data.end(); }
@Override public void run() { dataset.begin(ReadWrite.READ); System.out.println("------------------"); System.out.println(query); Op op = Algebra.compile(query); op = Algebra.optimize(op); System.out.println(op); System.out.println("------------------"); System.out.println(query); long time = System.currentTimeMillis(); try (QueryExecution qe = QueryExecutionFactory.create(query, dataset)) { ResultSet results = qe.execSelect(); if(pretty){ System.out.println("Output as pretty printed text"); ResultSetFormatter.out(stream, results, query); }else{ System.out.println("Output as CSV"); ResultSetFormatter.outputAsCSV(stream, results); } }catch (Exception e){ JOptionPane.showMessageDialog(null, "Writting to textarea failed!"); e.printStackTrace(); } time = System.currentTimeMillis() - time; String timeString = "\n Performed query in: "+time+"ms"; try { stream.write(timeString.getBytes()); stream.showText(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Writting to textarea failed!"); } System.out.println(time); System.out.println("Finished query"); dataset.end(); }
public static void main(String[] args) { ParameterizedSparqlString qs = new ParameterizedSparqlString("" + "prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" + "prefix dbpedia-owl: <http://dbpedia.org/ontology/>\n" + "prefix dbpprop: <http://dbpedia.org/property/>\n" + "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n" + "SELECT DISTINCT * \n" + "WHERE { \n" + " ?resource rdfs:label ?label ;\n" + " dbpedia-owl:abstract ?abstract .\n" + "FILTER ( lang(?abstract) = 'en' ) \n" + "}"); Literal london = ResourceFactory.createLangLiteral("London", "en"); qs.setParam("label", london); System.out.println(qs); QueryExecution exec = QueryExecutionFactory.sparqlService( "http://dbpedia.org/sparql", qs.asQuery()); ResultSet results = ResultSetFactory.copyResults(exec.execSelect()); while (results.hasNext()) { QuerySolution sol = (QuerySolution) results.next(); RDFNode node = sol.get("resource"); System.out.println(sol.get("?abstract")); System.out.println(node); } // A simpler way of printing the results. ResultSetFormatter.out(results); }
@Test public void select() throws Exception { for (final MisteryGuest data : DATA) { log.info("Running " + data.description + " test..."); load(data); final Query query = QueryFactory.create(queryString(data.query)); QueryExecution execution = null; QueryExecution inMemoryExecution = null; try { assertTrue( Arrays.toString(data.datasets) + ", " + data.query, ResultSetCompare.isomorphic( (execution = QueryExecutionFactory.create(query, dataset)).execSelect(), (inMemoryExecution = QueryExecutionFactory.create(query, memoryDataset)).execSelect())); } catch (final AssertionError error) { QueryExecution debugExecution = null; log.debug("JNS\n" + ResultSetFormatter.asText( (debugExecution = (QueryExecutionFactory.create(query, dataset))).execSelect())); debugExecution.close(); log.debug("MEM\n" + ResultSetFormatter.asText( (debugExecution = (QueryExecutionFactory.create(query, memoryDataset))).execSelect())); debugExecution.close(); throw error; } finally { clearDatasets(); execution.close(); inMemoryExecution.close(); } } }
private void dump(Table table) { Log.debug(this,"Table: "+Utils.className(table)) ; QueryIterator qIter = table.iterator(null) ; ResultSet rs = new ResultSetStream(table.getVarNames(), null, table.iterator(null)) ; ResultSetFormatter.out(rs) ; }
private void showQueryResults(String queryString, HttpServletRequest request, HttpServletResponse response) throws IOException { Query query = QueryFactory.create(queryString); if(query.isSelectType() || query.isDescribeType()) { Config config = new Config(request); ResultsFormat fmt = ResultsFormat.lookup(request.getParameter("format")); Dataset tdbstore = TDBFactory.createDataset(config.getTripleStoreDir()); QueryExecution qexec = QueryExecutionFactory.create(query, tdbstore); qexec.getContext().set(TDB.symUnionDefaultGraph, true); if(query.isSelectType()) { ResultSet results = qexec.execSelect(); if(fmt == null) { out.print(queryString+"\n"); ResultSetFormatter.out(out, results, query); } else ResultSetFormatter.output(out, results, fmt); } else { Model model = qexec.execDescribe(); RDFWriter rdfWriter = model.getWriter("RDF/XML-ABBREV"); rdfWriter.setProperty("showXmlDeclaration", "true"); rdfWriter.setProperty("tab", "6"); rdfWriter.write(model, out, null); } } else { out.print("Only select or describe queries allowed"); } }
public void tdbload() { Dataset dataset = TDBFactory.createDataset("tdb"); Model model = dataset.getNamedModel("fdg"); model.read("category_labels_en.nq"); if (model.READ){ System.out.println("right!!"); } Query q = QueryFactory.create(query); QueryExecution qe = QueryExecutionFactory.create(q, model); ResultSet rs = qe.execSelect(); ResultSetFormatter.out(rs); }
public void handleResultSet(ResultSet results, String method, TopicMap tm) throws Exception { if(results != null) { if("RESULTSET-RDF-TOPICMAP".equals(method)) { Model model = ResultSetFormatter.toModel(results); RDF2TopicMap(model, tm); } else { resultSet2TopicMap(results, tm); } } else { log("Warning: no result set available!"); } }
/** * Runs SPARQL queries * * @param type * Result Format: N3, N-TRIPLE, RDF/XML, RDF/XML-ABBREV, TURTLE * @param query * Sparql for the query * @return */ @GET @Produces({ WebUtil.MEDIA_TYPE_APPLICATION_NTRIPLE, WebUtil.MEDIA_TYPE_APPLICATION_RDFJSON, WebUtil.MEDIA_TYPE_APPLICATION_RDFXML, MediaType.TEXT_PLAIN, WebUtil.MEDIA_TYPE_TEXT_N3, WebUtil.MEDIA_TYPE_TEXT_TURTLE }) public Response selectQuery(@QueryParam("sparql") String query, @Context Request request) { Variant variant = request.selectVariant(WebUtil.VARIANTS); MediaType mediaType = variant.getMediaType(); Repository repository = RepositoryManager.getInstance().getRepository(); OntModel ontModel = repository.getMDRDatabase().getOntModel(); Query q = null; try { query = URLDecoder.decode(query, "UTF-8"); q = QueryFactory.create(query); } catch (Exception exc) { logger.error("Error during the creation of the SPARQL query", exc); return Response.serverError().build(); } QueryExecution qexec = QueryExecutionFactory.create(q, ontModel); Model resultModel = null; if (q.isSelectType()) { ResultSet resultSet = qexec.execSelect(); resultModel = ResultSetFormatter.toModel(resultSet); } else { throw new WebApplicationException(Status.UNAUTHORIZED); } qexec.close(); graphStream.setModel(resultModel); graphStream.setLanguage(WebUtil.getSerializationLanguage(mediaType .toString())); return Response.ok(graphStream).build(); }
@Override public Object execute(Map<String, EdmLiteral> parameters) throws ODataException { EdmLiteral query_lit = parameters.remove("query"); // Olingo2 checks for presence of non-nullable parameters for us! String query_s = query_lit.getLiteral(); Query query = QueryFactory.create(query_s); if (!(query.isSelectType() || query.isDescribeType())) { throw new InvalidOperationException(query.getQueryType()); } DrbCortexModel cortexmodel; try { cortexmodel = DrbCortexModel.getDefaultModel(); } catch (IOException ex) { throw new RuntimeException(ex); } Model model = cortexmodel.getCortexModel().getOntModel(); QueryExecution qexec = null; // FIXME: QueryExecution in newer versions of Jena (post apache incubation) implement AutoClosable. try { qexec = QueryExecutionFactory.create(query, model); if (query.isSelectType()) { ResultSet results = qexec.execSelect(); return ResultSetFormatter.asXMLString(results); } else { Model description = qexec.execDescribe(); // newer version of Jena have the RIOT package for I/O StringWriter strwrt = new StringWriter(); Abbreviated abb = new Abbreviated(); abb.write(description, strwrt, null); return strwrt.toString(); } } finally { if (qexec != null) { qexec.close(); } } }
private ResponseEntity<?> formatSelectOutput(ResultSet resultSet, int outputFormat) throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); HttpHeaders headers = new HttpHeaders(); switch (outputFormat) { case BygleSystemUtils.OUTPUTFORMAT_BIO: ResultSetFormatter.outputAsBIO(byteArrayOutputStream, resultSet); headers.add("Content-Type", "text/bio" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); headers.add("Content-Disposition", "attachment; filename=query.bio"); headers.add("Content-Length", Integer.toString(byteArrayOutputStream.toByteArray().length)); return new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK); case BygleSystemUtils.OUTPUTFORMAT_CSV: ResultSetFormatter.outputAsCSV(byteArrayOutputStream, resultSet); headers.add("Content-Type", "text/csv" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); headers.add("Content-Disposition", "attachment; filename=query.csv"); return new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK); case BygleSystemUtils.OUTPUTFORMAT_JSON: ResultSetFormatter.outputAsJSON(byteArrayOutputStream, resultSet); headers.add("Content-Type", "application/json" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); headers.add("Content-Disposition", "attachment; filename=query.json"); return new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK); case BygleSystemUtils.OUTPUTFORMAT_RDF: ResultSetFormatter.outputAsRDF(byteArrayOutputStream, "RDF/XML", resultSet); headers.add("Content-Type", "application/rdf+xml" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); headers.add("Content-Disposition", "attachment; filename=query.rdf"); return new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK); case BygleSystemUtils.OUTPUTFORMAT_RDF_ABBR: ResultSetFormatter.outputAsRDF(byteArrayOutputStream, "RDF/XML-ABBREV", resultSet); headers.add("Content-Type", "application/rdf+xml" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); headers.add("Content-Disposition", "attachment; filename=query.rdf"); return new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK); case BygleSystemUtils.OUTPUTFORMAT_TSV: ResultSetFormatter.outputAsTSV(byteArrayOutputStream, resultSet); headers.add("Content-Type", "text/tab-separated-values" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); headers.add("Content-Disposition", "attachment; filename=query.tsv"); return new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK); case BygleSystemUtils.OUTPUTFORMAT_XML: headers.add("Content-Type", "application/xml" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); headers.add("Content-Disposition", "attachment; filename=query.xml"); return new ResponseEntity<byte[]>(ResultSetFormatter.asXMLString(resultSet).getBytes(), headers, HttpStatus.OK); case BygleSystemUtils.OUTPUTFORMAT_N_TRIPLE: ResultSetFormatter.outputAsRDF(byteArrayOutputStream, "N-TRIPLE", resultSet); headers.add("Content-Type", "application/n-triples" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); headers.add("Content-Disposition", "attachment; filename=query.n3"); return new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK); case BygleSystemUtils.OUTPUTFORMAT_TURTLE: ResultSetFormatter.outputAsRDF(byteArrayOutputStream, "TURTLE", resultSet); headers.add("Content-Type", "text/turtle" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); headers.add("Content-Disposition", "attachment; filename=query.ttl"); return new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK); case BygleSystemUtils.OUTPUTFORMAT_HTML: headers.add("Content-Type", "text/html" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); return new ResponseEntity<byte[]>(TrasformXslt.xslt(ResultSetFormatter.asXMLString(resultSet), BygleSystemUtils.getXSLHTMLTController()).getBytes(), headers, HttpStatus.OK); default: headers.add("Content-Type", "text/html" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); return new ResponseEntity<byte[]>(TrasformXslt.xslt(ResultSetFormatter.asXMLString(resultSet), BygleSystemUtils.getXSLHTMLTController()).getBytes(), headers, HttpStatus.OK); } }
private ResponseEntity<?> formatAskOutput(boolean ask, int outputFormat) throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); HttpHeaders headers = new HttpHeaders(); switch (outputFormat) { case BygleSystemUtils.OUTPUTFORMAT_CSV: ResultSetFormatter.outputAsCSV(byteArrayOutputStream, ask); headers.add("Content-Type", "text/csv" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); headers.add("Content-Disposition", "attachment; filename=query.csv"); return new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK); case BygleSystemUtils.OUTPUTFORMAT_JSON: ResultSetFormatter.outputAsJSON(byteArrayOutputStream, ask); headers.add("Content-Type", "application/json" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); headers.add("Content-Disposition", "attachment; filename=query.json"); return new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK); case BygleSystemUtils.OUTPUTFORMAT_RDF: ResultSetFormatter.outputAsRDF(byteArrayOutputStream, "RDF/XML", ask); headers.add("Content-Type", "application/rdf+xml" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); headers.add("Content-Disposition", "attachment; filename=query.rdf"); return new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK); case BygleSystemUtils.OUTPUTFORMAT_RDF_ABBR: ResultSetFormatter.outputAsRDF(byteArrayOutputStream, "RDF/XML-ABBREV", ask); headers.add("Content-Type", "application/rdf+xml" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); headers.add("Content-Disposition", "attachment; filename=query.rdf"); return new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK); case BygleSystemUtils.OUTPUTFORMAT_TSV: ResultSetFormatter.outputAsTSV(byteArrayOutputStream, ask); headers.add("Content-Type", "text/tab-separated-values" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); headers.add("Content-Disposition", "attachment; filename=query.tsv"); return new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK); case BygleSystemUtils.OUTPUTFORMAT_XML: headers.add("Content-Type", "application/xml" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); headers.add("Content-Disposition", "attachment; filename=query.xml"); return new ResponseEntity<byte[]>(ResultSetFormatter.asXMLString(ask).getBytes(), headers, HttpStatus.OK); case BygleSystemUtils.OUTPUTFORMAT_N_TRIPLE: ResultSetFormatter.outputAsRDF(byteArrayOutputStream, "N-TRIPLE", ask); headers.add("Content-Type", "application/n-triples" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); headers.add("Content-Disposition", "attachment; filename=query.n3"); return new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK); case BygleSystemUtils.OUTPUTFORMAT_TURTLE: ResultSetFormatter.outputAsRDF(byteArrayOutputStream, "TURTLE", ask); headers.add("Content-Type", "text/turtle" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); headers.add("Content-Disposition", "attachment; filename=query.ttl"); return new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK); case BygleSystemUtils.OUTPUTFORMAT_HTML: headers.add("Content-Type", "text/html" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); return new ResponseEntity<byte[]>(TrasformXslt.xslt(ResultSetFormatter.asXMLString(ask), BygleSystemUtils.getXSLHTMLTController()).getBytes(), headers, HttpStatus.OK); default: headers.add("Content-Type", "text/html" + "; charset=" + BygleSystemUtils.getStringProperty("default.encoding")); return new ResponseEntity<byte[]>(TrasformXslt.xslt(ResultSetFormatter.asXMLString(ask), BygleSystemUtils.getXSLHTMLTController()).getBytes(), headers, HttpStatus.OK); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rdfread_write); TextView textView = (TextView) findViewById(R.id.rdfTextView); textView.setMovementMethod(new ScrollingMovementMethod()); // create tdb dataset File directory = new File(getFilesDir(), "tdb_dataset"); directory.delete(); directory.mkdir(); Dataset dataset = TDBFactory.createDataset(directory.getAbsolutePath()) ; dataset.begin(ReadWrite.WRITE); Model model = dataset.getDefaultModel(); // read a turtle file from assets and write them into a tdb backed model try { InputStream skos_ttl = getAssets().open("skos.ttl"); RDFDataMgr.read(model, skos_ttl, Lang.TURTLE); skos_ttl.close(); InputStream geosparql_rdf_xml = getAssets().open("geosparql_vocab_all.rdf"); RDFDataMgr.read(model, geosparql_rdf_xml, Lang.RDFXML); geosparql_rdf_xml.close(); } catch (IOException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } // add some example data String personURI = "http://somewhere/JohnSmith"; String fullName = "John Smith"; Resource johnSmith = model.createResource(personURI); johnSmith.addProperty(VCARD.FN, fullName); dataset.commit(); dataset.end(); // read from tdb and print triples dataset.begin(ReadWrite.READ); Query query = QueryFactory.create("SELECT * WHERE { ?s ?p ?o } LIMIT 2"); QueryExecution qexec = QueryExecutionFactory.create(query, model); ResultSet results = qexec.execSelect(); String resultString = ResultSetFormatter.asText(results); Log.d(TAG, resultString); StringWriter dump = new StringWriter(); RDFDataMgr.write(dump, dataset, RDFFormat.JSONLD_PRETTY); dataset.end(); dataset.close(); textView.setText(dump.toString()); }
/** * Sample query: "https://www.wikidata.org/wiki/Q6607" for guitar * @param id * @return DBPedia response */ public String getWikidataLabelById(String id) { String res = ""; ParameterizedSparqlString qs = new ParameterizedSparqlString( "" + "prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" + "prefix wd: <http://www.wikidata.org/entity/>\n" + "\n" + "select *\n" + "where {\n" + " wd:Q" + id + " rdfs:label ?label .\n" + " FILTER (LANG(?label) = 'en') .\n" + " }\n" + "LIMIT 1" ); // Literal labelLiteral = ResourceFactory.createLangLiteral( label, "en" ); // qs.setParam("label", labelLiteral); log.debug( qs ); QueryExecution exec = QueryExecutionFactory.sparqlService(SPARQL_ENDPOINT, qs.asQuery()); ResultSet resultSet = exec.execSelect(); // Normally you'd just do results = exec.execSelect(), but I want to // use this ResultSet twice, so I'm making a copy of it. ResultSet results = ResultSetFactory.copyResults( resultSet ); while ( results.hasNext() ) { // As RobV pointed out, don't use the `?` in the variable // name here. Use *just* the name of the variable. // System.out.println( results.next().get( "resource" )); QuerySolution resQs = results.next(); res = res + resQs.get( "resource" ) + "#"; res = res + resQs.get( "description" ); // System.out.println( resQs.get( "resource" )); // System.out.println( resQs.get( "description" )); } // A simpler way of printing the results. ResultSetFormatter.out( results ); // return results.toString(); if (res.equals("")) res = "#"; return res; }
/** * Sample query: "http://dbpedia.org/page/Chicago_blues" * @param label * @return DBPedia response */ public String queryDBPedia(String label) { String res = ""; ParameterizedSparqlString qs = new ParameterizedSparqlString( "" + "prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" + "\n" + "select ?resource ?description where {\n" + // " ?resource rdfs:label \"" + label + "\"@en .\n" + " ?resource rdfs:label ?label .\n" + " ?resource rdfs:comment ?description .\n" + " FILTER (LANG(?description) = 'en') .\n" + // "select ?resource where {\n" + // " ?resource rdfs:label ?label\n" + "}" ); Literal labelLiteral = ResourceFactory.createLangLiteral( label, "en" ); qs.setParam("label", labelLiteral); System.out.println( qs ); QueryExecution exec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", qs.asQuery()); // Normally you'd just do results = exec.execSelect(), but I want to // use this ResultSet twice, so I'm making a copy of it. ResultSet results = ResultSetFactory.copyResults( exec.execSelect() ); while ( results.hasNext() ) { // As RobV pointed out, don't use the `?` in the variable // name here. Use *just* the name of the variable. // System.out.println( results.next().get( "resource" )); QuerySolution resQs = results.next(); res = res + resQs.get( "resource" ) + "#"; res = res + resQs.get( "description" ); // System.out.println( resQs.get( "resource" )); // System.out.println( resQs.get( "description" )); } // A simpler way of printing the results. ResultSetFormatter.out( results ); // return results.toString(); if (res.equals("")) res = "#"; return res; }
/** * Sample query: "http://dbpedia.org/page/Chicago_blues" * @param label * @return DBPedia response */ public String queryDBPediaByLanguage(String label, String language) { String res = ""; ParameterizedSparqlString qs = new ParameterizedSparqlString( "" + "prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" + "\n" + "select ?resource ?description where {\n" + // " ?resource rdfs:label \"" + label + "\"@en .\n" + " ?resource rdfs:label ?label .\n" + " ?resource rdfs:comment ?description .\n" + " FILTER (LANG(?description) = '" + language + "') .\n" + // "select ?resource where {\n" + // " ?resource rdfs:label ?label\n" + "}" ); Literal labelLiteral = ResourceFactory.createLangLiteral( label, language ); qs.setParam("label", labelLiteral); System.out.println( qs ); QueryExecution exec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", qs.asQuery()); // Normally you'd just do results = exec.execSelect(), but I want to // use this ResultSet twice, so I'm making a copy of it. ResultSet results = ResultSetFactory.copyResults( exec.execSelect() ); while ( results.hasNext() ) { // As RobV pointed out, don't use the `?` in the variable // name here. Use *just* the name of the variable. // System.out.println( results.next().get( "resource" )); QuerySolution resQs = results.next(); res = res + resQs.get( "resource" ) + "#"; res = res + resQs.get( "description" ); // System.out.println( resQs.get( "resource" )); // System.out.println( resQs.get( "description" )); } // A simpler way of printing the results. ResultSetFormatter.out( results ); // return results.toString(); if (res.equals("")) res = "#"; return res; }
private static String buildRDF_JSON(Model RDFmodel) { // From http://www.w3.org/wiki/TriplesInJSON String queryString = "SELECT ?s ?p ?o " + "WHERE { ?s ?p ?o }"; Query q = QueryFactory.create(queryString); // Create a SPARQL-DL query execution for the given query and // ontology model QueryExecution qe = SparqlDLExecutionFactory.create(q, RDFmodel); // Print the query for better understanding System.out.println(q.toString()); // We want to execute a SELECT query, do it, and return the result set ResultSet resultSet = qe.execSelect(); ByteArrayOutputStream b = new ByteArrayOutputStream(); ResultSetFormatter.outputAsJSON(b, resultSet); String json = b.toString(); System.out.println(json); return json; }
public static String executar(String queryText) { Query query = QueryFactory.create(queryText); QueryExecution qExe = QueryExecutionFactory.sparqlService(Endpoint.getURL(), query); ResultSet results = qExe.execSelect(); return ResultSetFormatter.asText(results); }
public String getFormattedResults() { if (this.results == null) return "no query executed."; this.results.reset(); String formattedResults = ResultSetFormatter.asText(this.results); formattedResults = StringEscapeUtils.escapeXml(formattedResults); formattedResults = "<pre>" + formattedResults + "</pre>"; return formattedResults; }
public void executeQuery() { Query query = this.geraConsultaSPARQL(this.listaDePalavrasParaPesquisa); QueryExecution qe = QueryExecutionFactory.create(query, this.getOntologia()); ResultSet results = qe.execSelect(); this.lstResultados = ResultSetFormatter.toList(results); qe.close(); }