org.eclipse.rdf4j.query.algebra.ProjectionElem Java Examples

The following examples show how to use org.eclipse.rdf4j.query.algebra.ProjectionElem. 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: QueryAlgebraUtil.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Construct a SELECT query for a grouped bound check.
 * 
 * Pattern:
 * 
 * SELECT DISTINCT ?o_1 .. ?o_N WHERE { { s1 p1 ?o_1 FILTER ?o_1=o1 } UNION ... UNION { sN pN ?o_N FILTER ?o_N=oN }}
 * 
 * @param stmt
 * @param unionBindings
 * @return
 */
public static TupleExpr selectQueryStringBoundCheck(StatementPattern stmt, List<BindingSet> unionBindings) {
	
	Set<String> varNames = new HashSet<String>();
	
	Union union = new Union();
	union.setLeftArg(constructStatementCheckId(stmt, 0, varNames, unionBindings.get(0)) );
	Union tmp = union;
	int idx;
	for (idx=1; idx<unionBindings.size()-1; idx++) {
		Union _u = new Union();
		_u.setLeftArg( constructStatementCheckId(stmt, idx, varNames, unionBindings.get(idx)) );
		tmp.setRightArg(_u);
		tmp = _u;
	}
	tmp.setRightArg( constructStatementCheckId(stmt, idx, varNames, unionBindings.get(idx) ));
	
	ProjectionElemList projList = new ProjectionElemList();
	for (String var : varNames)
		projList.addElement( new ProjectionElem(var));
	
	Projection proj = new Projection(union, projList);

	return proj;
}
 
Example #2
Source File: HasSelfVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testTypePattern() throws Exception {
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    final Set<IRI> narcissistProps = new HashSet<>();
    narcissistProps.add(love);
    when(inferenceEngine.getHasSelfImplyingType(narcissist)).thenReturn(narcissistProps);
    final Var subj = new Var("s");
    final Var obj = new Var("o", narcissist);
    obj.setConstant(true);
    final Var pred = new Var("p", RDF.TYPE);
    pred.setConstant(true);

    final Projection query = new Projection(new StatementPattern(subj, pred, obj),
            new ProjectionElemList(new ProjectionElem("s", "subject")));
    query.visit(new HasSelfVisitor(conf, inferenceEngine));

    Assert.assertTrue(query.getArg() instanceof Union);
    final Union union = (Union) query.getArg();
    Assert.assertTrue(union.getRightArg() instanceof StatementPattern);
    Assert.assertTrue(union.getLeftArg() instanceof StatementPattern);
    final StatementPattern expectedLeft = new StatementPattern(subj, pred, obj);
    final StatementPattern expectedRight = new StatementPattern(subj, new Var("urn:love", love), subj);
    Assert.assertEquals(expectedLeft, union.getLeftArg());
    Assert.assertEquals(expectedRight, union.getRightArg());
}
 
Example #3
Source File: SomeValuesFromVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testSomeValuesFromDisabled() throws Exception {
    // Disable someValuesOf inference
    final AccumuloRdfConfiguration disabledConf = conf.clone();
    disabledConf.setInferSomeValuesFrom(false);
    // Configure a mock instance engine with an ontology:
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    Map<Resource, Set<IRI>> personSVF = new HashMap<>();
    personSVF.put(gradCourse, Sets.newHashSet(takesCourse));
    personSVF.put(course, Sets.newHashSet(takesCourse));
    personSVF.put(department, Sets.newHashSet(headOf));
    personSVF.put(organization, Sets.newHashSet(worksFor, headOf));
    when(inferenceEngine.getSomeValuesFromByRestrictionType(person)).thenReturn(personSVF);
    // Query for a specific type visit -- should not change
    StatementPattern originalSP = new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", person));
    final Projection originalQuery = new Projection(originalSP, new ProjectionElemList(new ProjectionElem("s", "subject")));
    final Projection modifiedQuery = originalQuery.clone();
    modifiedQuery.visit(new SomeValuesFromVisitor(disabledConf, inferenceEngine));
    Assert.assertEquals(originalQuery, modifiedQuery);
}
 
