Java Code Examples for org.apache.jena.query.ResultSet#hasNext()

The following examples show how to use org.apache.jena.query.ResultSet#hasNext() . 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: TripleIndexCreatorContext.java    From AGDISTIS with GNU Affero General Public License v3.0 6 votes vote down vote up
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 2
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 3
Source File: CombineManifest.java    From incubator-taverna-language with Apache License 2.0 6 votes vote down vote up
private static List<RDFNode> creatingAgentsFor(Resource r) {
	logger.fine("Finding creator of " + r);
	String queryStr = sparqlPrefixes + "SELECT ?agent WHERE { \n" + " { \n"
			+ "  ?r dct:creator [ \n" + "	    rdfs:member ?agent \n"
			+ "  ] \n" + " } UNION { \n" + "   ?r dct:creator ?agent .\n "
			+ "   FILTER NOT EXISTS { ?agent rdfs:member ?member } \n"
			+ " } \n" + "} \n";
	logger.finer(QueryFactory.create(queryStr).toString());
	QueryExecution qexec = QueryExecutionFactory.create(queryStr,
			r.getModel());
	QuerySolutionMap binding = new QuerySolutionMap();
	binding.add("r", r);
	qexec.setInitialBinding(binding);
	ResultSet select = qexec.execSelect();
	List<RDFNode> agents = new ArrayList<>();

	while (select.hasNext()) {
		RDFNode agent = select.next().get("agent");
		logger.fine("Found: " + agent);
		agents.add(agent);
	}
	return agents;
}
 
Example 4
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 5
Source File: CombineManifest.java    From incubator-taverna-language with Apache License 2.0 6 votes vote down vote up
private static Resource mboxForAgent(Resource agentResource) {
	logger.fine("Finding mbox of " + agentResource);
	String queryStr = sparqlPrefixes + "SELECT ?mbox WHERE { \n"
			+ "		{ ?agent foaf:mbox ?mbox } \n" + "	UNION  \n"
			+ "		{ ?agent vcard:hasEmail ?mbox } \n" + "	UNION  \n"
			+ "		{ ?agent vcard:email ?email .  \n"
			+ "       BIND(IRI(CONCAT(\"mbox:\", ?email)) AS ?mbox) \n" // legacy
			+ "	    } \n" + "} \n";
	logger.finer(QueryFactory.create(queryStr).toString());
	QueryExecution qexec = QueryExecutionFactory.create(queryStr,
			agentResource.getModel());
	QuerySolutionMap binding = new QuerySolutionMap();
	binding.add("agent", agentResource);
	qexec.setInitialBinding(binding);
	ResultSet select = qexec.execSelect();
	if (select.hasNext()) {
		Resource mbox = select.next().getResource("mbox");
		logger.fine("Found mbox: " + mbox);
		return mbox;
	}
	logger.fine("mbox not found");
	return null;
}
 
Example 6
Source File: TarqlTest.java    From tarql with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void assertSelect(TarqlQuery tq, Binding... bindings) throws IOException{
	TarqlQueryExecution ex;
	if (csv == null) {
		ex = TarqlQueryExecutionFactory.create(tq, options);
	} else {
		ex = TarqlQueryExecutionFactory.create(tq, InputStreamSource.fromBytes(csv.getBytes("utf-8")), options);
	}
	ResultSet rs = ex.execSelect();
	int counter = 0;
	while (rs.hasNext()) {
		if (counter >= bindings.length) {
			fail("Too many bindings in result; expected " + bindings.length);
		}
		assertEquals(bindings[counter], rs.nextBinding());
		counter += 1;
	}
	assertEquals(bindings.length, counter);
}
 
Example 7
Source File: ExTDB5.java    From xcurator with Apache License 2.0 6 votes vote down vote up
public static void main(String... argv)
{
    // Direct way: Make a TDB-back Jena model in the named directory.
    String directory = "MyDatabases/DB1" ;
    Dataset dataset = TDBFactory.createDataset(directory) ;
    
    // Potentially expensive query.
    String sparqlQueryString = "SELECT (count(*) AS ?count) { ?s ?p ?o }" ;
    // See http://incubator.apache.org/jena/documentation/query/app_api.html
    
    Query query = QueryFactory.create(sparqlQueryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, dataset) ;
    try {
      ResultSet results = qexec.execSelect() ;
      for ( ; results.hasNext() ; )
      {
          QuerySolution soln = results.nextSolution() ;
          int count = soln.getLiteral("count").getInt() ;
          System.out.println("count = "+count) ;
      }
    } finally { qexec.close() ; }

    // Close the dataset.
    dataset.close();
    
}
 
