org.apache.jena.sparql.syntax.Element Java Examples

The following examples show how to use org.apache.jena.sparql.syntax.Element. 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: RuleSystemToQueries.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
protected static Element processBoundFormula(AtomicFormula af) {
	assert af.getPredicate().getName().equals(Rule.BUILT_IN_BOUND_VAR) : af;
	assert af.getArity() >1 : af;
	assert af.getArguments().get(0).isVariable() : af;
	VariableExpr var = (VariableExpr) af.getArguments().get(0);
	Element ret;
	if (af.getArity() == 2) {
		Expr e1 = af.getArguments().get(1);
		ret = new ElementBind(Var.alloc(var.getName()), toJenaExpr(e1));
	} else {
		assert af.getArguments().size() == af.getArity();
		ElementUnion  union = new ElementUnion();
		for (int i=1;i<af.getArity();i++) {
			Expr e = af.getArguments().get(i);
			union.addElement(new ElementBind(Var.alloc(var.getName()), toJenaExpr(e)));
		}
		ret = union;
	}
	return ret;
}
 
Example #2
Source File: ConjunctiveQuery.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public void setQueryPattern(Element graphPattern) {
	if (graphPattern instanceof ElementTriplesBlock) {
		query.setQueryPattern((ElementTriplesBlock)graphPattern);
	} else if (graphPattern instanceof ElementGroup) {
		ElementGroup group = (ElementGroup) graphPattern;
		for (Element e: flatten(group)) {
			if (e instanceof ElementPathBlock) {
				ElementPathBlock epb = (ElementPathBlock) e;
				for (TriplePath p:epb.getPattern().getList()) {
					if (!p.isTriple()) {
						throw new IllegalArgumentException("Conjunctive query only accepts a basic graph patterns. No triple path:  "+ p+"\n"+graphPattern );	
					}
				}
			} else 	if (!(e instanceof ElementTriplesBlock)
			&&  !(e instanceof ElementFilter)) {
				throw new IllegalArgumentException("Conjunctive query only accepts a basic graph patterns: "+ e+"\n"+graphPattern );	
			}
		}
		query.setQueryPattern(graphPattern);
	}
	else {
		throw new IllegalArgumentException("Conjunctive query only accepts a basic graph patterns: "+ graphPattern);				
	}
	
}
 
Example #3
Source File: RuleSystemToUnionQuery.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
protected static Element instantiateBody(Query cq, List<? extends Expr> args ) {
	
	Map<Var, Node> oldVar2NewValue = new HashMap<Var, Node>();
	List<String> resultVars = cq.getResultVars();
	Set<String> alreadySeenVars = new HashSet<String>();
	
	assert resultVars.size() == args.size() : resultVars+", " +args	;
	for (int i=0;i<resultVars.size();i++) {
		String  old = resultVars.get(i);	
		if (alreadySeenVars.add(old)) {
			Expr newE = args.get(i);
			Node newN = toNode(newE);
			oldVar2NewValue.put(Var.alloc(old), newN);
		}		
	}
	VariableSubstitutionElementVisitor visitor = new VariableSubstitutionElementVisitor(oldVar2NewValue);
	cq.getQueryPattern().visit(visitor);
	Element result = visitor.getResult();
	return result;
}
 
Example #4
Source File: ElementFormat.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public boolean equalTo(Element el, NodeIsomorphismMap isoMap) {
    if (!(el instanceof ElementFormat)) {
        return false;
    }
    ElementFormat el2 = (ElementFormat) el;
    if(!expr.equals(el2.getExpr())) {
        return false;
    }
    if (size() != el2.size()) {
        return false;
    }
    List<Element> exprs2 = el2.getTExpressions();
    for (int i = 0; i < size(); i++) {
        if (!exprs.get(i).equals(exprs2.get(i))) {
            return false;
        }
    }
    return true;
}
 
Example #5
Source File: ElementBox.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public boolean equalTo(Element el, NodeIsomorphismMap isoMap) {
    if (!(el instanceof ElementBox)) {
        return false;
    }
    ElementBox el2 = (ElementBox) el;
    if (size() != el2.size()) {
        return false;
    }
    List<Element> exprs2 = el2.getTExpressions();
    for (int i = 0; i < size(); i++) {
        if (!exprs.get(i).equals(exprs2.get(i))) {
            return false;
        }
    }
    return true;
}
 
