Java Code Examples for org.apache.jena.query.QueryExecution

The following examples show how to use org.apache.jena.query.QueryExecution. These examples are extracted from open source projects. 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 Project: act   Source File: PubchemMeshSynonyms.java    License: GNU General Public License v3.0 7 votes vote down vote up
public String fetchCIDFromInchi(String inchi) {
  // The clone method has its own implementation in the SelectBuilder. Thus safe to use!
  SelectBuilder sb = CID_QUERY_TMPL.clone();
  // The inchi litteral needs to be create with a language tag, otherwise it will not match anything
  // See "Matching Litteral with Language Tags" (https://www.w3.org/TR/rdf-sparql-query/#matchLangTags)
  // for more information
  sb.setVar(Var.alloc("inchi_string"), NodeFactory.createLiteral(inchi, ENGLISH_LANG_TAG));
  Query query = sb.build();

  String result;
  LOGGER.debug("Executing SPARQL query: %s", query.toString());
  try (QueryExecution qexec = QueryExecutionFactory.sparqlService(sparqlService, query)) {
    ResultSet results = qexec.execSelect();
    // TODO: we assume here that there is at most one CID per InChI and return the first CID
    // Improve that behavior so we can stitch together many CID's synonyms.
    if (!results.hasNext()) {
      LOGGER.info("Could not find Pubchem Compound Id for input InChI %s", inchi);
      return null;
    }
    result = results.nextSolution().getResource("inchi_iri").getLocalName();
  }

  String cid = extractCIDFromResourceName(result);
  LOGGER.info("Found Pubchem Compound Id %s for input InChI %s", cid, inchi);
  return cid;
}
 
Example 2
Source Project: baleen   Source File: DBPediaService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Search DBPedia for candidates with a language restriction on certain variables
 *
 * @param selectVars The placeholders for variables to find eg ?x ?y
 * @param whereClauses An array of StringTriple in Subject, Predicate, Object form
 * @param filterClause Clause String to filter results
 * @param limit The maximum number of Candidates to return
 * @param idField A uniquely identifying field contained in the returned Candidates
 * @param nameField The name field used to find the Candidates
 * @param languageSpecificVars Variables to restrict to the specified language
 * @return a Set of DBPediaCandidates
 * @throws ParseException Exception thrown if the SPARQL query fails to parse
 */
public Set<DefaultCandidate> searchForCandidates(
    String[] selectVars,
    StringTriple[] whereClauses,
    String filterClause,
    int limit,
    String idField,
    String nameField,
    String[] languageSpecificVars)
    throws ParseException {

  Query query = buildQuery(selectVars, whereClauses, filterClause, limit, languageSpecificVars);

  QueryExecution qe = QueryExecutionFactory.sparqlService(DBPEDIA_SPARQL_ENDPOINT, query);

  ResultSet rs = qe.execSelect();

  if (LOGGER.isDebugEnabled()) {
    ResultSet rsToPrint = qe.execSelect();
    LOGGER.debug(ResultSetFormatter.asText(rsToPrint));
  }

  return getCandidates(rs, idField, nameField);
}
 
Example 3
Source Project: act   Source File: PubchemMeshSynonyms.java    License: 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 4
Source Project: act   Source File: PubchemMeshSynonyms.java    License: 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 5
Source Project: RDFUnit   Source File: TagRdfUnitTestGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private Set<TestCase> generate(QueryExecutionFactoryModel qef, SchemaSource source, TestGenerator testGenerator) {
    Set<TestCase> tests = new HashSet<>();

    Pattern tgPattern = testGenerator.getPattern();

    Query q = QueryFactory.create(PrefixNSService.getSparqlPrefixDecl() + testGenerator.getQuery());
    try (QueryExecution qe = qef.createQueryExecution(q) ) {
        qe.execSelect().forEachRemaining(result -> {

            Optional<TestCase> tc = generateTestFromResult(testGenerator, tgPattern, result, source);
            tc.ifPresent(tests::add);

        });
    }
    return tests;
}
 
Example 6
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 7
Source Project: RDFUnit   Source File: DatasetStatistics.java    License: Apache License 2.0 6 votes vote down vote up
private Map<String, Long> getStats(String sparqlQuery, QueryExecutionFactory qef) {
    Map<String, Long> stats = new HashMap<>();


    try (QueryExecution qe =  qef.createQueryExecution(sparqlQuery))
    {
        qe.execSelect().forEachRemaining( qs -> {

            String s = qs.get("stats").toString();
            int c = 0;
            if (qs.contains("count")) {
                c = qs.get("count").asLiteral().getInt();
            }
            stats.put(s, (long) c);
        });
    }

    return stats;
}
 