Example #4
Source File: ReflexivePropertyVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testReflexivePropertyDisabled() throws Exception {
    // Disable inference
    final RdfCloudTripleStoreConfiguration disabledConf = conf.clone();
    disabledConf.setInferReflexiveProperty(false);
    // Define a reflexive property
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    when(inferenceEngine.isReflexiveProperty(HAS_FAMILY)).thenReturn(true);
    // Construct a query, then make a copy and visit the copy
    final Projection query = new Projection(
            new StatementPattern(new Var("s", ALICE), new Var("p", HAS_FAMILY), new Var("o")),
            new ProjectionElemList(new ProjectionElem("s", "subject")));
    final Projection modifiedQuery = query.clone();
    modifiedQuery.visit(new ReflexivePropertyVisitor(disabledConf, inferenceEngine));
    // There should be no difference
    Assert.assertEquals(query, modifiedQuery);
}
 
Example #5
Source File: ReflexivePropertyVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testReflexiveProperty() throws Exception {
    // Define a reflexive property
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    when(inferenceEngine.isReflexiveProperty(HAS_FAMILY)).thenReturn(true);
    // Construct a query, then visit it
    final StatementPattern sp = new StatementPattern(new Var("s", ALICE), new Var("p", HAS_FAMILY), new Var("o"));
    final Projection query = new Projection(sp, new ProjectionElemList(new ProjectionElem("o", "member")));
    query.visit(new ReflexivePropertyVisitor(conf, inferenceEngine));
    // Expected structure after rewriting SP(:Alice :hasFamilyMember ?member):
    //
    // Union(
    //     originalSP(:Alice :hasFamilyMember ?member),
    //     ZeroLengthPath(:Alice, ?member)
    // )
    Assert.assertTrue(query.getArg() instanceof Union);
    final TupleExpr left = ((Union) query.getArg()).getLeftArg();
    final TupleExpr right = ((Union) query.getArg()).getRightArg();
    Assert.assertEquals(sp, left);
    Assert.assertTrue(right instanceof ZeroLengthPath);
    Assert.assertEquals(sp.getSubjectVar(), ((ZeroLengthPath) right).getSubjectVar());
    Assert.assertEquals(sp.getObjectVar(), ((ZeroLengthPath) right).getObjectVar());
}
 
Example #6
Source File: OneOfVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testOneOfDisabled() throws Exception {
    // Configure a mock instance engine with an ontology:
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    when(inferenceEngine.isEnumeratedType(SUITS)).thenReturn(true);
    when(inferenceEngine.getEnumeration(SUITS)).thenReturn(CARD_SUIT_ENUMERATION);
    when(inferenceEngine.isEnumeratedType(RANKS)).thenReturn(true);
    when(inferenceEngine.getEnumeration(RANKS)).thenReturn(CARD_RANK_ENUMERATION);

    // Query for a Suits and rewrite using the visitor:
    final Projection query = new Projection(
            new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", SUITS)),
            new ProjectionElemList(new ProjectionElem("s", "subject")));

    final AccumuloRdfConfiguration disabledConf = conf.clone();
    disabledConf.setInferOneOf(false);

    query.visit(new OneOfVisitor(disabledConf, inferenceEngine));

    // Expected structure: the original statement:
    assertTrue(query.getArg() instanceof StatementPattern);
    final StatementPattern actualCardSuitSp = (StatementPattern) query.getArg();
    final StatementPattern expectedCardSuitSp = new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", SUITS));
    assertEquals(expectedCardSuitSp, actualCardSuitSp);
}
 
Example #7
Source File: SparqlToPipelineTransformVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testProjection() throws Exception {
    StatementPattern isUndergrad = new StatementPattern(new Var("x"), constant(RDF.TYPE), constant(UNDERGRAD));
    StatementPattern isCourse = new StatementPattern(new Var("course"), constant(RDF.TYPE), constant(COURSE));
    StatementPattern hasEdge = new StatementPattern(new Var("x"), new Var("p"), new Var("course"));
    ProjectionElemList projectionElements = new ProjectionElemList(
            new ProjectionElem("p", "relation"),
            new ProjectionElem("course"));
    QueryRoot queryTree = new QueryRoot(new Projection(
            new Join(new Join(isCourse, hasEdge), isUndergrad),
            projectionElements));
    SparqlToPipelineTransformVisitor visitor = new SparqlToPipelineTransformVisitor(collection);
    queryTree.visit(visitor);
    Assert.assertTrue(queryTree.getArg() instanceof AggregationPipelineQueryNode);
    AggregationPipelineQueryNode pipelineNode = (AggregationPipelineQueryNode) queryTree.getArg();
    Assert.assertEquals(Sets.newHashSet("relation", "course"), pipelineNode.getAssuredBindingNames());
}
 