Example #6
Source File: ElementTGroup.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public boolean equalTo(Element el, NodeIsomorphismMap isoMap) {
    if (!(el instanceof ElementTGroup)) {
        return false;
    }
    ElementTGroup el2 = (ElementTGroup) el;
    if (distinct != el2.distinct) {
        return false;
    }
    if (sep == null && el2.sep != null || sep != null && !sep.equals(el2.sep)) {
        return false;
    }
    if (size() != el2.size()) {
        return false;
    }
    List<Element> exprs2 = el2.getTExpressions();
    for (int i = 0; i < size(); i++) {
        if (!exprs.get(i).equals(exprs2.get(i))) {
            return false;
        }
    }
    return true;
}
 
Example #7
Source File: ElementPerform.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public boolean equalTo(Element el, NodeIsomorphismMap isoMap) {
    if (!(el instanceof ElementPerform)) {
        return false;
    }
    ElementPerform el2 = (ElementPerform) el;
    if (!name.equals(el2.name)) {
        return false;
    }
    if (params == null && el2.params != null
            || params != null && el2.params == null) {
        return false;
    }
    if (params == null && el2.params == null) {
        return true;
    }
    if(params.size() != el2.params.size()) {
        return false;
    }
    for (int i = 0; i < params.size(); i++) {
        if (!params.get(i).equals(el2.params.get(i))) {
            return false;
        }
    }
    return true;
}
 
Example #8
Source File: ElementSource.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public boolean equalTo(Element el2, NodeIsomorphismMap isoMap) {
    if (el2 == null) {
        return false;
    }
    if (!(el2 instanceof ElementSource)) {
        return false;
    }
    ElementSource s2 = (ElementSource) el2;
    if (!this.getVar().equals(s2.getVar())) {
        return false;
    }
    if (!this.getSource().equals(s2.getSource())) {
        return false;
    }
    if (this.getAccept()== null && s2.getAccept()!=null || this.getAccept()!=null&&!this.getAccept().equals(s2.getAccept())) {
        return false;
    }
    return true;
}
 
Example #9
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 #10
Source File: SelectExtractionVisitor.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public void visitBindingClauses(SPARQLExtQuery query) {
    if (query.isSelectType()) {
        return;
    }
    if (query.hasAggregators() || query.hasGroupBy()) {
        return;
    }
    for (Element el : query.getBindingClauses()) {
    	isDummyQuery = false;
        if (el instanceof ElementIterator) {
            ElementIterator elementIterator = (ElementIterator) el;
            output.addProjectVars(elementIterator.getVars());
        } else if (el instanceof ElementSource) {
            ElementSource elementSource = (ElementSource) el;
            output.addResultVar(elementSource.getVar());
        } else if (el instanceof ElementBind) {
            ElementBind elementBind = (ElementBind) el;
            output.addResultVar(elementBind.getVar());
        } else {
            throw new UnsupportedOperationException("should not reach"
                    + " this point");
        }
    }
}
 
Example #11
Source File: SPARQLExtFormatterElement.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
private void visitNodePattern(String label, Node node, Element subElement) {
    int len = label.length();
    out.print(label);
    out.print(" ");
    String nodeStr = (node == null) ? "*" : slotToString(node);
    out.print(nodeStr);
    len += nodeStr.length();
    if (GRAPH_FIXED_INDENT) {
        out.incIndent(INDENT);
        out.newline(); // NB and newline
    } else {
        out.print(" ");
        len++;
        out.incIndent(len);
    }
    visitAsGroup(subElement);

    if (GRAPH_FIXED_INDENT) {
        out.decIndent(INDENT);
    } else {
        out.decIndent(len);
    }
}
 
