Java Code Examples for org.apache.jena.query.QuerySolution#get()

The following examples show how to use org.apache.jena.query.QuerySolution#get() . 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: SPARQLDataReader.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private void parseResultSet(DataStore dataStore, MetaData dataStoreMeta, ResultSet resultSet) {
	List<String> columnNames = resultSet.getResultVars();
	for (; resultSet.hasNext();) {
		QuerySolution row = resultSet.nextSolution();
		IRecord record = new Record(dataStore);
		for (int i = 0; i < columnNames.size(); i++) {
			IFieldMetaData fieldMeta = dataStoreMeta.getFieldMeta(i);

			String columnName = columnNames.get(i);
			RDFNode rdfNode = row.get(columnName);
			getValue(rdfNode, record);
			getMetaData(rdfNode, fieldMeta);
		}
		dataStore.appendRecord(record);
	}
}
 
Example 2
Source File: SHACLSPARQLARQFunction.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
   public NodeValue executeBody(Dataset dataset, Model defaultModel, QuerySolution bindings) {
    try( QueryExecution qexec = createQueryExecution(dataset, defaultModel, bindings) ) {
        if(arqQuery.isAskType()) {
            boolean result = qexec.execAsk();
            return NodeValue.makeBoolean(result);
        }
        else {
            ResultSet rs = qexec.execSelect();
            if(rs.hasNext()) {
                QuerySolution s = rs.nextSolution();
                List<String> resultVars = rs.getResultVars();
                String varName = resultVars.get(0);
                RDFNode resultNode = s.get(varName);
                if(resultNode != null) {
                    return NodeValue.makeNode(resultNode.asNode());
                }
            }
            throw new ExprEvalException("Empty result set for SHACL function");
        }
    }
}
 
Example 3
Source File: JenaUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * 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 4
Source File: JenaUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Turns a QuerySolution into a Binding. 
 * @param map  the input QuerySolution
 * @return a Binding or null if the input is null
 */
public static Binding asBinding(final QuerySolution map) {
	if(map != null) {
		BindingHashMap result = new BindingHashMap();
		Iterator<String> varNames = map.varNames();
		while(varNames.hasNext()) {
			String varName = varNames.next();
			RDFNode node = map.get(varName);
			if(node != null) {
				result.add(Var.alloc(varName), node.asNode());
			}
		}
		return result;
	}
	else {
		return null;
	}
}
 
Example 5
Source File: ITER_Call_Select.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
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 6
Source File: SPARQLExtIteratorFunction.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
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 7
Source File: DatasetGenerator.java    From NLIWOD with GNU Affero General Public License v3.0 6 votes vote down vote up
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 8
Source File: PropertySurfaceForms.java    From NLIWOD with GNU Affero General Public License v3.0 5 votes vote down vote up
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 9
Source File: QueryAnswerTypeAnalyzer.java    From NLIWOD with GNU Affero General Public License v3.0 5 votes vote down vote up
/***
 * Queries the DBpedia SPARQL endpoint for the range of the given property.
 * @param property
 * @return range of the property
 */
private String queryRange(String property) {	
	String q = "PREFIX rdfs:   <http://www.w3.org/2000/01/rdf-schema#> SELECT ?x {<" + property + "> rdfs:range ?x.  }";	
	QueryExecution qe = QueryExecutionFactory.sparqlService(SERVICE, q);
	ResultSet rs = qe.execSelect();	
	if(rs.hasNext()) {
		QuerySolution solution = rs.nextSolution();			
		RDFNode node = solution.get("?x");	
		return node.toString();
	}	
	return "Misc";
}
 
Example 10
Source File: SPARQLSubstitutions.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static Literal withSubstitutions(Literal template, QuerySolution bindings, Function<RDFNode,String> labelFunction) {
	StringBuffer buffer = new StringBuffer();
	String labelTemplate = template.getLexicalForm();
	for(int i = 0; i < labelTemplate.length(); i++) {
		if(i < labelTemplate.length() - 3 && labelTemplate.charAt(i) == '{' && (labelTemplate.charAt(i + 1) == '?' || labelTemplate.charAt(i + 1) == '$')) {
			int varEnd = i + 2;
			while(varEnd < labelTemplate.length()) {
				if(labelTemplate.charAt(varEnd) == '}') {
					String varName = labelTemplate.substring(i + 2, varEnd);
					RDFNode varValue = bindings.get(varName);
					if(varValue != null) {
						if(labelFunction != null) {
							buffer.append(labelFunction.apply(varValue));
						}
						else if(varValue instanceof Resource) {
							buffer.append(RDFLabels.get().getLabel((Resource)varValue));
						}
						else if(varValue instanceof Literal) {
							buffer.append(varValue.asNode().getLiteralLexicalForm());
						}
					}
					break;
				}
				else {
					varEnd++;
				}
			}
			i = varEnd;
		}
		else {
			buffer.append(labelTemplate.charAt(i));
		}
	}
	if(template.getLanguage().isEmpty()) {
		return ResourceFactory.createTypedLiteral(buffer.toString());
	}
	else {
		return ResourceFactory.createLangLiteral(buffer.toString(), template.getLanguage());
	}
}
 