Example #8
Source File: SparqlToPipelineTransformVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiProjection() throws Exception {
    StatementPattern isUndergrad = new StatementPattern(new Var("x"), constant(RDF.TYPE), constant(UNDERGRAD));
    StatementPattern isCourse = new StatementPattern(new Var("course"), constant(RDF.TYPE), constant(COURSE));
    StatementPattern hasEdge = new StatementPattern(new Var("x"), new Var("p"), new Var("course"));
    ProjectionElemList courseHasRelation = new ProjectionElemList(
            new ProjectionElem("p", "relation"),
            new ProjectionElem("course"));
    ProjectionElemList studentHasRelation = new ProjectionElemList(
            new ProjectionElem("p", "relation"),
            new ProjectionElem("x", "student"));
    QueryRoot queryTree = new QueryRoot(new MultiProjection(
            new Join(new Join(isCourse, hasEdge), isUndergrad),
            Arrays.asList(courseHasRelation, studentHasRelation)));
    SparqlToPipelineTransformVisitor visitor = new SparqlToPipelineTransformVisitor(collection);
    queryTree.visit(visitor);
    Assert.assertTrue(queryTree.getArg() instanceof AggregationPipelineQueryNode);
    AggregationPipelineQueryNode pipelineNode = (AggregationPipelineQueryNode) queryTree.getArg();
    Assert.assertEquals(Sets.newHashSet("relation"), pipelineNode.getAssuredBindingNames());
    Assert.assertEquals(Sets.newHashSet("relation", "course", "student"), pipelineNode.getBindingNames());
}
 
Example #9
Source File: SPARQLParserTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Verify that an INSERT with a subselect using a wildcard correctly adds vars to projection
 *
 * @see <a href="https://github.com/eclipse/rdf4j/issues/686">#686</a>
 */
@Test
public void testParseWildcardSubselectInUpdate() throws Exception {
	StringBuilder update = new StringBuilder();
	update.append("INSERT { <urn:a> <urn:b> <urn:c> . } WHERE { SELECT * {?s ?p ?o } }");

	ParsedUpdate parsedUpdate = parser.parseUpdate(update.toString(), null);
	List<UpdateExpr> exprs = parsedUpdate.getUpdateExprs();
	assertEquals(1, exprs.size());

	UpdateExpr expr = exprs.get(0);
	assertTrue(expr instanceof Modify);
	Modify m = (Modify) expr;
	TupleExpr whereClause = m.getWhereExpr();
	assertTrue(whereClause instanceof Projection);
	ProjectionElemList projectionElemList = ((Projection) whereClause).getProjectionElemList();
	assertNotNull(projectionElemList);
	List<ProjectionElem> elements = projectionElemList.getElements();
	assertNotNull(elements);

	assertEquals("projection should contain all three variables", 3, elements.size());
}
 
Example #10
Source File: AbstractQueryBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private UnaryTupleOperator projection() {
	if (!mProjectionPatterns.isEmpty()) {
		return multiProjection();
	} else {
		Extension aExt = null;

		ProjectionElemList aList = new ProjectionElemList();

		for (String aVar : mProjectionVars) {
			aList.addElement(new ProjectionElem(aVar));
		}

		Projection aProjection = new Projection();
		aProjection.setProjectionElemList(aList);

		if (aExt != null) {
			aProjection.setArg(aExt);
		}

		return aProjection;
	}
}
 
Example #11
Source File: BaseTupleExprRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Turn a ProjectionElemList for a construct query projection (three elements aliased as 'subject', 'predicate' and
 * 'object' in that order) into a StatementPattern.
 *
 * @param theList the elem list to render
 * @return the elem list for a construct projection as a statement pattern
 * @throws Exception if there is an exception while rendering
 */
public StatementPattern toStatementPattern(ProjectionElemList theList) throws Exception {
	ProjectionElem aSubj = theList.getElements().get(0);
	ProjectionElem aPred = theList.getElements().get(1);
	ProjectionElem aObj = theList.getElements().get(2);

	return new StatementPattern(
			mExtensions.containsKey(aSubj.getSourceName())
					? new Var(scrubVarName(aSubj.getSourceName()), asValue(mExtensions.get(aSubj.getSourceName())))
					: new Var(scrubVarName(aSubj.getSourceName())),
			mExtensions.containsKey(aPred.getSourceName())
					? new Var(scrubVarName(aPred.getSourceName()), asValue(mExtensions.get(aPred.getSourceName())))
					: new Var(scrubVarName(aPred.getSourceName())),
			mExtensions.containsKey(aObj.getSourceName())
					? new Var(scrubVarName(aObj.getSourceName()), asValue(mExtensions.get(aObj.getSourceName())))
					: new Var(scrubVarName(aObj.getSourceName())));
}
 
