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

The following examples show how to use org.eclipse.rdf4j.query.algebra.ProjectionElemList. 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: 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 #2
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 #3
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 #4
Source File: SparqlToPigTransformVisitor.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public void meet(Projection node) throws RuntimeException {
    super.meet(node);
    ProjectionElemList list = node.getProjectionElemList();
    String set = null;
    StringBuilder projList = new StringBuilder();
    boolean first = true;
    //TODO: we do not support projections from multiple pig statements yet
    for (String name : list.getTargetNames()) {
        set = varToSet.get(name);  //TODO: overwrite
        if (set == null) {
            throw new IllegalArgumentException("Have not found any pig logic for name[" + name + "]");
        }
        if (!first) {
            projList.append(",");
        }
        first = false;
        projList.append(name);
    }
    if (set == null)
        throw new IllegalArgumentException(""); //TODO: Fill this
    //SUBORG = FOREACH SUBORG_L GENERATE dept, univ;
    pigScriptBuilder.append("PROJ = FOREACH ").append(set).append(" GENERATE ").append(projList.toString()).append(";\n");
}
 
Example #5
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 #6
Source File: MultiProjectionEvaluator.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Make a {@link MultiProjectionEvaluator} that processes the logic of a {@link MultiProjection}.
 *
 * @param multiProjection - Defines the projections that will be processed. (not null)
 * @param bNodeIdFactory - Creates the IDs for Blank Nodes. (not null)
 * @return A {@link MultiProjectionEvaluator} for the provided {@link MultiProjection}.
 */
public static MultiProjectionEvaluator make(final MultiProjection multiProjection, final BNodeIdFactory bNodeIdFactory) {
    requireNonNull(multiProjection);

    // Figure out if there are extensions.
    final TupleExpr arg = multiProjection.getArg();
    final Optional<Extension> extension = (arg instanceof Extension) ? Optional.of((Extension)arg): Optional.empty();

    // If there are, iterate through them and find any blank node source names.
    final Set<String> blankNodeSourceNames = new HashSet<>();
    if(extension.isPresent()) {
        for(final ExtensionElem elem : extension.get().getElements()) {
            if(elem.getExpr() instanceof BNodeGenerator) {
                blankNodeSourceNames.add( elem.getName() );
            }
        }
    }

    // Create a ProjectionEvaluator for each projection that is part of the multi.
    final Set<ProjectionEvaluator> projections = new HashSet<>();
    for(final ProjectionElemList projectionElemList : multiProjection.getProjections()) {
        projections.add( new ProjectionEvaluator(projectionElemList, extension) );
    }

    return new MultiProjectionEvaluator(projections, blankNodeSourceNames, bNodeIdFactory);
}
 
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: 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 #9
Source File: SparqlFluoQueryBuilder.java    From rya with Apache License 2.0 6 votes vote down vote up
private static VariableOrder getConstructGraphVarOrder(final Reduced node) {

        //get child node
          final QueryModelNode child = node.getArg();
          Preconditions.checkArgument(child instanceof Projection || child instanceof MultiProjection);
          final UnaryTupleOperator unary = (UnaryTupleOperator) child;

          //get ProjectionElemList to build ConstructGraph
          final List<ProjectionElemList> projections = new ArrayList<>();
          if(unary instanceof Projection) {
              projections.add(((Projection) unary).getProjectionElemList());
          } else {
              projections.addAll(((MultiProjection)unary).getProjections());
          }

          return getConstructGraphVarOrder(projections);
      }
 
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: 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 #12
Source File: PrepareOwnedTupleExpr.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected void meetNode(QueryModelNode node) throws RepositoryException {
	super.meetNode(node);
	if (owner != null && patternNode != null && !(patternNode instanceof StatementPattern)) {
		StringBuilder builder = new StringBuilder();
		builder.append("SELECT");
		if (distinct) {
			builder.append(" DISTINCT");
		} else if (reduced || reduce) {
			builder.append(" REDUCED");
		}
		boolean mapping = false;
		Map<String, String> bindings = new HashMap<>();
		ProjectionElemList list = new ProjectionElemList();
		for (String name : patternNode.getBindingNames()) {
			mapping = addBindingNames(builder, mapping, bindings, list, name);
		}
		builder.append("\nWHERE {\n").append(pattern).append("}");
		meetNodeLocal(builder, mapping, bindings, list);
	}
	reduced = false;
	distinct = false;
	pattern = null; // NOPMD
	patternNode = null; // NOPMD
}
 
Example #13
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 #14
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 #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: 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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
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 #23
Source File: ProjectionEvaluator.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Make a {@link ProjectionEvaluator} that processes the logic of a {@link Projection}.
 *
 * @param projection - Defines the projection that will be processed. (not null)
 * @return A {@link ProjectionEvaluator} for the provided {@link Projection}.
 */
public static ProjectionEvaluator make(final Projection projection) {
    requireNonNull(projection);

    final ProjectionElemList projectionElems = projection.getProjectionElemList();

    final TupleExpr arg = projection.getArg();
    final Optional<Extension> extension = arg instanceof Extension ? Optional.of((Extension)arg) : Optional.empty();

    return new ProjectionEvaluator(projectionElems, extension);
}
 
Example #24
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 #25
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());
}
 
Example #26
Source File: ConstructConsequentVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenericSP() {
    Extension extension = new Extension(new SingletonSet(),
            new ExtensionElem(new Var("z"), "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), o(null)));
    Assert.assertEquals(expected, visitor.getConsequents());
}
 
Example #27
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 #28
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 #29
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 #30
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());
}