Java Code Examples for org.apache.jena.query.Query#getQueryPattern()

The following examples show how to use org.apache.jena.query.Query#getQueryPattern() . 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: SelectExtractionVisitor.java    From sparql-generate with 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 2
Source File: SHACLPaths.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to parse a given string into a Jena Path.
 * Throws an Exception if the string cannot be parsed.
 * @param string  the string to parse
 * @param model  the Model to operate on (for prefixes)
 * @return a Path or a Resource if this is a URI
 */
public static Object getJenaPath(String string, Model model) throws QueryParseException {
	Query query = ARQFactory.get().createQuery(model, "ASK { ?a \n" + string + "\n ?b }");
	Element element = query.getQueryPattern();
	if(element instanceof ElementGroup) {
		Element e = ((ElementGroup)element).getElements().get(0);
		if(e instanceof ElementPathBlock) {
			Path path = ((ElementPathBlock) e).getPattern().get(0).getPath();
			if(path instanceof P_Link && ((P_Link)path).isForward()) {
				return model.asRDFNode(((P_Link)path).getNode());
			}
			else {
				return path;
			}
		}
		else if(e instanceof ElementTriplesBlock) {
			return model.asRDFNode(((ElementTriplesBlock) e).getPattern().get(0).getPredicate());
		}
	}
	throw new QueryParseException("Not a SPARQL 1.1 Path expression", 2, 1);
}
 
Example 3
Source File: PatternQueryHandler.java    From IGUANA with 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 4
Source File: OWLQLSPARQLCompiler.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Element transform(ElementTriplesBlock tb) {
	List<Triple> triples = tb.getPattern().getList();
	// convert set of triples to a rule system
	// here is where all variables in triples are assumed to be distinguished variables
	logger.debug("Triples:\n{}", triples);
	RuleSystem rs = new TriplesToRuleSystem(tbox).toRules(triples, allVars, true);
	logger.debug("Triples as rule system:\n{}", rs);
	//
	RuleSystem outrs = compileToNonRecursiveDatalog(rs);
	logger.debug("RuleSystem:\n{}", outrs );
	if (outrs!=null) {
		Query q = RuleSystemToUnionQuery.toUnionQuery(outrs);
		return q.getQueryPattern();		
	} else {
		/*ElementTriplesBlock ts = new ElementTriplesBlock();
		Node owlNothing =  Node.createURI(OWL.Nothing.getURI());
		Node rdfType  = Node.createURI(RDF.type.getURI());
		ts.addTriple(new Triple(owlNothing, rdfType, owlNothing));
		result = ts;*/
		return tb;
	}
}
 
Example 5
Source File: OWLQLSPARQLCompiler.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
private Query primCompile(Query query, Set<String> allVars) {
	// query must already be in dnf 
	Element e = query.getQueryPattern();
	Element newelt;	
	/*if (e instanceof ElementUnion) {
		ElementUnion union= new ElementUnion();
		for (Element ge : ((ElementUnion) e).getElements()) {
			Set<String> distinguishedVars = getMultipleOccurrenceVars(getVisibleVarsToOccurrences(ge));
			distinguishedVars.addAll(query.getResultVars());
			ExpandBasicGraphPatterns ebgp = new ExpandBasicGraphPatterns();
			Element newge = ebgp.expand(query.getQueryPattern(),  new LinkedList<String>(distinguishedVars), allVars);
			union.addElement(newge);
		}
		newelt = union;
	} else {
		Set<String> distinguishedVars = getMultipleOccurrenceVars(getVisibleVarsToOccurrences(e));*/
		ExpandBasicGraphPatterns ebgp = new ExpandBasicGraphPatterns();
		//distinguishedVars.addAll(query.getResultVars());
		newelt = ebgp.expand(query.getQueryPattern(), /* new LinkedList<String>(distinguishedVars),*/ allVars);
		
	//}
	Query ret = query.cloneQuery();
	ret.setQueryPattern(newelt);
	return ret;
	
}
 
