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

The following examples show how to use org.apache.jena.query.Query. 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   Author: 20n   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: rdflint   Author: imas   File: CustomQueryValidator.java    License: MIT License 6 votes vote down vote up
@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 #3
Source Project: trellis   Author: trellis-ldp   File: TriplestoreResource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #4
Source Project: Processor   Author: AtomGraph   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 #5
Source Project: NLIWOD   Author: dice-group   File: TriplePatternExtractor.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 #6
Source Project: shacl   Author: TopQuadrant   File: ARQFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #7
Source Project: sparql-generate   Author: sparql-generate   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 #8
Source Project: sparql-generate   Author: sparql-generate   File: QueryAggregatesNormalizer.java    License: Apache License 2.0 6 votes vote down vote up
@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 #9
Source Project: IGUANA   Author: dice-group   File: PatternQueryHandler.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 #10
Source Project: sparql-generate   Author: sparql-generate   File: SPARQLExtQuerySerializer.java    License: Apache License 2.0 6 votes vote down vote up
@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 #11
Source Project: quetzal   Author: Quetzal-RDF   File: Drivers.java    License: Eclipse Public License 2.0 6 votes vote down vote up
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 #12
Source Project: tinkerpop   Author: apache   File: SparqlToGremlinCompiler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #13
Source Project: sparql-generate   Author: sparql-generate   File: SelectExtractionVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@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 #14
Source Project: quetzal   Author: Quetzal-RDF   File: RuleforJena.java    License: Eclipse Public License 2.0 6 votes vote down vote up
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 #15
Source Project: tarql   Author: tarql   File: TarqlQueryExecution.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 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 #16
Source Project: xcurator   Author: xcurator   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 #17
Source Project: sparql-generate   Author: sparql-generate   File: SPARQLExtQuerySerializer.java    License: Apache License 2.0 6 votes vote down vote up
@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 #18
Source Project: RDFstarTools   Author: RDFstar   File: ElementTransformSPARQLStarTest.java    License: Apache License 2.0 5 votes vote down vote up
protected void checkBgpAndBindOnlyQuery( String sparqlstarQueryString, String expectedResultQuery )
{
	final String baseIRI = null;
	final Query expectedQuery = QueryFactory.create(expectedResultQuery, baseIRI, Syntax.syntaxSPARQL);
	final ElementGroup expectedEG = (ElementGroup) expectedQuery.getQueryPattern();

	final Query convertedQuery = convert( sparqlstarQueryString );
	final ElementGroup convertedEG = (ElementGroup) convertedQuery.getQueryPattern();
	
	checkForEquivalence( expectedEG, mergeElementPathBlocks(convertedEG) );
}
 
Example #19
Source Project: RDFstarTools   Author: RDFstar   File: ParserSPARQLStarTest.java    License: Apache License 2.0 5 votes vote down vote up
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 Project: sparql-generate   Author: sparql-generate   File: SelectExtractionVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visitLimit(final Query query) {
    if (query.hasLimit()) {
    	isDummyQuery = false;
        output.setLimit(query.getLimit());
    }
}
 
Example #21
Source Project: shacl   Author: TopQuadrant   File: ARQFactory.java    License: Apache License 2.0 5 votes vote down vote up
public Query createExpressionQuery(String expression) {
	Query result = string2Query.get(expression);
	if(result == null) {
		String queryString = "SELECT (" + expression + ") WHERE {}";
		result = doCreateQuery(queryString);
		if(useCaches) {
			string2Query.put(expression, result);
		}
	}
	return result;
}
 
Example #22
Source Project: shacl   Author: TopQuadrant   File: QueryExecutionFactoryFilter.java    License: Apache License 2.0 5 votes vote down vote up
private void printQuery(Query query, QuerySolution initialBinding) {
    if ( PRINT ) {
        String time = DateTimeUtils.nowAsString(timestamp); 
           System.err.print("~~ ");
           System.err.print(time);
           System.err.println(" ~~");
           System.err.println(initialBinding);
           System.err.print(query);
       }
}
 
Example #23
Source Project: sparql-generate   Author: sparql-generate   File: ParserSPARQLExt.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void validateParsedQuery(Query query) {
    SyntaxVarScope.check(query);
    if(query instanceof SPARQLExtQuery) {
        SPARQLExtSyntaxVarScope.check((SPARQLExtQuery) query);
    }
}
 
Example #24
Source Project: trellis   Author: trellis-ldp   File: TriplestoreResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This code is equivalent to the SPARQL query below.
 *
 * <p><pre><code>
 * SELECT ?predicate ?object ?type
 * WHERE {
 *   GRAPH trellis:PreferServerManaged {
 *      IDENTIFIER dc:isPartOf ?subject .
 *      ?subject ldp:isMemberOfRelation ?predicate .
 *      ?subject ldp:membershipResource ?object .
 *      ?subject ldp:insertedContentRelation ldp:MemberSubject .
 *      ?object rdf:type ?type .
 *   }
 * }
 * </code></pre>
 */