Example 8
Source Project: sparql-generate   Source File: LocationMapperAccept.java    License: Apache License 2.0 6 votes vote down vote up
public LocationMapperAccept(final Model configurationModel) {
    Query q = QueryFactory.create("PREFIX lm: <http://jena.hpl.hp.com/2004/08/location-mapping#>"
            + "SELECT * WHERE {"
            + "[] lm:mapping ?e ."
            + "?e lm:name ?name ; lm:altName ?alt ."
            + "OPTIONAL { ?e lm:media ?media . } "
            + "}");
    try (QueryExecution exec = QueryExecutionFactory.create(q, configurationModel)) {
        exec.execSelect().forEachRemaining((result) -> {
            String name = null, altName = null, media = null;
            try {
                name = result.getLiteral("name").getString();
                altName = result.getLiteral("alt").getString();
                media = (result.getLiteral("media") == null ? null : result.getLiteral("media").getString());
                altLocations.put(new LookUpRequest(name, media), new LookUpRequest(altName, media));
            } catch (Exception ex) {
                log.debug("Error while reading mapping in configuration model for name " + name + ", alt " + altName + ", media " + media, ex);
            }
        });
    }
}
 
Example 9
Source Project: quetzal   Source File: DB2DescribeHandler.java    License: Eclipse Public License 2.0 6 votes vote down vote up
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 10
Source Project: xcurator   Source File: ExTDB4.java    License: 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) ;
    ResultSet results = qexec.execSelect() ;
    ResultSetFormatter.out(results) ;
    qexec.close() ;

    dataset.close();
}
 
Example 11
Source Project: shacl   Source File: ARQFactory.java    License: Apache License 2.0 6 votes vote down vote up
public QueryExecution createQueryExecution(Query query, Dataset dataset, QuerySolution initialBinding) {
		if(!query.getGraphURIs().isEmpty() || !query.getNamedGraphURIs().isEmpty()) {
			dataset = new FromDataset(dataset, query);
		}
		
		if ( LOG_QUERIES ) {
		    // And the data - can be long.
//    		System.err.println("~~ ~~");
//    		RDFDataMgr.write(System.err, dataset.getDefaultModel(), Lang.TTL);
    		System.err.println("~~ ~~");
    		System.err.println(initialBinding);
    		System.err.println(query);
		}
		
		QueryExecution qexec = QueryExecutionFactoryFilter.get().create(query, dataset, initialBinding);
		adjustQueryExecution(qexec);
		return qexec;
	}
 
Example 12
Source Project: shacl   Source File: JenaUtil.java    License: 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 13
Source Project: shacl   Source File: SPARQLTarget.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean contains(Dataset dataset, RDFNode node) {
	QuerySolutionMap bindings = new QuerySolutionMap();
	bindings.add(SH.thisVar.getVarName(), node);
	if(parameterizableTarget != null) {
		parameterizableTarget.addBindings(bindings);
	}
	if(query.isAskType()) {
		try(QueryExecution qexec = SPARQLSubstitutions.createQueryExecution(query, dataset, bindings)) {
		    return qexec.execAsk();
		}
	}
	else {
		try(QueryExecution qexec = SPARQLSubstitutions.createQueryExecution(query, dataset, bindings)) {
		    ResultSet rs = qexec.execSelect();
		    return rs.hasNext();
		}
	}
}
 
Example 14
Source Project: shacl   Source File: QueryTestCaseType.java    License: Apache License 2.0 6 votes vote down vote up
public static String createResultSetJSON(String queryString, Model model) {
	CurrentThreadFunctions old = CurrentThreadFunctionRegistry.register(model);
	try {
		Query query = ARQFactory.get().createQuery(model, queryString);
		try(QueryExecution qexec = ARQFactory.get().createQueryExecution(query, model)) {
   			ResultSet actualResults = qexec.execSelect();
   			ByteArrayOutputStream os = new ByteArrayOutputStream();
   			ResultSetFormatter.outputAsJSON(os, actualResults);
               return os.toString("UTF-8");
		}
	} 
	catch (UnsupportedEncodingException e) {
		throw ExceptionUtil.throwUnchecked(e);
	}
	finally {
		CurrentThreadFunctionRegistry.unregister(old);
	}
}
 
