Java Code Examples for org.apache.jena.query.QueryExecutionFactory#sparqlService()
The following examples show how to use
org.apache.jena.query.QueryExecutionFactory#sparqlService() .
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: PubchemMeshSynonyms.java From act with GNU General Public License v3.0 | 7 votes |
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 File: PubchemMeshSynonyms.java From act with GNU General Public License v3.0 | 6 votes |
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 3
Source File: TripleIndexCreatorContext.java From AGDISTIS with GNU Affero General Public License v3.0 | 6 votes |
public String sparql(String subject) { // First query takes the most specific class from a given resource. String ontology_service = endpoint; String endpointsSparql = "select ?label where {<" + subject + "> <http://www.w3.org/2000/01/rdf-schema#label> ?label FILTER (lang(?label) = 'en')} LIMIT 100"; Query sparqlQuery = QueryFactory.create(endpointsSparql, Syntax.syntaxARQ); QueryEngineHTTP qexec = (QueryEngineHTTP) QueryExecutionFactory.sparqlService(ontology_service, sparqlQuery); qexec.setModelContentType(WebContent.contentTypeRDFXML); ResultSet results = qexec.execSelect(); String property = null; while (results.hasNext()) { QuerySolution qs = results.next(); property = qs.getLiteral("?label").getLexicalForm(); } return property; }
Example 4
Source File: DBPediaService.java From baleen with Apache License 2.0 | 6 votes |
/** * 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 5
Source File: Utils.java From SDA with BSD 2-Clause "Simplified" License | 5 votes |
/** * Device정보 리턴 * @param deviceUri * @return String * @throws Exception */ public static String getDeviceInfo(String deviceUri) throws Exception { String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.dw.sparql.endpoint")+"/sparql"; StringWriter out = new StringWriter(); String query = getSparQlHeader() + "\n"+ "describe "+ deviceUri; QueryExecution qe = QueryExecutionFactory.sparqlService(serviceURI, query); Model model = qe.execDescribe(); qe.close(); model.write(out,"RDF/XML"); return out.toString(); }
Example 6
Source File: Utils.java From SDA with BSD 2-Clause "Simplified" License | 5 votes |
/** * DW데이타 지우기 * @throws Exception * @return void */ public static final void deleteDWTripleAll2() throws Exception { String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.dw.sparql.endpoint"); String queryString = "delete data where {?s ?p ?o }"; QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, queryString); ResultSet rs = queryExec.execSelect(); ResultSetFormatter.out(rs); }
Example 7
Source File: SPARQLExecutor.java From NLIWOD with GNU Affero General Public License v3.0 | 5 votes |
/** * 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 8
Source File: SPARQLExecutor.java From NLIWOD with GNU Affero General Public License v3.0 | 5 votes |
/** * 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 9
Source File: SPARQLExecutor.java From NLIWOD with GNU Affero General Public License v3.0 | 5 votes |
/** * An exact copy of this code is {@link SPARQL#isEndpointAlive(String)}. * @param endpoint * @return */ @Deprecated public static boolean isEndpointAlive(final String endpoint) { try { QueryExecution qeExe = QueryExecutionFactory.sparqlService(endpoint, "PREFIX foaf: <http://xmlns.com/foaf/0.1/> ASK { ?x foaf:name \"Alice\" }"); qeExe.execAsk(); return true; } catch (Exception e) { } return false; }
Example 10
Source File: OneM2MSubscribeUriMapper.java From SDA with BSD 2-Clause "Simplified" License | 5 votes |
/** * 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 11
Source File: Utils.java From SDA with BSD 2-Clause "Simplified" License | 5 votes |
/** * Device정보 리턴 * @param deviceUri * @return String * @throws Exception */ public static String getDeviceInfo(String deviceUri) throws Exception { String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.dw.sparql.endpoint")+"/sparql"; StringWriter out = new StringWriter(); String query = getSparQlHeader() + "\n"+ "describe "+ deviceUri; QueryExecution qe = QueryExecutionFactory.sparqlService(serviceURI, query); Model model = qe.execDescribe(); qe.close(); model.write(out,"RDF/XML"); return out.toString(); }
Example 12
Source File: Utils.java From SDA with BSD 2-Clause "Simplified" License | 5 votes |
/** * DW데이타 지우기 * @throws Exception * @return void */ public static final void deleteDWTripleAll2() throws Exception { String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.dw.sparql.endpoint"); String queryString = "delete data where {?s ?p ?o }"; QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, queryString); ResultSet rs = queryExec.execSelect(); ResultSetFormatter.out(rs); }
Example 13
Source File: OneM2MSubscribeUriMapper.java From SDA with BSD 2-Clause "Simplified" License | 5 votes |
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 14
Source File: Utils.java From SDA with BSD 2-Clause "Simplified" License | 5 votes |
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 15
Source File: Utils.java From SDA with BSD 2-Clause "Simplified" License | 5 votes |
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 16
Source File: QueryExecutionFactoryFilter.java From shacl with Apache License 2.0 | 4 votes |
public QueryExecution sparqlService(String service, Query query, HttpClient httpClient) { return QueryExecutionFactory.sparqlService(service, query, httpClient); }
Example 17
Source File: SparqlBasedRequestProcessorForTPFs.java From Server.Java with MIT License | 4 votes |
/** * * @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 18
Source File: QueryExecutionFactoryFilter.java From shacl with Apache License 2.0 | 4 votes |
public QueryExecution sparqlService(String service, Query query) { return QueryExecutionFactory.sparqlService(service, query); }
Example 19
Source File: ResultSizeRetriever.java From IGUANA with GNU Affero General Public License v3.0 | 4 votes |
public static int retrieveSize(String endpoint, String query) { QueryExecution exec = QueryExecutionFactory.sparqlService(endpoint, query); return ResultSetFormatter.consume(exec.execSelect()); }
Example 20
Source File: SPARQLExecutor.java From NLIWOD with GNU Affero General Public License v3.0 | 2 votes |
/** * An exact copy of this code is {@link SPARQL#executeAsk(String)}. * @param query * @param endpoint * @return */ @Deprecated public static Boolean executeAsk(final String query, final String endpoint) { QueryExecution qeExe = QueryExecutionFactory.sparqlService(endpoint, query); return qeExe.execAsk(); }