Example #12
Source File: ProjectionIterator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static BindingSet project(ProjectionElemList projElemList, BindingSet sourceBindings,
		BindingSet parentBindings, boolean includeAllParentBindings) {
	final QueryBindingSet resultBindings = new QueryBindingSet();
	if (includeAllParentBindings) {
		resultBindings.addAll(parentBindings);
	}

	for (ProjectionElem pe : projElemList.getElements()) {
		Value targetValue = sourceBindings.getValue(pe.getSourceName());
		if (!includeAllParentBindings && targetValue == null) {
			targetValue = parentBindings.getValue(pe.getSourceName());
		}
		if (targetValue != null) {
			resultBindings.setBinding(pe.getTargetName(), targetValue);
		}
	}

	return resultBindings;
}
 
Example #13
Source File: OrderLimitOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(Var node) {
	if (projection != null) {
		boolean projected = false;
		for (ProjectionElem e : projection.getProjectionElemList().getElements()) {
			String source = e.getSourceName();
			String target = e.getTargetName();
			if (node.getName().equals(source) && node.getName().equals(target)) {
				projected = true;
				break;
			}
		}
		if (!projected) {
			variablesProjected = false;
		}
	}
}
 
Example #14
Source File: PrepareOwnedTupleExpr.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(Projection node) throws RepositoryException {
	TupleExpr arg = node.getArg();
	if (arg instanceof StatementPattern && arg.getBindingNames().equals(node.getBindingNames())) {
		meetNode(node);
	} else {
		arg.visit(this);
		if (patternNode == null) {
			return;
		}
		Map<String, String> map = new HashMap<>();
		for (ProjectionElem e : node.getProjectionElemList().getElements()) {
			String source = variables.get(e.getSourceName());
			if (source == null) {
				source = safe(e.getSourceName());
			}
			map.put(e.getTargetName(), source);
		}
		this.variables = map;
		this.patternNode = node;
	}
}
 
Example #15
Source File: ConstructConsequentVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testConcreteSP() {
    Extension extension = new Extension(new SingletonSet(),
            new ExtensionElem(new ValueConstant(FOAF.PERSON), "x"),
            new ExtensionElem(new ValueConstant(RDF.TYPE), "y"),
            new ExtensionElem(new ValueConstant(OWL.CLASS), "z"));
    Projection projection = new Projection(extension, new ProjectionElemList(
            new ProjectionElem("x", "subject"),
            new ProjectionElem("y", "predicate"),
            new ProjectionElem("z", "object")));
    ConstructConsequentVisitor visitor = new ConstructConsequentVisitor();
    projection.visit(visitor);
    Set<StatementPattern> expected = Sets.newHashSet(
            new StatementPattern(s(FOAF.PERSON), p(RDF.TYPE), o(OWL.CLASS)));
    Assert.assertEquals(expected, visitor.getConsequents());
}
 
Example #16
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Projection visitResultVariables(Resource resultVars, Map<String, ProjectionElem> previousProjElems)
		throws RDF4JException {
	ProjectionElemList projElemList = new ProjectionElemList();
	Iteration<Resource, QueryEvaluationException> iter = TripleSources.listResources(resultVars,
			store);
	while (iter.hasNext()) {
		Resource r = iter.next();
		ProjectionElem projElem = visitResultVariable(r, previousProjElems);
		projElemList.addElement(projElem);
	}

	Projection proj = new Projection();
	proj.setProjectionElemList(projElemList);

	tupleRoot = proj;
	return proj;
}
 
Example #17
Source File: QueryAlgebraUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Construct a SELECT query for a grouped bound check.
 *
 * Pattern:
 *
 * SELECT DISTINCT ?o_1 .. ?o_N WHERE { { s1 p1 ?o_1 FILTER ?o_1=o1 } UNION ... UNION { sN pN ?o_N FILTER ?o_N=oN }}
 *
 * @param stmt
 * @param unionBindings
 * @return the SELECT query
 */