Example #12
Source File: PropertyPathRewrite.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public Element transform(TriplePath tp,boolean bestEffort, NewVariableGenerator vargen, boolean[] resultHasPropertyPaths) {
	Triple t = tp.asTriple();
	if (t!=null) {
		// this is a simple triple
		ElementTriplesBlock ret =new ElementTriplesBlock();
		ret.addTriple(t);
		return ret;
	}
	assert !tp.isTriple();
	assert tp.getPredicate()==null: tp;
	JenaPathRewrite pr = new JenaPathRewrite(tp.getSubject(), tp.getObject(), bestEffort, vargen);
	tp.getPath().visit(pr);
	if (resultHasPropertyPaths!=null) {
		resultHasPropertyPaths[0] = pr.resultWithPropertyPaths();
	}
	return pr.getResult();
}
 
Example #13
Source File: SPARQLExtQuerySerializer.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public void visitQueryPattern(Query q) {
    SPARQLExtQuery query = asSPARQLExtQuery(q);
    if(query.isTemplateType()) {
        if (query.isDistinct()) {
            out.print("DISTINCT ");
        }
        if (query.isReduced()) {
            out.print("REDUCED ");
        }
    }
    if (query.getQueryPattern() != null) {
        out.print("WHERE ");
        out.incIndent();
        out.newline();
        Element el = query.getQueryPattern();
        fmtElement.visitAsGroup(el);
        out.decIndent();
        out.newline();
    }
}
 
Example #14
Source File: SPARQLExtCli.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
private static void replaceSourcesIfRequested(CommandLine cli, SPARQLExtQuery query) {
	final Properties replacementSources = cli.getOptionProperties(ARG_SOURCE_LONG);

	List<Element> updatedSources = query.getBindingClauses().stream().map(element -> {
		if (element instanceof ElementSource) {
			ElementSource elementSource = (ElementSource) element;
			String sourceURI = elementSource.getSource().toString(query.getPrefixMapping(), false);

			if (replacementSources.containsKey(sourceURI)) {
				Node replacementSource = NodeFactory.createURI(replacementSources.getProperty(sourceURI));

				LOG.info("Replaced source <{}> with <{}>.", sourceURI, replacementSource);

				return new ElementSource(replacementSource, elementSource.getAccept(), elementSource.getVar());
			}
		}

		return element;
	}).collect(Collectors.toList());

	query.setBindingClauses(updatedSources);
}
 
Example #15
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 #16
Source File: PropertyPathRewrite.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void visit(P_Alt p) {
	p.getLeft().visit(this);
	Element left = result;
	if (left!=null) {
		p.getRight().visit(this);
		Element right = result;
		if (right!=null) {
			ElementUnion ret = new ElementUnion(left);
			ret.addElement(right);
			result = ret;
		} else {
			result = null;
		}
	} else {
		result = null;
	}
}
 
Example #17
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 #18
Source File: ElementTransformSPARQLStar.java    From RDFstarTools with Apache License 2.0 6 votes vote down vote up
@Override
public Element transform( ElementBind eb, Var v, Expr expr2 )
{
	if (    ( eb.getExpr() instanceof NodeValue )
	     && ( ((NodeValue) eb.getExpr()).getNode() instanceof Node_Triple ) )
	{
		final NodeValue nv = (NodeValue) eb.getExpr();
		final Node_Triple nt = (Node_Triple) nv.getNode();
		final Triple tp = nt.get();

		final ElementPathBlock epb = new ElementPathBlock();
		unNestBindClause(tp, epb, v);
		return epb;
	}
	else
		return super.transform(eb, v, expr2);
}
 
Example #19
Source File: PlanFactory.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public void visit(ElementBox el) {
    final List<Expr> texprs = new ArrayList<>();
    texprs.add(new E_Function(ST.incr, new ExprList()));
    List<Element> elements = el.getTExpressions();
    for (int i = 0; i < elements.size(); i++) {
        elements.get(i).visit(this);
        if (result instanceof E_Function && ((E_Function) result).getFunctionIRI().equals(ST.concat)) {
            texprs.addAll(((E_Function) result).getArgs());
        } else {
            texprs.add(result);
        }
    }
    texprs.add(new E_Function(ST.decr, new ExprList()));
    result = new E_Function(ST.concat, new ExprList(texprs));
}
 