Example 8
Source File: OneM2MSubscribeUriMapper.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * subscribe uri 가져오기
 * @return List<String>
 */
public List<String> getSubscribeUri() {
	List<String> result = new ArrayList<String>();
	String query = this.makeQueryString();
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.dw.sparql.endpoint");
	String baseuri = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.uri");
	QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, query);
	ResultSet rs = queryExec.execSelect();
	for (; rs.hasNext();) {
		QuerySolution qs = rs.nextSolution();
		result.add(getProperContainerType(
				new String(qs.get("res").toString().replaceAll(baseuri, ""))));
	}
	return result;
}
 
Example 9
Source File: OneM2MSubscribeUriMapper.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public List<String> getSubscribeUri() {
	List<String> result = new ArrayList<String>();
	String query = this.makeQueryString();
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.sparql.endpoint");
	String baseuri = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.uri");
	QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, query);
	ResultSet rs = queryExec.execSelect();
	for (; rs.hasNext();) {
		QuerySolution qs = rs.nextSolution();
		result.add(getProperContainerType(
				new String(qs.get("uri").toString().replaceAll(baseuri, ""))));
	}
	return result;
}
 
Example 10
Source File: AbstractSPARQLExpression.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
public ExtendedIterator<RDFNode> eval(RDFNode focusNode, NodeExpressionContext context) {
	List<RDFNode> focusNodes;
	NodeExpression input = getInput();
	if(input != null) {
		focusNodes = input.eval(focusNode, context).toList();
	}
	else {
		focusNodes = Collections.singletonList(focusNode);
	}
	List<RDFNode> results = new LinkedList<>();
	for(RDFNode f : focusNodes) {
		QuerySolutionMap binding = new QuerySolutionMap();
		binding.add(SH.thisVar.getName(), f);
		try(QueryExecution qexec = ARQFactory.get().createQueryExecution(query, focusNode.getModel(), binding)) {
			if(query.isAskType()) {
				results.add(qexec.execAsk() ? JenaDatatypes.TRUE : JenaDatatypes.FALSE);
			}
			else {
				ResultSet rs = qexec.execSelect();
				String varName = rs.getResultVars().get(0);
				while(rs.hasNext()) {
					RDFNode node = rs.next().get(varName);
					if(node != null) {
						results.add(node);
					}
				}
			}
		}
	}
	return WrappedIterator.create(results.iterator());
}
 
Example 11
Source File: SPARQL.java    From NLIWOD with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Executes a select query for the given endpoint and query. Returns the answer as an {@link Results} object.
 * @param query
 * @param endpoint
 * @return
 */
public static Results executeSelect(final String query, final String endpoint) {
	QueryExecutionFactory qef = new QueryExecutionFactoryHttp(endpoint);
	QueryExecution qe = qef.createQueryExecution(query);

	ResultSet rs = qe.execSelect();	
	
	Results res = new Results();
	res.header.addAll(rs.getResultVars());

	while(rs.hasNext()) {
		QuerySolution sol = rs.nextSolution();
		res.table.add(new ArrayList<String>());
		for(String head: res.header) {
			String answer = "";
			
			if(sol.get(head).isResource()) {
				answer = sol.getResource(head).toString();
			} else {
				String temp = sol.get(head).toString();
				if(temp.contains("@")) {
					answer = "\"" + temp.substring(0, temp.indexOf("@")) + "\"" + temp.substring(temp.indexOf("@"));
				} else if (temp.contains("^^")){
					answer = "\"" + temp.substring(0, temp.indexOf("^")) + "\"^^<" + temp.substring(temp.indexOf("^")+2) + ">";
				} else {
					answer = temp;
				}
			}
			res.table.get(res.table.size()-1).add(answer);
		}
	}		
	closeExecFactory(qef);
	return res;
}
 