Example 6
Source File: ElementTransformSPARQLStarTest.java    From RDFstarTools with 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 7
Source File: ParserSPARQLStarTest.java    From RDFstarTools with 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 8
Source File: QueryXExprNormalizer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void visitQueryPattern(Query query) {
    if (query.getQueryPattern() == null) {
        return;
    }
    final QueryPatternNormalizer nzer = new QueryPatternNormalizer();
    query.getQueryPattern().visit(nzer);
    query.setQueryPattern(nzer.getResult());
}
 
Example 9
Source File: SelectQueryPartialCopyVisitor.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void visitQueryPattern(final Query query) {
    ElementGroup group = new ElementGroup();
    if (query.getQueryPattern() != null) {
        Element el = query.getQueryPattern();
        if(!(el instanceof ElementGroup)) {
            throw new SPARQLExtException("should not reach this point");
        }
        ((ElementGroup) el).getElements().forEach(group::addElement);
    }
    output.setQueryPattern(group);
}
 
Example 10
Source File: SelectPlan.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private void augmentQuery(final Query q, final List<Var> variables, final List<Binding> values) {
	if (variables.isEmpty()) {
		return;
	}
	ElementGroup old = (ElementGroup) q.getQueryPattern();
	ElementGroup newQueryPattern = new ElementGroup();
	q.setQueryPattern(newQueryPattern);
	if (old.size() >= 1 && old.get(0) instanceof ElementData) {
		ElementData qData = (ElementData) old.get(0);
		int oldSize = qData.getRows().size();
		qData = mergeValues(qData, variables, values);
		newQueryPattern.addElement(qData);
		for (int i = 1; i < old.size(); i++) {
			newQueryPattern.addElement(old.get(i));
		}
		LOG.debug("New query has " + qData.getRows().size() + " initial values. It had " + oldSize
				+ " values before");
	} else {
		ElementData data = new ElementData();
		variables.forEach(data::add);
		values.forEach(data::add);
		newQueryPattern.addElement(data);
		old.getElements().forEach(newQueryPattern::addElement);
		// unexplainable, but did happen
		check(data, values);
	}
}
 