public static TupleExpr selectQueryStringBoundCheck(StatementPattern stmt, List<BindingSet> unionBindings) {

	Set<String> varNames = new HashSet<>();

	Union union = new Union();
	union.setLeftArg(constructStatementCheckId(stmt, 0, varNames, unionBindings.get(0)));
	Union tmp = union;
	int idx;
	for (idx = 1; idx < unionBindings.size() - 1; idx++) {
		Union _u = new Union();
		_u.setLeftArg(constructStatementCheckId(stmt, idx, varNames, unionBindings.get(idx)));
		tmp.setRightArg(_u);
		tmp = _u;
	}
	tmp.setRightArg(constructStatementCheckId(stmt, idx, varNames, unionBindings.get(idx)));

	ProjectionElemList projList = new ProjectionElemList();
	for (String var : varNames) {
		projList.addElement(new ProjectionElem(var));
	}

	Projection proj = new Projection(union, projList);

	return proj;
}
 
Example #18
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Projection visitResultNodes(Resource resultNodes) throws RDF4JException {
	ProjectionElemList projElemList = new ProjectionElemList();
	Iteration<Resource, QueryEvaluationException> iter = TripleSources.listResources(resultNodes,
			store);
	while (iter.hasNext()) {
		Resource r = iter.next();
		ProjectionElem projElem = visitResultNode(r);
		projElemList.addElement(projElem);
	}

	Projection proj = new Projection();
	proj.setProjectionElemList(projElemList);

	tupleRoot = new DescribeOperator(proj);
	return proj;
}
 
Example #19
Source File: SpinRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(ProjectionElem node) throws RDFHandlerException {
	ValueExpr valueExpr = null;
	if (inlineBindings != null) {
		String varName = node.getSourceName();
		valueExpr = inlineBindings.getValueExpr(varName);
	}
	Resource targetVar = getVar(node.getTargetName());
	listEntry(targetVar);
	if (valueExpr != null && !(valueExpr instanceof Var)) {
		Resource currentSubj = subject;
		subject = valueFactory.createBNode();
		handler.handleStatement(valueFactory.createStatement(targetVar, SP.EXPRESSION_PROPERTY, subject));
		valueExpr.visit(new ExtensionVisitor());
		subject = currentSubj;
	}
}
 
Example #20
Source File: SpinRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(ProjectionElem node) throws RDFHandlerException {
	if (isSubQuery) {
		super.meet(node);
	} else {
		String varName = node.getSourceName();
		ValueExpr valueExpr = inlineBindings.getValueExpr(varName);
		Value value = (valueExpr instanceof ValueConstant) ? ((ValueConstant) valueExpr).getValue()
				: getVar(varName);
		String targetName = node.getTargetName();
		IRI pred;
		if ("subject".equals(targetName)) {
			pred = SP.SUBJECT_PROPERTY;
		} else if ("predicate".equals(targetName)) {
			pred = SP.PREDICATE_PROPERTY;
		} else if ("object".equals(targetName)) {
			pred = SP.OBJECT_PROPERTY;
		} else {
			throw new AssertionError("Unexpected ProjectionElem: " + node);
		}
		handler.handleStatement(valueFactory.createStatement(subject, pred, value));
	}
}
 
Example #21
Source File: ConstructConsequentVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiProjection() {
    Extension extension = new Extension(new SingletonSet(),
            new ExtensionElem(new ValueConstant(RDF.TYPE), "rdftype"),
            new ExtensionElem(new ValueConstant(OWL.OBJECTPROPERTY), "owlprop"),
            new ExtensionElem(new ValueConstant(OWL.EQUIVALENTCLASS), "owleqcls"),
            new ExtensionElem(new ValueConstant(OWL.CLASS), "owlclass"));
    MultiProjection projection = new MultiProjection(extension, Arrays.asList(
            new ProjectionElemList(
                    new ProjectionElem("cls", "subject"),
                    new ProjectionElem("rdftype", "predicate"),
                    new ProjectionElem("owlclass", "object")),
            new ProjectionElemList(
                    new ProjectionElem("prop", "subject"),
                    new ProjectionElem("rdftype", "predicate"),
                    new ProjectionElem("owlprop", "object")),
            new ProjectionElemList(
                    new ProjectionElem("owleqcls", "predicate"),
                    new ProjectionElem("cls", "object"))));
    ConstructConsequentVisitor visitor = new ConstructConsequentVisitor();
    projection.visit(visitor);
    Set<StatementPattern> expected = Sets.newHashSet(
            new StatementPattern(s(null), p(RDF.TYPE), o(OWL.CLASS)),
            new StatementPattern(s(null), p(RDF.TYPE), o(OWL.OBJECTPROPERTY)),
            new StatementPattern(s(null), p(OWL.EQUIVALENTCLASS), o(null)));
    Assert.assertEquals(expected, visitor.getConsequents());
}
 