Example 15
Source Project: shacl   Source File: SHACLSPARQLARQFunction.java    License: 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 16
Source Project: shacl   Source File: SPARQLRule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void execute(RuleEngine ruleEngine, List<RDFNode> focusNodes, Shape shape) {
	ProgressMonitor monitor = ruleEngine.getProgressMonitor();
	for(RDFNode focusNode : focusNodes) {
		
		if(monitor != null && monitor.isCanceled()) {
			return;
		}

		QuerySolutionMap bindings = new QuerySolutionMap();
		bindings.add(SH.thisVar.getVarName(), focusNode);
		try(QueryExecution qexec = ARQFactory.get().createQueryExecution(query, ruleEngine.getDataset(), bindings)) {
			Iterator<Triple> it = qexec.execConstructTriples();
			while(it.hasNext()) {
				Triple triple = it.next();
				ruleEngine.infer(triple, this, shape);
			}
		}
	}
}
 
Example 17
Source Project: shacl   Source File: SHACLUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Runs the rule to infer missing rdf:type triples for certain blank nodes.
 * @param model  the input Model
 * @return a new Model containing the inferred triples
 */
public static Model createDefaultValueTypesModel(Model model) {
	String sparql = JenaUtil.getStringProperty(DASH.DefaultValueTypeRule.inModel(model), SH.construct);
	if(sparql == null) {
		throw new IllegalArgumentException("Shapes graph does not include " + TOSH.PREFIX + ":" + DASH.DefaultValueTypeRule);
	}
	Model resultModel = JenaUtil.createMemoryModel();
	MultiUnion multiUnion = new MultiUnion(new Graph[] {
		model.getGraph(),
		resultModel.getGraph()
	});
	Model unionModel = ModelFactory.createModelForGraph(multiUnion);
	Query query = ARQFactory.get().createQuery(model, sparql);
	try(QueryExecution qexec = ARQFactory.get().createQueryExecution(query, unionModel)) {
	    qexec.execConstruct(resultModel);
	    return resultModel;    
	}
}
 
Example 18
Source Project: Processor   Source File: Validator.java    License: Apache License 2.0 6 votes vote down vote up
public OntModel fixOntModel(OntModel ontModel)
    {
        if (ontModel == null) throw new IllegalArgumentException("Model cannot be null");
        
        OntModel fixedModel = ModelFactory.createOntologyModel(ontModel.getSpecification());
        Query fix = QueryFactory.create("CONSTRUCT\n" +
"{\n" +
"  ?s ?p ?o\n" +
"}\n" +
"WHERE\n" +
"{\n" +
"  ?s ?p ?o\n" +
"  FILTER (!(?p = <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> && ?o = <https://www.w3.org/ns/ldt#Constraint>))\n" +
"}");
        
        try (QueryExecution qex = QueryExecutionFactory.create(fix, ontModel))
        {
            fixedModel.add(qex.execConstruct());
        }
        
        return fixedModel;
    }
 
Example 19
/**
 * Take an existing {@link CypherEntity} and adds the properties that can be mapped from the underlining TDB by means 
 * of a property query, like {@link CyNodeLoadingHandler#getNodePropsSparql()}, or 
 * {@link CyRelationLoadingHandler#getRelationPropsSparql()}.
 * 
 * It doesn't do anything if the query is null.
 * 
 */
protected void addCypherProps ( CypherEntity cyEnt, String propsSparql )
{
	ensureOpen ();		
	Dataset dataSet = this.getDataSet ();
	
	QuerySolutionMap params = new QuerySolutionMap ();
	params.add ( "iri", dataSet.getUnionModel().getResource ( cyEnt.getIri () ) );

	// It may be omitted, if you don't have any property except the IRI.
	if ( propsSparql == null ) return;
	
	Query qry = SparqlUtils.getCachedQuery ( propsSparql );
	Function<String, String> propIdConverter = this.getCyPropertyIdConverter ();
	
	boolean wasInTnx = dataSet.isInTransaction ();
	if ( !wasInTnx ) dataSet.begin ( ReadWrite.READ );
	try
	{
		QueryExecution qx = QueryExecutionFactory.create ( qry, dataSet, params );
		qx.execSelect ().forEachRemaining ( row ->
		{
			String propName = this.getCypherId ( row.get ( "name" ), propIdConverter );
			if ( propName == null ) throw new IllegalArgumentException ( 
				"Null property name for " + cyEnt.getIri () 
			);
			
			String propValue = JENAUTILS.literal2Value ( row.getLiteral ( "value" ) ).get ();
			cyEnt.addPropValue ( propName, propValue );
		});
	}
	finally {
		if ( !wasInTnx && dataSet.isInTransaction () ) dataSet.end ();
	}
}
 
