org.apache.jena.query.Query Java Examples
The following examples show how to use
org.apache.jena.query.Query.
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: SPARQLExtQuerySerializer.java From sparql-generate with Apache License 2.0 | 6 votes |
@Override public void visitSelectResultForm(Query q) { SPARQLExtQuery query = asSPARQLExtQuery(q); out.print("SELECT "); printName(query); if (query.isDistinct()) { out.print("DISTINCT "); } if (query.isReduced()) { out.print("REDUCED "); } out.print(" "); //Padding if (query.isQueryResultStar()) { out.print("*"); } else { appendNamedExprList(query, out, query.getProject()); } out.newline(); }
Example #3
Source File: CustomQueryValidator.java From rdflint with MIT License | 6 votes |
@Override public void validateTripleSet(LintProblemSet problems, String file, List<Triple> tripeSet) { if (this.getParameters().getRules() == null) { return; } // execute sparql & custom validation Graph g = Factory.createGraphMem(); tripeSet.forEach(g::add); Model m = ModelFactory.createModelForGraph(g); this.getParameters().getRules().stream() .filter(r -> file.matches(r.getTarget())) .forEach(r -> { Query query = QueryFactory.create(r.getQuery()); QueryExecution qe = QueryExecutionFactory.create(query, m); Binding binding = new Binding(); binding.setVariable("rs", qe.execSelect()); binding.setVariable("log", new ProblemLogger(this, problems, file, r.getName())); GroovyShell shell = new GroovyShell(binding, new CompilerConfiguration()); shell.evaluate(r.getValid()); }); }
Example #4
Source File: ExTDB4.java From xcurator with Apache License 2.0 | 6 votes |
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 #5
Source File: TriplestoreResource.java From trellis with Apache License 2.0 | 6 votes |
/** * This code is equivalent to the SPARQL query below. * * <p><pre><code> * SELECT ?subject ?predicate ?object * WHERE { GRAPH fromGraphName { ?subject ?predicate ?object } } * </code></pre> */ private Stream<Quad> fetchAllFromGraph(final String fromGraphName, final IRI toGraphName) { final Query q = new Query(); q.setQuerySelectType(); q.addResultVar(SUBJECT); q.addResultVar(PREDICATE); q.addResultVar(OBJECT); final ElementPathBlock epb = new ElementPathBlock(); epb.addTriple(create(SUBJECT, PREDICATE, OBJECT)); final ElementGroup elg = new ElementGroup(); elg.addElement(new ElementNamedGraph(createURI(fromGraphName), epb)); q.setQueryPattern(elg); final Stream.Builder<Quad> builder = builder(); rdfConnection.querySelect(q, qs -> builder.accept(rdf.createQuad(toGraphName, getSubject(qs), getPredicate(qs), getObject(qs)))); return builder.build(); }
Example #6
Source File: SPARQLExtQuerySerializer.java From sparql-generate with Apache License 2.0 | 6 votes |
@Override public void visitDatasetDecl(Query q) { SPARQLExtQuery query = asSPARQLExtQuery(q); for (FromClause fromClause : query.getFromClauses()) { out.print("FROM "); if (fromClause.getGenerate() == null) { if (fromClause.isNamed()) { out.print(" NAMED "); } fmtExpr.format(fromClause.getName()); } else { printSubGenerate(fromClause.getGenerate()); if (fromClause.isNamed()) { out.print(" NAMED "); fmtExpr.format(fromClause.getName()); } out.print(" . "); } out.newline(); } }
Example #7
Source File: Validator.java From Processor with Apache License 2.0 | 6 votes |
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 #8
Source File: TarqlQueryExecution.java From tarql with BSD 2-Clause "Simplified" License | 6 votes |
/** * Sets up a new query execution. * * @param source The input CSV file * @param options Configuration options for the CSV file * @param query The input query */ public TarqlQueryExecution(InputStreamSource source, CSVOptions options, TarqlQuery query) { if (options == null) { options = new CSVOptions(); } if (options.hasColumnNamesInFirstRow() == null) { // Presence or absence of header row was not specified on command line or FROM clause. // So we fall back to the convention where OFFSET 1 in the query // indicates that a header is present. To make that work, we // set the OFFSET to 0 and tell the parser to gobble up the first // row for column names. options = new CSVOptions(options); Query firstQuery = query.getQueries().get(0); if (firstQuery.getOffset() == 1) { options.setColumnNamesInFirstRow(true); firstQuery.setOffset(0); } } table = new CSVTable(source, options); tq = query; }
Example #9
Source File: RuleforJena.java From quetzal with Eclipse Public License 2.0 | 6 votes |
public RuleforJena(Query constructQuery, int id) { this.id = id; antecedent = Algebra.compile(constructQuery); // KAVITHA: the consequent should be a single triple List<Triple> list = constructQuery.getConstructTemplate().getBGP() .getList(); consequent = new OpTriple(list.get(0)); if (SPARQLRewriterForJena.GENERATE_TRACE == true) { Op bind = null; VarExprList expr = new VarExprList(); expr.add( Var.alloc("RULEID"), new NodeValueNode(NodeFactory.createLiteral(String .valueOf(id)))); bind = OpExtend.extend(antecedent, expr); antecedent = bind; } }
Example #10
Source File: TriplePatternExtractor.java From NLIWOD with GNU Affero General Public License v3.0 | 6 votes |
public Set<Triple> extractTriplePattern(final Query query, final boolean ignoreOptionals) { triplePattern = new HashSet<>(); optionalTriplePattern = new HashSet<>(); query.getQueryPattern().visit(this); // postprocessing: triplepattern in OPTIONAL clause if (!ignoreOptionals && query.isSelectType()) { for (Triple t : optionalTriplePattern) { if (!ListUtils.intersection(new ArrayList<>(VarUtils.getVars(t)), query.getProjectVars()).isEmpty()) { triplePattern.add(t); } } } return triplePattern; }
Example #11
Source File: ARQFactory.java From shacl with Apache License 2.0 | 6 votes |
/** * Gets a list of named graphs (GRAPH elements) mentioned in a given * Query. * @param query the Query to traverse * @return a List of those GRAPHs */ public static List<String> getNamedGraphURIs(Query query) { final List<String> results = new LinkedList<String>(); ElementWalker.walk(query.getQueryPattern(), new ElementVisitorBase() { @Override public void visit(ElementNamedGraph el) { Node node = el.getGraphNameNode(); if(node != null && node.isURI()) { String uri = node.getURI(); if(!results.contains(uri)) { results.add(uri); } } } }); return results; }
Example #12
Source File: SelectExtractionVisitor.java From sparql-generate with Apache License 2.0 | 6 votes |
@Override public void visitQueryPattern(final Query query) { if (query.getQueryPattern() == null || ((ElementGroup) query.getQueryPattern()).isEmpty()) { output.setQueryPattern(new ElementGroup()); return; } isDummyQuery = false; if (output.getQueryPattern() != null) { ElementGroup group = new ElementGroup(); group.addElement(query.getQueryPattern()); group.addElement(output.getQueryPattern()); output.setQueryPattern(group); } else { Element el = query.getQueryPattern(); output.setQueryPattern(el); } }
Example #13
Source File: LocationMapperAccept.java From sparql-generate with Apache License 2.0 | 6 votes |
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 #14
Source File: SparqlToGremlinCompiler.java From tinkerpop with Apache License 2.0 | 6 votes |
/** * Extracts any {@code SortCondition} instances from the SPARQL query and holds them in an index of their keys * where the value is that keys sorting direction. */ private static Map<String, Order> createOrderIndexFromQuery(final Query query) { final Map<String, Order> orderingIndex = new HashMap<>(); if (query.hasOrderBy()) { final List<SortCondition> sortingConditions = query.getOrderBy(); for (SortCondition sortCondition : sortingConditions) { final Expr expr = sortCondition.getExpression(); // by default, the sort will be ascending. getDirection() returns -2 if the DESC/ASC isn't // supplied - weird orderingIndex.put(expr.getVarName(), sortCondition.getDirection() == -1 ? Order.desc : Order.asc); } } return orderingIndex; }
Example #15
Source File: Drivers.java From quetzal with Eclipse Public License 2.0 | 6 votes |
public static void runRepair(URL datasetURL, String queryFile, SparqlSelectResult result) throws URISyntaxException, MalformedURLException, ParserConfigurationException, SAXException, IOException { Query q = JenaUtil.parse(queryFile); List<Var> vars = q.getProjectVars(); UniverseFactory uf = new ComparisonUniverse(datasetURL); SolutionRelation r = null; if (result != null) { uf.addSolution(r = new SolutionRelation(result, vars, Collections.<String,Object>emptyMap())); } Op query = JenaUtil.compile(q); JenaTranslator jt = r==null? JenaTranslator.make(vars, query, uf): JenaTranslator.make(vars, query, uf, r); Pair<Formula, Pair<Formula, Formula>> answer = jt.translateSingle(Collections.<String,Object>emptyMap(), false).iterator().next(); Formula minDiff = QuadTableRelations.quads.union(QuadTableRelations.desiredQuads).count().minus( QuadTableRelations.quads.intersection(QuadTableRelations.desiredQuads).count()).lte(IntConstant.constant(1)); answer = Pair.make(answer.fst.and(minDiff), Pair.make(answer.snd.fst.and(minDiff), answer.snd.snd.and(minDiff))); check(uf, answer, "solution"); }
Example #16
Source File: QueryAggregatesNormalizer.java From sparql-generate with Apache License 2.0 | 6 votes |
@Override public void visitDatasetDecl(Query q) { SPARQLExtQuery query = asSPARQLExtQuery(q); final ExprNormalizer enzer = new ExprNormalizer(query); query.getFromClauses().replaceAll((fromClause) -> { if (fromClause.getGenerate() == null) { Expr nzed = enzer.normalize(fromClause.getName()); return new FromClause(fromClause.isNamed(), nzed); } else { SPARQLExtQuery gnzed = fromClause.getGenerate(); gnzed.normalizeXExpr(); if (!fromClause.isNamed()) { return new FromClause(gnzed); } Expr nnzed = enzer.normalize(fromClause.getName()); return new FromClause(gnzed, nnzed); } }); }
Example #17
Source File: PatternQueryHandler.java From IGUANA with GNU Affero General Public License v3.0 | 6 votes |
protected Query convertToSelect(ParameterizedSparqlString pss, Set<String> varNames) { Query queryCpy = pss.asQuery(); queryCpy.getQueryPattern(); StringBuilder queryStr = new StringBuilder("SELECT DISTINCT "); for(String varName : varNames) { queryStr.append("?").append(varName).append(" "); } queryStr.append(queryCpy.getQueryPattern()); ParameterizedSparqlString pssSelect = new ParameterizedSparqlString(); pssSelect.setCommandText(queryStr.toString()); pssSelect.setNsPrefixes(pss.getNsPrefixMap()); pssSelect.append(" LIMIT "); pssSelect.append(this.limit); System.out.println(pssSelect); return pssSelect.asQuery(); }
Example #18
Source File: RDF2CSV.java From IGUANA with GNU Affero General Public License v3.0 | 5 votes |
private static Query createQuery(String taskID, Field[] fields) { StringBuilder vars = new StringBuilder(); StringBuilder triples = new StringBuilder(taskID).append(" ?p ?uuid . "); triples.append("?expID <http://iguana-benchmark.eu/properties/task> "+taskID+" ."); triples.append("?suiteId <http://iguana-benchmark.eu/properties/experiment> ?expID ."); triples.append("?expID <http://iguana-benchmark.eu/properties/task> ?taskID FILTER(?taskID="+taskID+")."); for (Field field : fields) { vars.append(field.getVar()).append(" "); triples.append(field.getTriples()).append(" "); } return QueryFactory.create("SELECT DISTINCT " + vars + " { " + triples + " }"); }
Example #19
Source File: ParserSPARQLStarTest.java From RDFstarTools with Apache License 2.0 | 5 votes |
protected ElementGroup getElementGroup( String queryString ) { final SPARQLParser parser = new ParserSPARQLStar(); final Query query = parser.parse(new Query(), queryString); assertTrue( query.isSelectType() ); assertTrue( "unexpected type (" + query.getQueryPattern().getClass() + ")", query.getQueryPattern() instanceof ElementGroup ); return (ElementGroup) query.getQueryPattern(); }
Example #20
Source File: TestCoverageEvaluator.java From RDFUnit with Apache License 2.0 | 5 votes |
private Collection<String> getReferenceSet(QueryExecutionFactory model, String query) { Collection<String> references = new ArrayList<>(); Query q = QueryFactory.create(query); try (QueryExecution qe = model.createQueryExecution(q)) { qe.execSelect().forEachRemaining( row -> references.add("<" + row.get("reference").toString() + ">") ); } return references; }
Example #21
Source File: Drivers.java From quetzal with Eclipse Public License 2.0 | 5 votes |
public static void runVerify(URL dataSet, String queryFile, SparqlSelectResult result) throws URISyntaxException, MalformedURLException, ParserConfigurationException, SAXException, IOException { Query q = JenaUtil.parse(queryFile); List<Var> vars = q.getProjectVars(); tryToCheck(dataSet, result, q, vars, Collections.<String,Object>emptyMap(), "solution", false); }
Example #22
Source File: TarqlQueryExecution.java From tarql with BSD 2-Clause "Simplified" License | 5 votes |
private QueryExecution createQueryExecution(Query query, Model model) { QueryExecution result = QueryExecutionFactory.create(query, model); PrefixMappingImpl prefixes = new PrefixMappingImpl(); prefixes.setNsPrefixes(tq.getPrologue().getPrefixMapping()); prefixes.setNsPrefix("tarql", tarql.NS); result.getContext().set(ExpandPrefixFunction.PREFIX_MAPPING, prefixes); return result; }
Example #23
Source File: ExTDB_Txn1.java From xcurator with Apache License 2.0 | 5 votes |
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 #24
Source File: QueryPatternSimplification.java From quetzal with Eclipse Public License 2.0 | 5 votes |
public Query simplify(Query q) { QueryPatternSimplification qps = new QueryPatternSimplification(); q.getQueryPattern().visit(qps); Element newelt = qps.getResult(); Query ret = q.cloneQuery(); ret.setQueryPattern(newelt); return ret; }
Example #25
Source File: SelectQueryPartialCopyVisitor.java From sparql-generate with Apache License 2.0 | 5 votes |
@Override public void visitSelectResultForm(final Query q) { SPARQLExtQuery query = asSPARQLExtQuery(q); output.setDistinct(query.isDistinct()); output.setReduced(query.isReduced()); output.setQueryResultStar(query.isQueryResultStar()); VarExprList project = query.getProject(); project.forEachVar((v) -> { output.addResultVar(v, project.getExpr(v)); }); }
Example #26
Source File: OWLQLToNonRecursiveDatalogCompiler.java From quetzal with Eclipse Public License 2.0 | 5 votes |
/** * @param args */ public static void main(String[] args) throws Exception { if (args.length<2) { logger.error("At least two arguments expected: queryFile ontologyFile (ontologyFile)* "); return; } logger.debug("START"); File queryFile = new File(args[0]); File[] ontFiles = new File[args.length-1]; for (int i=1; i<args.length;i++) { ontFiles[i-1] = new File(args[i]); } List<ConjunctiveQuery> conjQueries = OCUtils.loadConjunctiveQueries(queryFile); OWLOntology ont = OCUtils.load(ontFiles); /*Set<ConjunctiveQuery> memQueries = Utils.getMembershipQuery(ont); logger.info("Number of membership queries: {}",memQueries.size()); for (ConjunctiveQuery cq: memQueries) { logger.info(cq); } conjQueries.addAll(memQueries);*/ int count = 1; OWLQLToNonRecursiveDatalogCompiler compiler = new OWLQLToNonRecursiveDatalogCompiler(ont, null, null); for (ConjunctiveQuery q: conjQueries) { //logger.info("Building non-recursive datalog for query: {}",q); long time = System.currentTimeMillis(); RuleSystem rs = compiler.compileToNonRecursiveDatalog(q); //logger.info("Non-recursive datalog built in {} ms", (System.currentTimeMillis()-time)); //logger.info("Result:\n", rs); Query cq =RuleSystemToUnionQuery.toUnionQuery(rs); StringBuffer buf =new StringBuffer(); buf.append(cq+"\n"); //logger.info("Generated Query:\n{}", buf); System.out.println("# Query #"+count); System.out.println(buf+";"); count++; } }
Example #27
Source File: ARQTest.java From tarql with BSD 2-Clause "Simplified" License | 5 votes |
@Test public void testDetectSelectStar() { Query selectStar = QueryFactory.create("SELECT * { ?s ?p ?o }"); assertTrue(selectStar.isQueryResultStar()); Query selectVars = QueryFactory.create("SELECT ?s ?p ?o { ?s ?p ?o }"); assertFalse(selectVars.isQueryResultStar()); }
Example #28
Source File: RdfStoreQueryExecutionFactory.java From quetzal with Eclipse Public License 2.0 | 5 votes |
public static QueryExecution create(String sparql, Model model, OWLQLSPARQLCompiler compiler) { checkArg(model); return new DB2QueryExecutionImpl((com.ibm.research.rdf.store.jena.Query) RdfStoreQueryFactory.create(sparql), (DB2Graph) model.getGraph(), compiler); }
Example #29
Source File: TriplePatternExtractorTest.java From NLIWOD with GNU Affero General Public License v3.0 | 5 votes |
@Test public void extractProjectionVarsTest() { Query q = QueryFactory.create("prefix dbp: <http://dbpedia.org/resource/> " + "prefix dbp2: <http://dbpedia.org/ontology/> " + "select ?x where { dbp:total dbp2:thumbnail ?thumbnail. " + "?thumbnail dbp2:thumbnail ?x. ?y dbp2:thumbnail ?c}"); String realAnswer = "[?thumbnail @http://dbpedia.org/ontology/thumbnail ?x]"; TriplePatternExtractor triplePatternExtractor = new TriplePatternExtractor(); Map<Var,Set<Triple>> answer = triplePatternExtractor.extractTriplePatternsForProjectionVars(q); Set<Triple> extractedTriple = answer.get(q.getProjectVars().get(0)); Assert.assertTrue(realAnswer.equals(extractedTriple.toString())); }
Example #30
Source File: QueryGenerationFactoryCache.java From RDFUnit with Apache License 2.0 | 5 votes |
@Override public Query getSparqlQuery(TestCase testCase) { try { return queryCache.get(testCase); } catch (ExecutionException e) { log.error("Error retrieving query from cache", e); throw new IllegalStateException("Error retrieving query from cache", e); } }