Example 12
Source File: ExTDB_Txn1.java    From xcurator with Apache License 2.0 5 votes vote down vote up
public static void execQuery(String sparqlQueryString, Dataset dataset)
{
    Query query = QueryFactory.create(sparqlQueryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, dataset) ;
    try {
        ResultSet results = qexec.execSelect() ;
        for ( ; results.hasNext() ; )
        {
            QuerySolution soln = results.nextSolution() ;
            int count = soln.getLiteral("count").getInt() ;
            System.out.println("count = "+count) ;
        }
      } finally { qexec.close() ; }
}
 
Example 13
Source File: SPARQLExecutor.java    From NLIWOD with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * An exact copy of this code is {@link SPARQL#sparql(String)}. Please consider using this, or even {@link ThreadedSPARQL}
 *
 * @param service
 * @param query
 * @return
 */
@Deprecated
public static Set<RDFNode> sparql(final String service, final String query) {
	Set<RDFNode> set = Sets.newHashSet();

	QueryExecution qe = QueryExecutionFactory.sparqlService(service, query);
	if ((qe != null) && (query != null)) {
		if (QALD4_EvaluationUtils.isAskType(query)) {
			set.add(new ResourceImpl(String.valueOf(qe.execAsk())));
		} else {
			ResultSet results = qe.execSelect();
			String firstVarName = results.getResultVars().get(0);
			while (results.hasNext()) {

				RDFNode node = results.next().get(firstVarName);
				/**
				 * Instead of returning a set with size 1 and value (null) in it, when no answers are found, this ensures that Set is empty
				 */
				if (node != null) {
					set.add(node);
				}
			}
		}
		qe.close();
	}
	return set;
}
 
Example 14
Source File: DBpediaToWikiId.java    From gerbil with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * The Wikipedia Id or -1 if the Id couldn't be retrieved.
 * 
 * FIXME The method throws an exception for "http://DBpedia.org/resource/Origin_of_the_name_"Empire_State"". this
 * might be happen because of the quotes inside the URI.
 * 
 * @param dbpediaUri
 * @return
 */
@Deprecated
public static int getIdFromDBpedia(String dbpediaUri) {
    int id = -1;
    ParameterizedSparqlString query = new ParameterizedSparqlString(
            "SELECT ?id WHERE { ?dbpedia dbo:wikiPageID ?id .}", prefixes);
    query.setIri("dbpedia", dbpediaUri);
    QueryExecution qexec = null;
    try {
        qexec = QueryExecutionFactory.create(query.asQuery(),
                model);
    } catch (QueryParseException e) {
        LOGGER.error("Got a bad dbpediaUri \"" + dbpediaUri
                + "\" which couldn't be parse inside of a SPARQL query. Returning -1.", e);
        return id;
    }
    ResultSet result = qexec.execSelect();
    if (result.hasNext()) {
        id = result.next().get("id").asLiteral().getInt();
        return id;
    }
    qexec = QueryExecutionFactory.sparqlService(
            "http://dbpedia.org/sparql", query.asQuery());
    result = qexec.execSelect();
    if (result.hasNext()) {
        id = result.next().get("id").asLiteral().getInt();
        model.add(new StatementImpl(model.createResource(dbpediaUri), model
                .createProperty("http://dbpedia.org/ontology/wikiPageID"),
                model.createTypedLiteral(id)));
        return id;
    }

    model.add(new StatementImpl(model.createResource(dbpediaUri), model
            .createProperty("http://dbpedia.org/ontology/wikiPageID"),
            model.createTypedLiteral(id)));
    return id;
}
 
Example 15
Source File: ClassSurfaceForms.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 {

		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 16
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 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: SparqlBasedRequestProcessorForTPFs.java    From Server.Java with MIT License 4 votes vote down vote up
/**
 *
 * @param subject
 * @param predicate
 * @param object
 * @param offset
 * @param limit
 * @return
 */
@Override
protected ILinkedDataFragment createFragment(
           final ITriplePatternElement<RDFNode,String,String> subject,
           final ITriplePatternElement<RDFNode,String,String> predicate,
           final ITriplePatternElement<RDFNode,String,String> object,
           final long offset,
           final long limit )
{
    // FIXME: The following algorithm is incorrect for cases in which
    //        the requested triple pattern contains a specific variable
    //        multiple times;
    //        e.g., (?x foaf:knows ?x ) or (_:bn foaf:knows _:bn)
    // see https://github.com/LinkedDataFragments/Server.Java/issues/24

    QuerySolutionMap map = new QuerySolutionMap();
    if ( ! subject.isVariable() ) {
        map.add("s", subject.asConstantTerm());
    }
    if ( ! predicate.isVariable() ) {
        map.add("p", predicate.asConstantTerm());
    }
    if ( ! object.isVariable() ) {
        map.add("o", object.asConstantTerm());
    }

    query.setOffset(offset);
    query.setLimit(limit);

    Model triples = ModelFactory.createDefaultModel();

    // Build the SPARQL-endpoint
    URIBuilder uriBuilder = new URIBuilder(endpointURI);
    addCredentials(uriBuilder);

    final String endpoint;
    try {
        endpoint = uriBuilder.build().toString();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }

    ParameterizedSparqlString queryWithParams = new ParameterizedSparqlString(query.serialize(), map);

    try (QueryExecution qexec = QueryExecutionFactory.sparqlService(endpoint, queryWithParams.asQuery())) {
        qexec.execConstruct(triples);
    }

    if (triples.isEmpty()) {
        return createEmptyTriplePatternFragment();
    }

    // Try to get an estimate
    long size = triples.size();
    long estimate = -1;

    ParameterizedSparqlString countQueryWithParams = new ParameterizedSparqlString(countQuery.serialize(), map);

    try (QueryExecution qexec = QueryExecutionFactory.createServiceRequest(endpoint, countQueryWithParams.asQuery())) {
        ResultSet results = qexec.execSelect();
        if (results.hasNext()) {
            QuerySolution soln = results.nextSolution() ;
            Literal literal = soln.getLiteral("count");
            estimate = literal.getLong();
        }
    }

    /*GraphStatisticsHandler stats = model.getGraph().getStatisticsHandler();
    if (stats != null) {
        Node s = (subject != null) ? subject.asNode() : null;
        Node p = (predicate != null) ? predicate.asNode() : null;
        Node o = (object != null) ? object.asNode() : null;
        estimate = stats.getStatistic(s, p, o);
    }*/

    // No estimate or incorrect
    if (estimate < offset + size) {
        estimate = (size == limit) ? offset + size + 1 : offset + size;
    }

    // create the fragment
    final boolean isLastPage = ( estimate < offset + limit );
    return createTriplePatternFragment( triples, estimate, isLastPage );
}
 
Example 19
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 20
Source File: JSTestCaseType.java    From shacl with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Model results) {
	Resource testCase = getResource();
	
	FunctionRegistry oldFR = FunctionRegistry.get();
	CurrentThreadFunctionRegistry threadFR = new CurrentThreadFunctionRegistry(oldFR);
	FunctionRegistry.set(ARQ.getContext(), threadFR);

	CurrentThreadFunctions old = CurrentThreadFunctionRegistry.register(testCase.getModel());
	Statement expectedResultS = testCase.getProperty(DASH.expectedResult);
	String queryString = "SELECT (<" + getResource() + ">() AS ?result) WHERE {}";
	Query query = ARQFactory.get().createQuery(testCase.getModel(), queryString);
	try(QueryExecution qexec = ARQFactory.get().createQueryExecution(query, testCase.getModel())) {
	    ResultSet rs = qexec.execSelect();
	    if(!rs.hasNext()) {
	        if(expectedResultS != null) {
	            createFailure(results,
	                          "Expression returned no result, but expected: " + expectedResultS.getObject());
	            return;
	        }
	    }
	    else {
	        RDFNode result = rs.next().get("result");
	        if(expectedResultS == null) {
	            if(result != null) {
	                createFailure(results,
	                              "Expression returned a result, but none expected: " + result);
	                return;
	            }
	        }
	        else if(!expectedResultS.getObject().equals(result)) {
	            createFailure(results,
	                          "Mismatching result. Expected: " + expectedResultS.getObject() + ". Found: " + result);
	            return;
	        }
	    }
	}
	finally {
		CurrentThreadFunctionRegistry.unregister(old);
		FunctionRegistry.set(ARQ.getContext(), oldFR);
	}
	
	createResult(results, DASH.SuccessTestCaseResult);
}