Example #22
Source File: ConstructConsequentVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testBNode() {
    Extension extension = new Extension(new SingletonSet(),
            new ExtensionElem(new Var("x"), "x"),
            new ExtensionElem(new BNodeGenerator(), "z"));
    Projection projection = new Projection(extension, new ProjectionElemList(
            new ProjectionElem("x", "subject"),
            new ProjectionElem("y", "predicate"),
            new ProjectionElem("z", "object")));
    ConstructConsequentVisitor visitor = new ConstructConsequentVisitor();
    projection.visit(visitor);
    Set<StatementPattern> expected = Sets.newHashSet(
            new StatementPattern(s(null), p(null), anon(o(null))));
    Assert.assertEquals(expected, visitor.getConsequents());
}
 
Example #23
Source File: QueryAlgebraUtil.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Construct a SELECT query expression for a bound union.
 * 
 * Pattern:
 * 
 * SELECT ?v_1 ?v_2 ?v_N WHERE { { ?v_1 p o } UNION { ?v_2 p o } UNION ... } 
 * 
 * Note that the filterExpr is not evaluated at the moment.
 * 
 * @param stmt
 * @param unionBindings
 * @param filterExpr
 * @param evaluated
 * 			parameter can be used outside this method to check whether FILTER has been evaluated, false in beginning
 * 
 * @return
 */
public static TupleExpr selectQueryBoundUnion( StatementPattern stmt, List<BindingSet> unionBindings, FilterValueExpr filterExpr, Boolean evaluated) {
	
	// TODO add FILTER expressions
	
	Set<String> varNames = new HashSet<String>();
	
	Union union = new Union();
	union.setLeftArg(constructStatementId(stmt, Integer.toString(0), varNames, unionBindings.get(0)) );
	Union tmp = union;
	int idx;
	for (idx=1; idx<unionBindings.size()-1; idx++) {
		Union _u = new Union();
		_u.setLeftArg( constructStatementId(stmt, Integer.toString(idx), varNames, unionBindings.get(idx)) );
		tmp.setRightArg(_u);
		tmp = _u;
	}
	tmp.setRightArg( constructStatementId(stmt, Integer.toString(idx), varNames, unionBindings.get(idx) ));
			
	ProjectionElemList projList = new ProjectionElemList();
	for (String var : varNames)
		projList.addElement( new ProjectionElem(var));
	
	Projection proj = new Projection(union, projList);

	return proj;
}
 
Example #24
Source File: HasSelfVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropertyPattern_constantSubj() throws Exception {
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    final Set<Resource> loveTypes = new HashSet<>();
    loveTypes.add(narcissist);
    when(inferenceEngine.getHasSelfImplyingProperty(love)).thenReturn(loveTypes);
    final Var subj = new Var("s", self);
    subj.setConstant(true);
    final Var obj = new Var("o");
    final Var pred = new Var("p", love);
    pred.setConstant(true);

    final Projection query = new Projection(new StatementPattern(subj, pred, obj),
            new ProjectionElemList(new ProjectionElem("s", "subject")));
    query.visit(new HasSelfVisitor(conf, inferenceEngine));

    Assert.assertTrue(query.getArg() instanceof Union);
    final Union union = (Union) query.getArg();
    Assert.assertTrue(union.getRightArg() instanceof StatementPattern);
    Assert.assertTrue(union.getLeftArg() instanceof Extension);
    final StatementPattern expectedRight = new StatementPattern(subj, pred, obj);
    final Extension expectedLeft = new Extension(
            new StatementPattern(subj, new Var(RDF.TYPE.stringValue(), RDF.TYPE), new Var("urn:Narcissist", narcissist)),
            new ExtensionElem(subj, "o"));
    Assert.assertEquals(expectedLeft, union.getLeftArg());
    Assert.assertEquals(expectedRight, union.getRightArg());
}
 