Example 11
Source File: TextOutputStar.java    From RDFstarTools with Apache License 2.0 5 votes vote down vote up
@Override
protected String getVarValueAsString(QuerySolution rBind, String varName) {
    final RDFNode obj = rBind.get(varName);

    if ( obj == null ) {
        return super.getVarValueAsString(rBind, varName);
    }
    else if ( obj.asNode() instanceof Node_Triple ) {
    	final Triple t = ( (Node_Triple) obj.asNode() ).get();
    	return getAsString(t);
    }
    else {
    	return FmtUtils.stringForRDFNode(obj, context);
    }
}
 
Example 12
Source File: TestCaseWithTarget.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
@Override
public RDFNode getFocusNode(QuerySolution solution) {

    String focusVar = getVariableAnnotations().stream()
            .filter(ra -> ra.getAnnotationProperty().equals(SHACL.focusNode))
            .map(ResultAnnotation::getAnnotationVarName)
            .filter(Optional::isPresent)
            .map(Optional::get)
            .findFirst()
            .orElse(CommonNames.This);
    return solution.get(focusVar);
}
 
Example 13
Source File: DBPediaService.java    From baleen with Apache License 2.0 5 votes vote down vote up
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 14
Source File: ManualTestCaseImpl.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
@Override
public RDFNode getFocusNode(QuerySolution solution) {
    String focusVar = getVariableAnnotations().stream()
            .filter(ra -> ra.getAnnotationProperty().equals(SHACL.focusNode))
            .map(ResultAnnotation::getAnnotationVarName)
            .filter(Optional::isPresent)
            .map(Optional::get)
            .findFirst()
            .orElse(CommonNames.This);
    return solution.get(focusVar);
}
 
Example 15
Source File: AlwaysFailingTestCase.java    From RDFUnit with Apache License 2.0 4 votes vote down vote up
@Override
public RDFNode getFocusNode(QuerySolution solution){
    return solution.get(CommonNames.This);
}
 
Example 16
Source File: QUEPY.java    From NLIWOD with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 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 17
Source File: DatasetGenerator.java    From NLIWOD with GNU Affero General Public License v3.0 4 votes vote down vote up
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: CorrectnessTask.java    From IGUANA with GNU Affero General Public License v3.0 4 votes vote down vote up
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 19
Source File: TagRdfUnitTestGenerator.java    From RDFUnit with Apache License 2.0 4 votes vote down vote up
private Optional<TestCase> generateTestFromResult(TestGenerator tg, Pattern tgPattern, QuerySolution row, SchemaSource schemaSource) {
    Set<String> references = new HashSet<>();
    String description;

    Collection<Binding> bindings = new ArrayList<>();
    for (PatternParameter p : tgPattern.getParameters()) {
        if (row.contains(p.getId())) {
            RDFNode n = row.get(p.getId());
            Binding b;
            try {
                b = new Binding(p, n);
            } catch (NullPointerException | IllegalArgumentException e) {
                log.error("Non valid binding for parameter {} in AutoGenerator: {}", p.getId(), tg.getUri(), e);
                continue;
            }
            bindings.add(b);
            if (n.isResource() && !"loglevel".equalsIgnoreCase(p.getId())) {
                references.add(n.toString().trim().replace(" ", ""));
            }
        } else {
            log.error("Not bindings for parameter {} in AutoGenerator: {}", p.getId(), tg.getUri());
            break;
        }
    }
    if (bindings.size() != tg.getPattern().getParameters().size()) {
        log.error("Bindings for pattern {} do not match in AutoGenerator: {}", tgPattern.getId(), tg.getUri());
        return Optional.empty();
    }

    if (row.get("DESCRIPTION") != null) {
        description = row.get("DESCRIPTION").toString();
    } else {
        log.error("No ?DESCRIPTION variable found in AutoGenerator: {}", tg.getUri());
        return Optional.empty();
    }


    Set<ResultAnnotation> patternBindedAnnotations = tgPattern.getBindedAnnotations(bindings);
    patternBindedAnnotations.addAll(tg.getAnnotations());
    Resource tcResource = ResourceFactory.createResource(TestUtils.generateTestURI(schemaSource.getPrefix(), tgPattern, bindings, tg.getUri()));
    PatternBasedTestCaseImpl tc = new PatternBasedTestCaseImpl(
            tcResource,
            new TestCaseAnnotation(
                    tcResource,
                    TestGenerationType.AutoGenerated,
                    tg.getUri(),
                    schemaSource.getSourceType(),
                    schemaSource.getUri(),
                    references,
                    description,
                    null,
                    patternBindedAnnotations),
            tgPattern,
            bindings
    );
    new TestCaseValidator(tc).validate();
    return Optional.of(tc);
}
 
Example 20
Source File: PatternBasedTestCaseImpl.java    From RDFUnit with Apache License 2.0 4 votes vote down vote up
@Override
public RDFNode getFocusNode(QuerySolution solution) {
    return solution.get(this.focusNodeVarName);
}