Example #20
Source File: QueryPatternSimplification.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
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 #21
Source File: SPARQLExtFmtExprSPARQL.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ExprFunctionOp funcOp) {
	String fn = funcOp.getFunctionPrintName(context);
	if (funcOp instanceof E_NotExists) {
		fn = "NOT EXISTS";
	} else if (funcOp instanceof E_Exists) {
		fn = "EXISTS";
	} else {
		throw new ARQInternalErrorException("Unrecognized ExprFunctionOp: " + fn);
	}

	SPARQLExtFormatterElement fmtElt = new SPARQLExtFormatterElement(out, context);
	out.print(fn);
	out.print(" ");
	int indent = out.getAbsoluteIndent();
	int currentCol = out.getCol();
	try {
		out.setAbsoluteIndent(currentCol);
		Element el = funcOp.getElement();
		if (el == null) {
			el = OpAsQuery.asQuery(funcOp.getGraphPattern()).getQueryPattern();
		}
		el.visit(fmtElt);
	} finally {
		out.setAbsoluteIndent(indent);
	}
}
 
Example #22
Source File: OutputClauseNormalizer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ElementFormat el) {
    visit(el.getExpr());
    for (Element e : el.getTExpressions()) {
        e.visit(this);
    }
    result = el;
}
 
Example #23
Source File: OutputClauseNormalizer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ElementTGroup el) {
    for (Element e : el.getTExpressions()) {
        e.visit(this);
    }
    result = el;
}
 
Example #24
Source File: ConjunctiveQuery.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
public void add(Element elt) {
	if (query.getQueryPattern() instanceof ElementTriplesBlock) {
		ElementGroup group = new ElementGroup();
		group.addElement(query.getQueryPattern());
		group.addElement(elt);
		query.setQueryPattern(group);
	} else {
		assert query.getQueryPattern() instanceof ElementGroup;
		ElementGroup group = (ElementGroup) query.getQueryPattern();
		group.addElement(elt);
	}
}
 
Example #25
Source File: QueryAggregatesNormalizer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private List<Element> normalizeOutput(List<Element> elements, ExprNormalizer enzer) {
    final OutputClauseNormalizer nzer = new OutputClauseNormalizer(enzer);
    final List<Element> group = new ArrayList<>();
    for (Element el : elements) {
        el.visit(nzer);
        group.add(nzer.getResult());
    }
    return group;
}
 
Example #26
Source File: OutputClauseNormalizer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ElementTGroup el) {
    List<Element> nzed = new ArrayList<>();
    for (Element e : el.getTExpressions()) {
        e.visit(this);
        nzed.add(result);
    }
    result = new ElementTGroup(nzed, el.isDistinct(), el.getSeparator());
}
 
Example #27
Source File: RuleSystemToUnionQuery.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void visit(ElementSubQuery e) {
	Query sq = e.getQuery();
	VariableSubstitutionElementVisitor qps = new VariableSubstitutionElementVisitor(oldVar2NewValue);
	sq.getQueryPattern().visit(qps);
	Element newelt = qps.getResult();
	Query newsq = sq.cloneQuery();
	newsq.setQueryPattern(newelt);
	result = new ElementSubQuery(newsq);
}
 
Example #28
Source File: QueryPatternNormalizer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ElementGroup el) {
    final ElementGroup res = new ElementGroup();
    for (final Element element : el.getElements()) {
        element.visit(this);
        res.addElement(result);
    }
    result = res;
}
 
Example #29
Source File: ElementSubExtQuery.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equalTo(Element other, NodeIsomorphismMap isoMap) {
    if (!(other instanceof ElementSubExtQuery)) {
        return false;
    }
    ElementSubExtQuery el = (ElementSubExtQuery) other;
    return query.equals(el.query);
}
 
Example #30
Source File: SPARQLExtQuerySerializer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void visitBindingClauses(SPARQLExtQuery query) {
    if (query.getBindingClauses() == null) {
        return;
    }
    for (Element iteratorOrSource : query.getBindingClauses()) {
        iteratorOrSource.visit(fmtElement);
        out.newline();
    }
}