Example #25
Source File: ConstructConsequentVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoExtension() {
    StatementPattern sp = new StatementPattern(new Var("x"), new Var("y"), new Var("z"));
    Projection projection = new Projection(sp, new ProjectionElemList(
            new ProjectionElem("x", "subject"),
            new ProjectionElem("y", "predicate"),
            new ProjectionElem("z", "object")));
    ConstructConsequentVisitor visitor = new ConstructConsequentVisitor();
    projection.visit(visitor);
    Set<StatementPattern> expected = Sets.newHashSet(
            new StatementPattern(s(null), p(null), o(null)));
    Assert.assertEquals(expected, visitor.getConsequents());
}
 
Example #26
Source File: HasSelfVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropertyPattern_constantObj() throws Exception {
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    final Set<Resource> loveTypes = new HashSet<>();
    loveTypes.add(narcissist);
    when(inferenceEngine.getHasSelfImplyingProperty(love)).thenReturn(loveTypes);
    final Var subj = new Var("s");
    final Var obj = new Var("o", self);
    obj.setConstant(true);
    final Var pred = new Var("p", love);
    pred.setConstant(true);

    final Projection query = new Projection(new StatementPattern(subj, pred, obj),
            new ProjectionElemList(new ProjectionElem("s", "subject")));
    query.visit(new HasSelfVisitor(conf, inferenceEngine));

    Assert.assertTrue(query.getArg() instanceof Union);
    final Union union = (Union) query.getArg();
    Assert.assertTrue(union.getRightArg() instanceof StatementPattern);
    Assert.assertTrue(union.getLeftArg() instanceof Extension);
    final StatementPattern expectedRight = new StatementPattern(subj, pred, obj);
    final Extension expectedLeft = new Extension(
            new StatementPattern(obj, new Var(RDF.TYPE.stringValue(), RDF.TYPE), new Var("urn:Narcissist", narcissist)),
            new ExtensionElem(obj, "s"));
    Assert.assertEquals(expectedLeft, union.getLeftArg());
    Assert.assertEquals(expectedRight, union.getRightArg());
}
 
Example #27
Source File: OneOfVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testOneOf() throws Exception {
    // Configure a mock instance engine with an ontology:
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    when(inferenceEngine.isEnumeratedType(SUITS)).thenReturn(true);
    when(inferenceEngine.getEnumeration(SUITS)).thenReturn(CARD_SUIT_ENUMERATION);
    when(inferenceEngine.isEnumeratedType(RANKS)).thenReturn(true);
    when(inferenceEngine.getEnumeration(RANKS)).thenReturn(CARD_RANK_ENUMERATION);
    // Query for a  Suits and rewrite using the visitor:
    final Projection query = new Projection(
            new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", SUITS)),
            new ProjectionElemList(new ProjectionElem("s", "subject")));
    query.visit(new OneOfVisitor(conf, inferenceEngine));
    // Expected structure: BindingSetAssignment containing the enumeration:
    // BindingSetAssignment(CLUBS, DIAMONDS, HEARTS, SPADES)
    // Collect the arguments to the BindingSetAssignment:
    assertTrue(query.getArg() instanceof BindingSetAssignment);
    final BindingSetAssignment bsa = (BindingSetAssignment) query.getArg();
    final Iterable<BindingSet> iterable = bsa.getBindingSets();
    final Iterator<BindingSet> iter = iterable.iterator();

    assertBindingSet(iter, CARD_SUIT_ENUMERATION.iterator());

    // Query for a Ranks and rewrite using the visitor:
    final Projection query2 = new Projection(
            new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", RANKS)),
            new ProjectionElemList(new ProjectionElem("s", "subject")));
    query2.visit(new OneOfVisitor(conf, inferenceEngine));
    // Expected structure: BindingSetAssignment containing the enumeration:
    // BindingSetAssignment(ACE, 2, 3, 4, 5, 6, 7, 8, 9, 10, JACK, QUEEN, KING)
    // Collect the arguments to the BindingSetAssignment:
    assertTrue(query2.getArg() instanceof BindingSetAssignment);
    final BindingSetAssignment bsa2 = (BindingSetAssignment) query2.getArg();
    final Iterable<BindingSet> iterable2 = bsa2.getBindingSets();
    final Iterator<BindingSet> iter2 = iterable2.iterator();

    assertBindingSet(iter2, CARD_RANK_ENUMERATION.iterator());
}
 
