org.apache.jena.query.QueryFactory Java Examples
The following examples show how to use
org.apache.jena.query.QueryFactory.
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: 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 #2
Source File: Qald7CreationTool.java From NLIWOD with GNU Affero General Public License v3.0 | 6 votes |
private boolean checkIsOnlydbo(final String sparqlQuery) throws QueryParseException { if (sparqlQuery == null) { return false; } Query q = QueryFactory.create(sparqlQuery); PrefixMapping prefixMap = q.getPrefixMapping(); Map<String, String> map = new HashMap<>(prefixMap.getNsPrefixMap()); Set<Entry<String, String>> remove = new HashSet<>(); for (Entry<String, String> it : map.entrySet()) { if (it.getKey().equals("rdf") || it.getKey().equals("rdfs") || it.getValue().equals(DBO_URI) || it.getValue().equals(RES_URI)) { remove.add(it); } } map.entrySet().removeAll(remove); return map.isEmpty(); }
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: ParserSPARQLStarTest.java From RDFstarTools with Apache License 2.0 | 6 votes |
@Test public void registrationOK() { assertTrue( SPARQLParserRegistry.containsParserFactory(SPARQLStar.syntax) ); assertTrue( SPARQLParserRegistry.parser(SPARQLStar.syntax) instanceof ParserSPARQLStar ); final String queryString = "SELECT * WHERE { <<?s ?p ?o>> ?p2 ?o2 }"; QueryFactory.create(queryString, SPARQLStar.syntax); try { QueryFactory.create(queryString); // This should fail with the } // default SPARQL parser. catch ( QueryParseException e ) { // Hence, this exception return; // is expected. } fail( "Expected exception not thrown." ); }
Example #5
Source File: ARQTest.java From tarql with BSD 2-Clause "Simplified" License | 6 votes |
@Test public void testQuerySetValuesDataBlock() { List<Var> header = vars("a", "b"); Binding b1 = binding(header, "1", "2"); Binding b2 = binding(header, "3", "4"); Query q = QueryFactory.create("SELECT * {}"); q.setValuesDataBlock(header, bindings(b1, b2)); ResultSet rs = QueryExecutionFactory.create(q, ModelFactory.createDefaultModel()).execSelect(); assertEquals(Arrays.asList(new String[]{"a","b"}), rs.getResultVars()); assertTrue(rs.hasNext()); assertEquals(b1, rs.nextBinding()); assertTrue(rs.hasNext()); assertEquals(b2, rs.nextBinding()); assertFalse(rs.hasNext()); }
Example #6
Source File: ARQTest.java From tarql with BSD 2-Clause "Simplified" License | 6 votes |
@Test public void testQueryAddValuesInQueryPattern() { List<Var> header = vars("a", "b"); Binding b1 = binding(header, "1", "2"); Binding b2 = binding(header, "3", "4"); Query q = QueryFactory.create("SELECT * {}"); ElementGroup group = new ElementGroup(); ElementData table = new ElementData(); table.add(Var.alloc("a")); table.add(Var.alloc("b")); table.add(b1); table.add(b2); group.addElement(q.getQueryPattern()); group.addElement(table); q.setQueryPattern(group); ResultSet rs = QueryExecutionFactory.create(q, ModelFactory.createDefaultModel()).execSelect(); assertEquals(Arrays.asList(new String[]{"a","b"}), rs.getResultVars()); assertTrue(rs.hasNext()); assertEquals(b1, rs.nextBinding()); assertTrue(rs.hasNext()); assertEquals(b2, rs.nextBinding()); assertFalse(rs.hasNext()); }
Example #7
Source File: TagRdfUnitTestGenerator.java From RDFUnit with Apache License 2.0 | 6 votes |
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 #8
Source File: TestCaseWithTargetTest.java From RDFUnit with Apache License 2.0 | 6 votes |
@Test public void test() { TestCase innerTestCAse = Mockito.mock(TestCase.class); when(innerTestCAse.getSparqlWhere()).thenReturn(sparqlQuery); TestCase testCaseWithTarget = TestCaseWithTarget.builder() .testCase(innerTestCAse) .target(target) .filterSparql(" ?this <http://example.cpm/p> ?value .") .build(); String finalSparql = PrefixNSService.getSparqlPrefixDecl() + testCaseWithTarget.getSparqlWhere(); assertThat(finalSparql) .contains(target.getPattern()); try { QueryFactory.create(finalSparql); } catch (Exception e) { Fail.fail("Failed sparql query:\n" + finalSparql, e); } }
Example #9
Source File: PlanFactory.java From sparql-generate with Apache License 2.0 | 6 votes |
/** * A factory that creates a {@link RootPlan} from a query. * * @param queryStr the string representation of the SPARQL-Generate or * SPARQL-Template Query. * @param base the base URI, if not set explicitly in the query string * @return the RootPlan that may be used to execute the query. */ public static final RootPlan create(final String queryStr, String base) { Objects.requireNonNull(queryStr, "Parameter string must not be null"); SPARQLExtQuery query; try { query = (SPARQLExtQuery) QueryFactory.create(queryStr, base, SPARQLExt.SYNTAX); if(!query.explicitlySetBaseURI()) { query.setBaseURI(base); } } catch (QueryParseException ex) { throw new SPARQLExtException( "Error while parsing the query \n" + queryStr, ex); } LOG.trace("Creating plan for query: \n" + query); return create(query); }
Example #10
Source File: TestGeneratorImpl.java From RDFUnit with Apache License 2.0 | 6 votes |
@Override public boolean isValid() { Query q; if (pattern == null) { log.error("{} : Pattern {} does not exist", getUri(), getPattern()); return false; } try { q = QueryFactory.create(PrefixNSService.getSparqlPrefixDecl() + getQuery()); } catch (Exception e) { log.error("{} Cannot parse query:\n{}", getUri(), PrefixNSService.getSparqlPrefixDecl() + getQuery(), e); return false; } Collection<Var> sv = q.getProjectVars(); if (sv.size() != pattern.getParameters().size() + 1) { log.error("{} Select variables are different than Pattern parameters", getUri()); return false; } return true; }
Example #11
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 #12
Source File: CombineManifest.java From incubator-taverna-language with Apache License 2.0 | 6 votes |
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 #13
Source File: CombineManifest.java From incubator-taverna-language with Apache License 2.0 | 6 votes |
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 #14
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 #15
Source File: AlgebraEx.java From xcurator with Apache License 2.0 | 6 votes |
public static void main(String []args) { String s = "SELECT DISTINCT ?s { ?s ?p ?o }"; // Parse Query query = QueryFactory.create(s) ; System.out.println(query) ; // Generate algebra Op op = Algebra.compile(query) ; op = Algebra.optimize(op) ; System.out.println(op) ; // Execute it. QueryIterator qIter = Algebra.exec(op, ExQuerySelect1.createModel()) ; // Results for ( ; qIter.hasNext() ; ) { Binding b = qIter.nextBinding() ; System.out.println(b) ; } qIter.close() ; }
Example #16
Source File: OCUtils.java From quetzal with Eclipse Public License 2.0 | 6 votes |
public static List<ConjunctiveQuery> loadConjunctiveQueries(File queryFile) throws IOException { List<ConjunctiveQuery> ret = new ArrayList<ConjunctiveQuery>(); Reader in = new FileReader(queryFile); for (String queryText: SPARQLFileParser.readQueries(in)) { queryText= queryText.trim(); if (queryText.startsWith("#")) { continue; } Query query= QueryFactory.create(queryText, Syntax.syntaxSPARQL_11); if (!query.isSelectType()) { logger.debug("Ignoring non select query: {}",query.toString()); continue; } logger.debug("Query: {}"+query); ret.add(new ConjunctiveQuery(query)); } in.close(); return ret; }
Example #17
Source File: OCUtils.java From quetzal with Eclipse Public License 2.0 | 6 votes |
public static List<Query> loadQueries(File queryFile) throws IOException { List<Query> ret = new ArrayList<Query>(); Reader in = new FileReader(queryFile); for (String queryText: SPARQLFileParser.readQueries(in)) { queryText= queryText.trim(); if (queryText.startsWith("#")) { continue; } Query query= QueryFactory.create(queryText, Syntax.syntaxSPARQL_11); if (!query.isSelectType()) { logger.debug("Ignoring non select query: {}",query.toString()); continue; } logger.debug("Query: {}"+query); ret.add(query); } in.close(); return ret; }
Example #18
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 #19
Source File: ExTDB5.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) ; 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 #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: OCUtils.java From quetzal with Eclipse Public License 2.0 | 5 votes |
public static ConjunctiveQuery parse(String sparqlQuery) { try { Query query= QueryFactory.create(sparqlQuery, Syntax.syntaxSPARQL_11); if (!query.isSelectType()) { throw new RuntimeException("Non select query: "+sparqlQuery.toString()); } return new ConjunctiveQuery(query); } catch (Exception e) { throw new RuntimeException(e); } }
Example #22
Source File: QueryProcessorImpl.java From quetzal with Eclipse Public License 2.0 | 5 votes |
public static Query compile(OWLQLSPARQLCompiler compiler, String query) { org.apache.jena.query.Query jq = QueryFactory.create(query); org.apache.jena.query.Query compiledJQ = compiler.compile(jq); logger.debug("QL query compilation:\n\t OriginalQuery: {}\n\t CompiledQuery:\n\t{}", jq, compiledJQ); Query ret = SparqlParserUtilities.parseSparqlString(compiledJQ.toString()); return ret; }
Example #23
Source File: QueryProcessorImpl.java From quetzal with Eclipse Public License 2.0 | 5 votes |
public static Query compile(OWLQLSPARQLCompiler compiler, String query) { org.apache.jena.query.Query jq = QueryFactory.create(query); org.apache.jena.query.Query compiledJQ = compiler.compile(jq); logger.debug("QL query compilation:\n\t OriginalQuery: {}\n\t CompiledQuery:\n\t{}", jq, compiledJQ); Query ret = SparqlParserUtilities.parseSparqlString(compiledJQ.toString()); return ret; }
Example #24
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 #25
Source File: TestQueryToStrring.java From quetzal with Eclipse Public License 2.0 | 5 votes |
protected static boolean test(String fileName) { Query q = SparqlParserUtilities.parseSparqlFile(fileName, Collections.<String,String>emptyMap()); System.out.println("Query:\n"+q); try { org.apache.jena.query.Query jenaq = QueryFactory.create(q.toString()); } catch (Exception e) { e.printStackTrace(System.out); return false; } return true; }
Example #26
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 #27
Source File: PatternQueryHandlerTest.java From IGUANA with GNU Affero General Public License v3.0 | 5 votes |
/** * Tests the convert to select method */ @Test public void testConverting() { ParameterizedSparqlString pss = new ParameterizedSparqlString(); pss.setCommandText(query); assertEquals(QueryFactory.create(expectedQuery), handler.convertToSelect(pss, varNames)); }
Example #28
Source File: SPARQL.java From NLIWOD with GNU Affero General Public License v3.0 | 5 votes |
/** * Tries to parse query with apache.jena . If fails, returns false. * * @param sparql * @return */ public static boolean isValidSparqlQuery(final String sparql) { try { QueryFactory.create(sparql); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
Example #29
Source File: InstancesQueryHandler.java From IGUANA with GNU Affero General Public License v3.0 | 5 votes |
@Override public Model generateTripleStats(String taskID, String resource, String property) { QueryStatistics qs = new QueryStatistics(); String rdfs = "http://www.w3.org/2000/01/rdf-schema#"; Model model = ModelFactory.createDefaultModel(); for (File queryFile : queryFiles) { try { String query = FileUtils.readLineAt(0, queryFile); Query q = QueryFactory.create(query); qs.getStatistics(q); QueryStatistics qs2 = new QueryStatistics(); qs2.getStatistics(q); String subject = resource + hashcode + "/" + queryFile.getName(); model.add(model.createResource(subject), ResourceFactory.createProperty(rdfs + "ID"), queryFile.getName().replace("sparql", "")); model.add(model.createResource(subject), RDFS.label, query); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "aggregations"), model.createTypedLiteral(qs2.aggr)); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "filter"), model.createTypedLiteral(qs2.filter)); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "groupBy"), model.createTypedLiteral(qs2.groupBy)); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "having"), model.createTypedLiteral(qs2.having)); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "triples"), model.createTypedLiteral(qs2.triples)); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "offset"), model.createTypedLiteral(qs2.offset)); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "optional"), model.createTypedLiteral(qs2.optional)); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "orderBy"), model.createTypedLiteral(qs2.orderBy)); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "union"), model.createTypedLiteral(qs2.union)); } catch (IOException e) { LOGGER.error("[QueryHandler: {{}}] Cannot read file {{}}", this.getClass().getName(), queryFile.getName()); } } return model; }
Example #30
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() ; } }