Example 11
Source File: PropertyPathToRules.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception{
PropertyPathToRules toRules = new PropertyPathToRules();
String q = "select * where { " +
		"?x (^<http://example.org/p>|<http://example.org/s>?)/(<http://example.org/q>| <http://example.org/r>)+/!(^<http://example.org/t>| ^<http://example.org/u>|<http://example.org/v> )?y ." +
		"?x <http://example.org/s>/<http://example.org/r>/^<http://example.org/t> ?y ." +
		"?x <http://example.org/s>/<http://example.org/r>+/^<http://example.org/t> ?y ." +
		"?x (<http://example.org/s>/<http://example.org/r>+/^<http://example.org/t>)+ ?y ." +
		"?x (<http://example.org/s>/(^(<http://example.org/r>+|<http://example.org/p>))+/(^<http://example.org/t>)+)+ ?y ." +
	"?x <http://example.org/s>/<http://example.org/r>/<http://example.org/t> ?y ." +
	"?x !(a|<http://example.org/s>|<http://example.org/r>| <http://example.org/t> ) ?y ." +
	"?x !(<http://example.org/r>|^<http://example.org/t>| ^a|<http://example.org/s> ) ?y ." +
		"}"; 
// ( iRIref | 'a' )
com.ibm.research.rdf.store.sparql11.model.Query db2rdfQuery =  SparqlParserUtilities.parseSparqlString(q);
System.out.println("Query:\n"+db2rdfQuery.toString());

//System.exit(0);

Query query = QueryFactory.create(q, Syntax.syntaxSPARQL_11);
System.out.println("Parsed Query:\n\t"+query);
ElementGroup group = (ElementGroup)  query.getQueryPattern();
ElementPathBlock p = (ElementPathBlock) group.getElements().get(0);
for (TriplePath path : p.getPattern().getList()) {
	System.out.println("Path: "+path);
	RuleSystem rs = toRules.toRules(path, true, "Triple", "NegatedPropertySetTriple");
	System.out.println("Equivalent Rule System (Main formula: "+rs.getMainHeadFormula()+"):\n"+rs);
	rs = rs.simplify(Collections.singleton(rs.getMainHeadFormula().getPredicate()));
	System.out.println("Equivalent Rule System after simplification (Main formula: "+rs.getMainHeadFormula()+"):\n"
			+rs);
	/*Graph<Predicate> graph = DatalogEngine.buildDependencyGraph(rs);
	LinkedList<Set<Predicate>> sccs =DatalogEngine.topologicalSortOfSCC(graph);
	System.out.println("Predicate dependency graph:\n"+graph);
	System.out.println("Topological sort of predicates:");
	for (Set<Predicate> scc: sccs) {
		System.out.println("\t"+scc);
	}*/
	AtomicFormula goal = new AtomicFormula(rs.getMainHeadFormula().getPredicate(), new ConstantExpr(0), new VariableExpr("Y"));
	RuleSystem mgrs = rs.magicSetTransformation(goal, true, true, false);
	Set<Predicate> predicatesToKeep = HashSetFactory.make();
	predicatesToKeep.add(goal.getPredicate());
	for (Predicate pred: mgrs.getHeadPredicates()) {
		if (pred instanceof MagicSetPredicate) {
			//predicatesToKeep.add(pred);
			/*Set<Predicate> preds = HashSetFactory.make();
			preds.add(goal.getPredicate());
			preds.add(pred);
			RuleSystem rules = mgrs.simplify(preds);
			System.out.println("Rule System For Magic set predicate: "+pred+"\n"+rules);
			*/
		}
	}
	mgrs = mgrs.simplify(predicatesToKeep);
	System.out.println("Rule System after magic set transformation (goal: "+goal+"):\n"+mgrs);
	/*graph = DatalogEngine.buildDependencyGraph(mgrs);
	sccs =DatalogEngine.topologicalSortOfSCC(graph);
	System.out.println("Predicate dependency graph:\n"+graph);
	System.out.println("Topological sort of predicates:");
	for (Set<Predicate> scc: sccs) {
		System.out.println("\t"+scc);
	}*/
}
	

}
 
Example 12
Source File: TarqlQueryExecution.java    From tarql with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Modifies a query so that it operates onto a table. This is achieved
 * by appending the table as a VALUES block to the end of the main
 * query pattern.
 * 
 * @param query Original query; will be modified in place
 * @param table Data table to be added into the query
 */
private void modifyQuery(Query query, final Table table) {
	ElementData tableElement = new ElementData() {
		@Override
		public Table getTable() {
			return table;
		}
	};
	for (Var var: table.getVars()) {
		// Skip ?ROWNUM for "SELECT *" queries -- see further below
		if (query.isSelectType() && query.isQueryResultStar() 
				&& var.equals(TarqlQuery.ROWNUM)) continue;
		tableElement.add(var);
	}
	ElementGroup groupElement = new ElementGroup();
	groupElement.addElement(tableElement);
	if (query.getQueryPattern() instanceof ElementGroup) {
		for (Element element: ((ElementGroup) query.getQueryPattern()).getElements()) {
			groupElement.addElement(element);
		}
	} else {
		groupElement.addElement(query.getQueryPattern());
	}
	query.setQueryPattern(groupElement);
	
	// For SELECT * queries, we don't want to include pseudo
	// columns such as ?ROWNUM that may exist in the table.
	// That's why we skipped ?ROWNUM further up.
	if (query.isSelectType() && query.isQueryResultStar()) {
		// Force expansion of "SELECT *" to actual projection list
		query.setResultVars();
		// Tell ARQ that it actually needs to pay attention to
		// the projection list
		query.setQueryResultStar(false);
		// And now we can add ?ROWNUM to the table, as the "*"
		// has already been expanded.
		tableElement.add(TarqlQuery.ROWNUM);
	}
	// Data can only be added to table after we've finished the
	// ?ROWNUM shenangians
	/*for (Binding binding: table.getRows()) {
		tableElement.add(binding);
	}*/
}