Example #28
Source File: ConstructConsequentVisitor.java    From rya with Apache License 2.0 5 votes vote down vote up
private void recordConsequent(ProjectionElemList variables, List<ExtensionElem> extensionElements) {
    Map<String, Value> bindings = new ConcurrentHashMap<>();
    Map<String, Value> values = new ConcurrentHashMap<>();
    Set<String> queryBnodes = new HashSet<>();
    Set<String> projectedBnodes = new HashSet<>();
    for (ExtensionElem ee : extensionElements) {
        if (ee.getExpr() instanceof ValueConstant) {
            bindings.put(ee.getName(), ((ValueConstant) ee.getExpr()).getValue());
        }
        else if (ee.getExpr() instanceof BNodeGenerator) {
            queryBnodes.add(ee.getName());
        }
    }
    for (ProjectionElem var : variables.getElements()) {
        String sourceName = var.getSourceName();
        String targetName = var.getTargetName();
        Value constValue = bindings.get(sourceName);
        if (constValue != null) {
            values.put(targetName, constValue);
        }
        else if (queryBnodes.contains(sourceName)) {
            projectedBnodes.add(targetName);
        }
    }
    Var subjVar = new Var(SUBJECT_VAR_NAME, values.get(SUBJECT_VAR_NAME));
    Var predVar = new Var(PREDICATE_VAR_NAME, values.get(PREDICATE_VAR_NAME));
    Var objVar = new Var(OBJECT_VAR_NAME, values.get(OBJECT_VAR_NAME));
    subjVar.setAnonymous(projectedBnodes.contains(SUBJECT_VAR_NAME));
    predVar.setAnonymous(projectedBnodes.contains(PREDICATE_VAR_NAME));
    objVar.setAnonymous(projectedBnodes.contains(OBJECT_VAR_NAME));
    StatementPattern sp = new StatementPattern(subjVar, predVar, objVar);
    consequentStatementPatterns.add(sp);
}
 
Example #29
Source File: ProjectionEvaluator.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Applies the projection to a value. If the result has a blank node whose ID is not mapped to a value in
 * {@code blankNodes}, then a random UUID will be used.
 *
 * @param bs - The value the projection will be applied to. (not null)
 * @param blankNodes - A map from node source names to the blank nodes that will be used for those names. (not null)
 * @return A new value that is the result of the projection.
 */
public VisibilityBindingSet project(final VisibilityBindingSet bs, final Map<String, BNode> blankNodes) {
    requireNonNull(bs);
    requireNonNull(blankNodes);

    // Apply the projection elements against the original binding set.
    final MapBindingSet result = new MapBindingSet();
    for (final ProjectionElem elem : projectionElems.getElements()) {
        final String sourceName = elem.getSourceName();

        Value value = null;

        // If the binding set already has the source name, then use the target name.
        if (bs.hasBinding(sourceName)) {
            value = bs.getValue(elem.getSourceName());
        }

        // If the source name represents a constant value, then use the constant.
        else if(constantSources.containsKey(sourceName)) {
            value = constantSources.get(sourceName);
        }

        // If the source name represents an anonymous value, then create a Blank Node.
        else if(anonymousSources.contains(sourceName)) {
            if(blankNodes.containsKey(sourceName)) {
                value = blankNodes.get(sourceName);
            } else {
                value = VF.createBNode( UUID.randomUUID().toString() );
            }
        }

        // Only add the value if there is one. There may not be one if a binding is optional.
        if(value != null) {
            result.addBinding(elem.getTargetName(), value);
        }
    }

    return new VisibilityBindingSet(result, bs.getVisibility());
}
 
Example #30
Source File: ConstructConsequentVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testMissingVariables() {
    Extension extension = new Extension(new SingletonSet(),
            new ExtensionElem(new ValueConstant(FOAF.PERSON), "x"),
            new ExtensionElem(new ValueConstant(RDF.TYPE), "y"));
    Projection projection = new Projection(extension, new ProjectionElemList(
            new ProjectionElem("x", "s"),
            new ProjectionElem("y", "predicate"),
            new ProjectionElem("z", "object")));
    ConstructConsequentVisitor visitor = new ConstructConsequentVisitor();
    projection.visit(visitor);
    Set<StatementPattern> expected = Sets.newHashSet(
            new StatementPattern(s(null), p(RDF.TYPE), o(null)));
    Assert.assertEquals(expected, visitor.getConsequents());
}