Example 20
@Override
public IDataStore load(IDataReader dataReader) {
	logger.debug("IN");
	IDataStore dataStore = null;

	try (QueryExecution queryExecution = QueryExecutionFactory.sparqlService(sparqlEndpoint, sparqlQuery, defaultGraphIRI)) {
		ResultSet resultSet = executeSPARQLQuery(queryExecution);
		dataStore = readResultSet(dataReader, dataStore, resultSet);
	} catch (Exception e) {
		throw new SpagoBIRuntimeException("An error occurred while executing SPARQL query", e);
	}
	logger.debug("OUT");
	return dataStore;
}
 
Example 21
private ResultSet executeSPARQLQuery(QueryExecution queryExecution) {
	queryExecution.setTimeout(executionTimeout * 1000);
	Monitor monitor = MonitorFactory.start("Knowage.SPARQLDataProxy.executeSPARQLQuery");
	ResultSet resultSet = null;
	try {
		resultSet = queryExecution.execSelect();
	} finally {
		monitor.stop();
	}
	return resultSet;
}
 
Example 22
Source Project: RDFUnit   Source File: StatusTestExecutor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Collection<TestCaseResult> executeSingleTest(TestSource testSource, TestCase testCase) {

    TestCaseResultStatus status = TestCaseResultStatus.Error;


    try (QueryExecution qe = testSource.getExecutionFactory().createQueryExecution(queryGenerationFactory.getSparqlQuery(testCase))) {
        boolean fail = qe.execAsk();

        if (fail) {
            status = TestCaseResultStatus.Fail;
        } else {
            status = TestCaseResultStatus.Success;
        }

    } catch (QueryExceptionHTTP e) {
        // No need to throw exception here, class supports status
        if (SparqlUtils.checkStatusForTimeout(e)) {
            status = TestCaseResultStatus.Timeout;
        } else {
            status = TestCaseResultStatus.Error;
        }

    }

    return Collections.singletonList(new StatusTestCaseResultImpl(testCase, status));
}
 
Example 23
Source Project: SDA   Source File: Utils.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static final void getTripleCount() throws Exception {
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.sparql.endpoint");

	String queryString = "select  (count(?s) as ?count) where {?s ?p ?o }";
	QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, queryString);

	ResultSet rs = queryExec.execSelect();

	// 값을 console에 출력함
	ResultSetFormatter.out(rs);
}
 
Example 24
Source Project: SDA   Source File: Utils.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static final void getTripleAll() throws Exception {
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.sparql.endpoint");

	String queryString = "select ?s ?p ?o {?s ?p ?o}";
	QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, queryString);

	ResultSet rs = queryExec.execSelect();
	ResultSetFormatter.out(rs);
}
 
Example 25
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 26
/**
 * 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 27
/***
 * 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 28
Source Project: NLIWOD   Source File: SPARQL.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Fire a sparql query against endpoint defined in constructor.
 * <p>
 * <b>NOTE:</b> This will block. To set a maximum execution time, use {@link ThreadedSPARQL}
 * <p>
 * For string representation of answers, see {@link #extractAnswerStrings(Set)}
 *
 * @param query
 *            - a sparql query
 * @return
 */
public Set<RDFNode> sparql(final String query) {
	Set<RDFNode> set = Sets.newHashSet();

	QueryExecution qe = qef.createQueryExecution(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 29
Source Project: NLIWOD   Source File: SPARQL.java    License: 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 30
Source Project: NLIWOD   Source File: SPARQL.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Executes an ask query for the given endpoint and query.
 * @param query
 * @param endpoint
 * @return
 */
public static Boolean executeAsk(final String query, final String endpoint) {
	QueryExecutionFactory qef = new QueryExecutionFactoryHttp(endpoint);
	QueryExecution qe = qef.createQueryExecution(query);		
	closeExecFactory(qef);
	return qe.execAsk();
}