Java Code Examples for org.apache.jena.query.ResultSet#next()
The following examples show how to use
org.apache.jena.query.ResultSet#next() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DatasetGenerator.java From NLIWOD with GNU Affero General Public License v3.0 | 6 votes |
private static void updateGoldenAnswers(QueryExecutionFactory qef, IQuestion q) { Set<String> uris = new HashSet<>(); if (null != q && null != q.getSparqlQuery() && !q.getSparqlQuery().contains("ASK")) { try (QueryExecution qe = qef.createQueryExecution(q.getSparqlQuery())) { ResultSet rs = qe.execSelect(); while (rs.hasNext()) { QuerySolution qs = rs.next(); RDFNode node = qs.get("uri"); if (node != null && node.isResource()) { uris.add(node.asResource().getURI()); } } } q.setGoldenAnswers(uris); } else {// TODO what happens if q is null? } }
Example 2
Source File: TripleIndexCreatorContext.java From AGDISTIS with GNU Affero General Public License v3.0 | 6 votes |
public String sparql(String subject) { // First query takes the most specific class from a given resource. String ontology_service = endpoint; String endpointsSparql = "select ?label where {<" + subject + "> <http://www.w3.org/2000/01/rdf-schema#label> ?label FILTER (lang(?label) = 'en')} LIMIT 100"; Query sparqlQuery = QueryFactory.create(endpointsSparql, Syntax.syntaxARQ); QueryEngineHTTP qexec = (QueryEngineHTTP) QueryExecutionFactory.sparqlService(ontology_service, sparqlQuery); qexec.setModelContentType(WebContent.contentTypeRDFXML); ResultSet results = qexec.execSelect(); String property = null; while (results.hasNext()) { QuerySolution qs = results.next(); property = qs.getLiteral("?label").getLexicalForm(); } return property; }
Example 3
Source File: DB2DescribeHandler.java From quetzal with Eclipse Public License 2.0 | 6 votes |
public void describe(Resource r) { // Default model. DB2Closure.closure(otherModel(r, dataset.getDefaultModel()), false, acc, resources); String query = "SELECT ?g { GRAPH ?g { <" + r.getURI() + "> ?p ?o } }"; QueryExecution qExec = RdfStoreQueryExecutionFactory.create(query, dataset); ResultSet rs = qExec.execSelect(); for (; rs.hasNext();) { QuerySolution qs = rs.next(); String gName = qs.getResource("g").getURI(); // mdb for DB2 Model model = dataset.getNamedModel(gName); Resource r2 = otherModel(r, model); DB2Closure.closure(r2, false, acc, resources); } qExec.close(); DB2Closure.closure(r, false, acc, resources); }
Example 4
Source File: TestAnnotationTools.java From incubator-taverna-language with Apache License 2.0 | 6 votes |
@Test public void componentStuff() throws Exception { Dataset dataset = annotations.annotationDatasetFor(component.getMainWorkflow()); String query = "PREFIX comp: <http://purl.org/DP/components#> " + "SELECT ?fits ?from ?to WHERE { " + " GRAPH ?any { " + "?w comp:fits ?fits ; " + " comp:migrates ?path . " + "?path comp:fromMimetype ?from ; " + " comp:toMimetype ?to . " + " }" + "}"; ResultSet select = QueryExecutionFactory.create(query, dataset).execSelect(); assertTrue(select.hasNext()); QuerySolution solution = select.next(); assertEquals("image/tiff", solution.getLiteral("from").toString()); assertEquals("image/tiff", solution.getLiteral("to").toString()); assertEquals("MigrationAction", solution.getResource("fits").getLocalName()); }
Example 5
Source File: JenaQuery.java From trainbenchmark with Eclipse Public License 1.0 | 6 votes |
@SuppressWarnings("unchecked") @Override public Collection<TPatternMatch> evaluate() throws IOException { final List<TPatternMatch> matches = new ArrayList<>(); try (QueryExecution queryExecution = QueryExecutionFactory.create(jenaQuery, driver.getModel())) { final ResultSet resultSet = queryExecution.execSelect(); while (resultSet.hasNext()) { final QuerySolution qs = resultSet.next(); final JenaMatch match = JenaMatch.createMatch(query, qs); matches.add((TPatternMatch) match); } } return matches; }
Example 6
Source File: JenaUtil.java From shacl with Apache License 2.0 | 6 votes |
/** * Calls a SPARQL expression and returns the result, using some initial bindings. * * @param expression the expression to execute (must contain absolute URIs) * @param initialBinding the initial bindings for the unbound variables * @param dataset the query Dataset or null for default * @return the result or null */ public static Node invokeExpression(String expression, QuerySolution initialBinding, Dataset dataset) { if (dataset == null) { dataset = ARQFactory.get().getDataset(ModelFactory.createDefaultModel()); } Query query = ARQFactory.get().createExpressionQuery(expression); try(QueryExecution qexec = ARQFactory.get().createQueryExecution(query, dataset, initialBinding)) { ResultSet rs = qexec.execSelect(); Node result = null; if (rs.hasNext()) { QuerySolution qs = rs.next(); String firstVarName = rs.getResultVars().get(0); RDFNode rdfNode = qs.get(firstVarName); if (rdfNode != null) { result = rdfNode.asNode(); } } return result; } }
Example 7
Source File: ITER_Call_Select.java From sparql-generate with Apache License 2.0 | 6 votes |
private List<List<NodeValue>> getListNodeValues(ResultSet result) { List<String> resultVars = result.getResultVars(); List<List<NodeValue>> listNodeValues = new ArrayList<>(); while (result.hasNext()) { List<NodeValue> nodeValues = new ArrayList<>(); QuerySolution sol = result.next(); for (String var : resultVars) { RDFNode rdfNode = sol.get(var); if (rdfNode != null) { NodeValue n = new NodeValueNode(rdfNode.asNode()); nodeValues.add(n); } else { nodeValues.add(null); } } listNodeValues.add(nodeValues); } return listNodeValues; }
Example 8
Source File: SPARQLExtIteratorFunction.java From sparql-generate with Apache License 2.0 | 6 votes |
private List<List<NodeValue>> getListNodeValues(ResultSet result) { List<String> resultVars = result.getResultVars(); List<List<NodeValue>> listNodeValues = new ArrayList<>(); while (result.hasNext()) { List<NodeValue> nodeValues = new ArrayList<>(); QuerySolution sol = result.next(); for (String var : resultVars) { RDFNode rdfNode = sol.get(var); if (rdfNode != null) { NodeValue n = new NodeValueNode(rdfNode.asNode()); nodeValues.add(n); } else { nodeValues.add(null); } } listNodeValues.add(nodeValues); } return listNodeValues; }
Example 9
Source File: EntitySPARQLReader.java From JedAIToolkit with Apache License 2.0 | 5 votes |
private void readEndpoint(String endpointUrl) throws IOException { //read each ntriples //get spo, create a separate profile for each separate subject, //with Attribute=predicate and Value=object final String sparqlQueryString1 = "select ?a ?b ?c where {?a ?b ?c}"; final Query query = QueryFactory.create(sparqlQueryString1); try (QueryExecution qexec = QueryExecutionFactory.sparqlService(endpointUrl, query)) { final ResultSet results = qexec.execSelect(); //ResultSetFormatter.out(System.out, results, query); //results = qexec.execSelect(); while (results.hasNext()) { final QuerySolution qs = results.next(); final String sub = qs.get("a").toString(); final String pred = qs.get("b").toString(); final String obj = qs.get("c").toString(); if (attributesToExclude.contains(pred)) { continue; } //if already exists a profile for the subject, simply add po as <Att>-<Value> EntityProfile entityProfile = urlToEntity.get(sub); if (entityProfile == null) { entityProfile = new EntityProfile(sub); entityProfiles.add(entityProfile); urlToEntity.put(sub, entityProfile); } if (!obj.isEmpty()) { entityProfile.addAttribute(pred, obj); } } } //ResultSetFormatter.out(System.out, results, query); //results = qexec.execSelect(); }
Example 10
Source File: JenaDriver.java From trainbenchmark with Eclipse Public License 1.0 | 5 votes |
public Collection<QuerySolution> runQuery(final RailwayQuery query, final String queryDefinition) throws IOException { final Collection<QuerySolution> results = new ArrayList<>(); try (QueryExecution queryExecution = QueryExecutionFactory.create(queryDefinition, model)) { final ResultSet resultSet = queryExecution.execSelect(); while (resultSet.hasNext()) { final QuerySolution qs = resultSet.next(); results.add(qs); } } return results; }
Example 11
Source File: ClassSurfaceForms.java From NLIWOD with GNU Affero General Public License v3.0 | 5 votes |
public static void main(String[] args) throws IOException, InterruptedException { CLASS_SURFACE_FORMS = DIRECTORY + "class_surface_forms.ttl"; // create an empty model Model inputModel = ModelFactory.createDefaultModel(); // use the FileManager to find the input file InputStream in = FileManager.get().open(DBPEDIA_CLASSE_FILE); if (in == null) { throw new IllegalArgumentException("File: " + DBPEDIA_CLASSE_FILE + " not found"); } // read the RDF/XML file inputModel.read(in, null, "N-TRIPLE"); Model outputModel = ModelFactory.createDefaultModel(); QueryExecution qExec = QueryExecutionFactory .create("SELECT ?s ?label WHERE{?s a <http://www.w3.org/2002/07/owl#Class>." + " ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label. " + "FILTER (lang(?label) = \"en\")}", inputModel); ResultSet rs = qExec.execSelect(); while (rs.hasNext()) { QuerySolution qs = rs.next(); Resource uri = qs.get("?s").asResource(); RDFNode label = qs.get("?label"); StatementImpl s = new StatementImpl(uri, RDFS.label, label); outputModel.add(s); } qExec.close(); FileOutputStream outputFile = new FileOutputStream(CLASS_SURFACE_FORMS); RDFDataMgr.write(outputFile, outputModel, RDFFormat.NTRIPLES); }
Example 12
Source File: DBPediaService.java From baleen with Apache License 2.0 | 5 votes |
private Set<DefaultCandidate> getCandidates(ResultSet rs, String idField, String nameField) { Set<DefaultCandidate> candidates = new HashSet<>(); while (rs.hasNext()) { QuerySolution qs = rs.next(); Map<String, String> fieldsMap = new HashMap<>(); qs.varNames() .forEachRemaining( varName -> fieldsMap.put(varName, new DBPediaLanguageString(qs.get(varName)).raw())); DBPediaLanguageString id = new DBPediaLanguageString(qs.get(idField)); DBPediaLanguageString name = new DBPediaLanguageString(qs.get(nameField)); candidates.add(new DefaultCandidate(id.raw(), name.raw(), fieldsMap)); } return candidates; }
Example 13
Source File: PropertySurfaceForms.java From NLIWOD with GNU Affero General Public License v3.0 | 5 votes |
public static void main(String[] args) throws IOException, InterruptedException { PROPERTY_SURFACE_FORMS = DIRECTORY + "property_surface_forms.ttl"; // create an empty model Model inputModel = ModelFactory.createDefaultModel(); // use the FileManager to find the input file InputStream in = FileManager.get().open(DBPEDIA_PROPERTY_FILE); if (in == null) { throw new IllegalArgumentException("File: " + DBPEDIA_PROPERTY_FILE + " not found"); } // read the RDF/XML file inputModel.read(in, null, "N-TRIPLE"); inputModel.write(System.out); Model outputModel = ModelFactory.createDefaultModel(); QueryExecution qExec = QueryExecutionFactory .create("SELECT ?s ?label WHERE{?s a <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property>." + " ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label. }", inputModel); ResultSet rs = qExec.execSelect(); System.out.println(qExec); while (rs.hasNext()) { QuerySolution qs = rs.next(); Resource uri = qs.get("?s").asResource(); RDFNode label = qs.get("?label"); StatementImpl s = new StatementImpl(uri, RDFS.label, label); outputModel.add(s); } qExec.close(); FileOutputStream outputFile = new FileOutputStream(PROPERTY_SURFACE_FORMS); RDFDataMgr.write(outputFile, outputModel, RDFFormat.NTRIPLES); }
Example 14
Source File: QUEPY.java From NLIWOD with GNU Affero General Public License v3.0 | 4 votes |
/** * Overriding Original search method to implement Quepy's two step requests for * QA */ @Override public void search(IQuestion question, String language) throws Exception { String questionString; if (!question.getLanguageToQuestion().containsKey(language)) { return; } questionString = question.getLanguageToQuestion().get(language); log.debug(this.getClass().getSimpleName() + ": " + questionString); this.getParamMap().put(this.getQueryKey(), questionString); if (this.setLangPar) { this.getParamMap().put(this.getLangKey(), language); } HttpResponse response = this.getIsPostReq() ? fetchPostResponse(getUrl(), getParamMap()) : fetchGetResponse(getUrl(), getParamMap()); // Test if error occured if (response.getStatusLine().getStatusCode() >= 400) { throw new Exception("QUEPY Server could not answer due to: " + response.getStatusLine()); } // Fetch the SPARQL String sparqlStr = null; JSONParser parser = new JSONParser(); JSONObject responsejson = (JSONObject) parser.parse(responseparser.responseToString(response)); JSONArray queriesArr = (JSONArray) responsejson.get("queries"); for (int i = 0; i < queriesArr.size(); i++) { JSONObject queryObj = (JSONObject) queriesArr.get(i); if (queryObj.get("language").toString().equalsIgnoreCase("sparql") && queryObj.get("query") != null) { sparqlStr = queryObj.get("query").toString(); break; } } if (sparqlStr != null) { HashSet<String> result = new HashSet<String>(); question.setSparqlQuery(sparqlStr); // Fetch results using sparql Query query = QueryFactory.create(sparqlStr); // Remote execution. QueryExecution qexec = QueryExecutionFactory.sparqlService(SPARQL_ENDPOINT, query); // Set the DBpedia specific timeout. ((QueryEngineHTTP) qexec).addParam("timeout", "10000"); // Execute. ResultSet rs = qexec.execSelect(); // Get the values and push them to the question while (rs.hasNext()) { QuerySolution qs = rs.next(); Iterator<String> varIt = qs.varNames(); while (varIt.hasNext()) { RDFNode node = qs.get(varIt.next()); result.add(node.asLiteral().getString()); } } question.setGoldenAnswers(result); } }
Example 15
Source File: CorrectnessTask.java From IGUANA with GNU Affero General Public License v3.0 | 4 votes |
private double[] compare(JSONObject expectedResults, ResultSet systemResults) { double[] rawDouble = new double[] { 0, 0, 0 }; JSONArray bindings = (JSONArray) ((JSONObject) expectedResults.get("results")).get("bindings"); if (systemResults == null) { rawDouble[2] = bindings.size(); return rawDouble; } Set<Integer> alreadySet = new HashSet<Integer>(); while (systemResults.hasNext()) { QuerySolution solution = systemResults.next(); boolean equals = true; //check for each bindings if the solution exists for (int i = 0; i < bindings.size(); i++) { //if the binding is already set continue if (alreadySet.contains(i)) { continue; } JSONObject binding = (JSONObject) bindings.get(i); equals = true; //check for each var if the solution is the same as the expected for (String varName : systemResults.getResultVars()) { RDFNode solutionNode = solution.get(varName); JSONObject varBinding = (JSONObject) binding.get(varName); equals &= compareNodes(solutionNode, varBinding); } if (equals) { // found solution alreadySet.add(i); break; } } if (equals) { rawDouble[0]++; } else { rawDouble[1]++; } } rawDouble[2] = bindings.size() - alreadySet.size(); return rawDouble; }
Example 16
Source File: PatternQueryHandler.java From IGUANA with GNU Affero General Public License v3.0 | 4 votes |
protected Set<String> getInstances(String queryStr) { Set<String> instances = new HashSet<String>(); //check if query is already an instance try{ QueryFactory.create(queryStr); //query is instance LOGGER.debug("[QueryHandler: {{}}] Query is already an instance: {{}}", this.getClass().getName(), queryStr); instances.add(queryStr); return instances; }catch(Exception e) { //query is pattern, nothing to do } //get vars from queryStr Set<String> varNames = new HashSet<String>(); String command = replaceVars(queryStr, varNames); //generate parameterized sparql query ParameterizedSparqlString pss = new ParameterizedSparqlString(); pss.setCommandText(command); ResultSet exchange = getInstanceVars(pss, varNames); System.out.println("instaces retrieved"); // exchange vars in PSS if(!exchange.hasNext()) { //no solution System.out.println("No solution"); LOGGER.warn("[QueryHandler: {{}}] Query has no solution, will use variables instead of var instances: {{}}", this.getClass().getName(), queryStr); instances.add(command); } while(exchange.hasNext()) { QuerySolution solution = exchange.next(); for(String var : exchange.getResultVars()) { //exchange variable with pss.clearParam(var); pss.setParam(var, solution.get(var)); } instances.add(pss.toString()); } System.out.println("Found instances "+instances); return instances; }
Example 17
Source File: DatasetGenerator.java From NLIWOD with GNU Affero General Public License v3.0 | 4 votes |
private void evaluate(Set<String>answers,Query query,String question){ QueryExecution qe = qef.createQueryExecution(query); LOGGER.debug(query.toString()); LOGGER.debug("Question:"+ question); double truepositive=0; double falsepositive=0; try { ResultSet rs = qe.execSelect(); while (rs.hasNext()) { QuerySolution qs = rs.next(); RDFNode node = qs.get("s"); if (node != null && node.isResource()) { String resourceString = (node.asResource().toString().replace(NAMESPACE, "")); resourceString = resourceString.replace(NAMESPACE2, ""); if (answers.contains(resourceString)) { truepositive++; //LOGGER.debug("truepositive: " + resourceString); } else { falsepositive++; //LOGGER.debug("falsepositive: " + resourceString); } } } }catch(Exception e){ LOGGER.error("Executing SPARQL Query"+query.toString()+"failed"); } if(truepositive>0||falsepositive>0) { double falsenegative = answers.size() - truepositive; double recall = truepositive / (truepositive + falsepositive); double precision = truepositive / (truepositive + falsenegative); double accuracy = truepositive / (truepositive + falsenegative + falsepositive); double f1 = 2 * (precision * recall) / (precision + recall); if(f1==1.0) correct++; if(Double.isNaN(f1)) f1=0.0; f1sum+=f1; if(Double.isNaN(accuracy)) accuracy=0.0; accsum+=accuracy; LOGGER.debug("Evaluation: tp:" + truepositive + " fp:" + falsepositive + " fn:" + falsenegative + " recall:" + recall + " precision:" + precision + " f1:" + f1 + " accuracy:" + accuracy); evaluation.add(new String[]{question, truepositive + "", falsepositive + "" , falsenegative + "", recall + "", precision + "", f1 + "", accuracy + ""}); } else{ LOGGER.debug("No results for question: "+question); f1sum+=0.0; accsum+=0.0; evaluation.add(new String[]{question,"0.0","0.0","0.0","0.0","0.0","0.0","0.0"}); } }
Example 18
Source File: AggregatedTestExecutor.java From RDFUnit with Apache License 2.0 | 4 votes |
private int getCountNumber(QueryExecutionFactory model, Query query, String var) { checkNotNull(query); checkNotNull(var); int result = 0; try ( QueryExecution qe = model.createQueryExecution(query) ) { ResultSet results = qe.execSelect(); if (results != null && results.hasNext()) { QuerySolution qs = results.next(); result = qs.get(var).asLiteral().getInt(); } } return result; }