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

The following examples show how to use org.apache.jena.query.ResultSet#nextSolution() . 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: PubchemMeshSynonyms.java    From act with GNU General Public License v3.0 6 votes vote down vote up
public Map<PubchemSynonymType, Set<String>> fetchPubchemSynonymsFromCID(String cid) {
  // The clone method has its own implementation in the SelectBuilder. Thus safe to use!
  SelectBuilder sb = PUBCHEM_SYNO_QUERY_TMPL.clone();
  sb.setVar(Var.alloc("compound"), String.format("compound:%s", cid));
  Query query = sb.build();
  LOGGER.debug("Executing SPARQL query: %s", query.toString());
  Map<PubchemSynonymType, Set<String>> map = new HashMap<>();

  try (QueryExecution queryExecution = QueryExecutionFactory.sparqlService(sparqlService, query)) {
    ResultSet results = queryExecution.execSelect();
    while(results.hasNext()) {
      QuerySolution solution = results.nextSolution();
      String cheminfId = solution.getResource("type").getLocalName();
      String synonym = solution.getLiteral("value").getString();
      LOGGER.debug("Found synonym %s with type %s", synonym, cheminfId);
      PubchemSynonymType synonymType = PubchemSynonymType.getByCheminfId(cheminfId);
      Set synonyms = map.get(synonymType);
      if (synonyms == null) {
        synonyms = new HashSet<>();
        map.put(synonymType, synonyms);
      }
      synonyms.add(synonym);
    }
  }
  return map;
}
 
Example 3
Source File: PubchemMeshSynonyms.java    From act with GNU General Public License v3.0 6 votes vote down vote up
public Map<MeshTermType, Set<String>> fetchMeshTermsFromCID(String cid) {
  // The clone method has its own implementation in the SelectBuilder. Thus safe to use!
  SelectBuilder sb = MESH_TERMS_QUERY_TMPL.clone();
  sb.setVar(Var.alloc("compound"), String.format("compound:%s", cid));
  Query query = sb.build();
  LOGGER.debug("Executing SPARQL query: %s", query.toString());
  Map<MeshTermType, Set<String>> map = new HashMap<>();

  try (QueryExecution queryExecution = QueryExecutionFactory.sparqlService(sparqlService, query)) {
    ResultSet results = queryExecution.execSelect();
    while(results.hasNext()) {
      QuerySolution solution = results.nextSolution();
      String conceptLabel = solution.getLiteral("concept_label").getString();
      String lexicalTag = solution.getLiteral("lexical_tag").getString();
      LOGGER.debug("Found term %s with tag %s", conceptLabel, lexicalTag);
      MeshTermType meshTermsType = MeshTermType.getByLexicalTag(lexicalTag);
      Set synonyms = map.get(meshTermsType);
      if (synonyms == null) {
        synonyms = new HashSet<>();
        map.put(meshTermsType, synonyms);
      }
      synonyms.add(conceptLabel);
    }
  }
  return map;
}
 
Example 4
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 5
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 6
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 7
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 8
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 9
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 10
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#executeSelect(String)}.
 * @param query
 * @param endpoint
 * @return
 */
@Deprecated
public static Results executeSelect(final String query, final String endpoint) {
	QueryExecution qeExe = QueryExecutionFactory.sparqlService(endpoint, query);
	ResultSet rs = qeExe.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);
		}
	}
	return res;
}
 
Example 11
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 12
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 13
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 14
Source File: JenaTDBBasedRequestProcessorForTPFs.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

    Model model;
    if (defaultGraph == null) {
        model = tdb.getDefaultModel();
    } else {
        model = tdb.getNamedModel(defaultGraph);
    }

    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();

    try (QueryExecution qexec = QueryExecutionFactory.create(query, model, map)) {
        qexec.execConstruct(triples);
    }

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

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

    try (QueryExecution qexec = QueryExecutionFactory.create(countQuery, model, map)) {
        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 15
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 );
}