private Stream<Quad> fetchDirectMemberQuadsInverse() {
    final Query q = new Query();
    q.setQuerySelectType();
    q.addResultVar(PREDICATE);
    q.addResultVar(OBJECT);
    q.addResultVar(TYPE);

    final ElementPathBlock epb = new ElementPathBlock();
    epb.addTriple(create(toJena(identifier), toJena(DC.isPartOf), SUBJECT));
    epb.addTriple(create(SUBJECT, toJena(LDP.isMemberOfRelation), PREDICATE));
    epb.addTriple(create(SUBJECT, toJena(LDP.membershipResource), OBJECT));
    epb.addTriple(create(SUBJECT, toJena(LDP.insertedContentRelation), toJena(LDP.MemberSubject)));
    epb.addTriple(create(OBJECT, type.asNode(), TYPE));

    final ElementNamedGraph ng = new ElementNamedGraph(toJena(Trellis.PreferServerManaged), epb);

    final ElementGroup elg = new ElementGroup();
    elg.addElement(ng);

    q.setQueryPattern(elg);

    final Stream.Builder<Quad> builder = builder();
    final IRI ixnModel = getInteractionModel();
    final IRI subject = adjustIdentifier(identifier, ixnModel);
    rdfConnection.querySelect(q, qs -> builder.accept(rdf.createQuad(LDP.PreferMembership, subject,
                    getPredicate(qs), getObject(qs))));
    return builder.build();
}
 
Example #25
Source Project: NLIWOD   Author: dice-group   File: TriplePatternExtractor.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Returns all triple patterns in given SPARQL query that have the given
 * node in subject position, i.e. the outgoing triple patterns.
 * 
 * @param query The SPARQL query.
 */
public Set<Triple> extractOutgoingTriplePatterns(final Query query, final Node node) {
	Set<Triple> triplePatterns = extractTriplePattern(query, false);
	// remove triple patterns not containing triple patterns with given node
	// in subject position
	for (Iterator<Triple> iterator = triplePatterns.iterator(); iterator.hasNext();) {
		Triple triple = iterator.next();
		if (!triple.subjectMatches(node)) {
			iterator.remove();
		}
	}
	return triplePatterns;
}
 
Example #26
Source Project: quetzal   Author: Quetzal-RDF   File: OWLQLSPARQLCompiler.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * <p>
 * Usage: queryFile ontologyFile (ontologyFile)* 
 * </p>
 * <p>
 * where
 *   <ul>
 *   	<li>queryFile: indicates the location of a semicolon separated file containing the input SPARQL queries. </li>
 *      <li>ontologyFile: indicates the location of the TBox files</li>
 *   </ul> 
 * </p>
 * @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<Query> queries = OCUtils.loadQueries(queryFile);
	Model tboxmodel = ModelFactory.createDefaultModel();
	for (File f: ontFiles) {
		tboxmodel.read(f.toURI().toString());
	}
	
	int count = 1;
	OWLQLSPARQLCompiler compiler = new OWLQLSPARQLCompiler(tboxmodel, null, null);
	for (Query q: queries) {
		Query eq = compiler.compile(q);
		StringBuffer buf =new StringBuffer();
		buf.append(eq+"\n");
		System.out.println("# Query #"+count);
		System.out.println(buf+";");
		count++;
	}
}
 
Example #27
Source Project: quetzal   Author: Quetzal-RDF   File: RdfStoreQueryExecutionFactory.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public static QueryExecution create(String sparql, Dataset dataset, OWLQLSPARQLCompiler compiler) {
	checkArg(dataset);

	return new DB2QueryExecutionImpl((com.ibm.research.rdf.store.jena.Query)
			RdfStoreQueryFactory.create(sparql),
			(DB2Dataset) dataset, compiler);
}
 
Example #28
Source Project: RDFUnit   Author: AKSW   File: ComponentConstraintImpl.java    License: Apache License 2.0 5 votes vote down vote up
private Set<ResultAnnotation> createResultAnnotations() {
    String prefixes = validator.getPrefixDeclarations().stream()
            .map(p -> "PREFIX " + p.getPrefix() + ": <" + p.getNamespace() + ">")
            .collect(Collectors.joining("\n"));

    String originalSelectClause = validator.getSparqlQuery().substring(0,validator.getSparqlQuery().indexOf('{'));
    String constructedQuery = prefixes + "\n" + originalSelectClause + getSparqlWhere()

            .replaceFirst("(?i)\\s*ASK\\s*\\{", "SELECT \\?this WHERE \\{");

    try {
        Query query = QueryFactory.create(constructedQuery);

        return ResultAnnotationParser.builder()
                .query(query)
                .validator(validator)
                .component(component)
                .shape(shape)
                .canBindValueVariable(componentCanBindValueAnnotation())
                .build()
                .getResultAnnotations();
    } catch (Exception e) {

        throw new IllegalArgumentException(constructedQuery, e);
    }

}
 
Example #29
Source Project: quetzal   Author: Quetzal-RDF   File: Drivers.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public static Set<List<Object>> tryToCheck(URL datasetURL, SparqlSelectResult result,
		Query q, List<Var> vars, Map<String, Object> bindings, String relation, boolean expand) throws URISyntaxException,
		MalformedURLException, IOException {
	Dataset D = RDFDataMgr.loadDataset(
			datasetURL.toExternalForm(),
					datasetURL.getPath().endsWith(".nq")? Lang.NQUADS: Lang.NTRIPLES);
	return tryToCheck(D, result, q, vars, bindings, relation, expand);
}
 
Example #30
Source Project: sparql-generate   Author: sparql-generate   File: SelectQueryPartialCopyVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void startVisit(final Query query) {
    asSPARQLExtQuery(query);
    if(!query.isSelectType()) {
        throw new SPARQLExtException("Expecting a SELECT query:" + query);            
    }
}