Java Code Examples for org.eclipse.rdf4j.query.algebra.Projection#getArg()

The following examples show how to use org.eclipse.rdf4j.query.algebra.Projection#getArg() . 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: TopologyFactory.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public void meet(final Projection node) throws TopologyBuilderException {
    final String id = PROJECTION_PREFIX + UUID.randomUUID();
    final Optional<Side> side = getSide(node);

    // If the arg is an Extension, there are rebindings that need to be
    // ignored since they do not have a processor node.
    TupleExpr downstreamNode = node.getArg();
    if (downstreamNode instanceof Extension) {
        downstreamNode = ((Extension) downstreamNode).getArg();
    }

    final ProjectionProcessorSupplier supplier = new ProjectionProcessorSupplier(
            ProjectionEvaluator.make(node),
            result -> getResult(side, result));

    entries.add(new ProcessorEntry(node, id, side, supplier, Lists.newArrayList(downstreamNode)));
    idMap.put(node, id);
    super.meet(node);
}
 
Example 2
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 3
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 4
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 5
Source File: TopOfQueryFilterRelocator.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 *
 * This method moves the Filters of a specified {@link TupleExpr} to the top
 * of the TupleExpr.
 *
 * @param query
 *            - query whose filters will be relocated
 * @return - TupleExpr with filters relocated to top
 */
public static TupleExpr moveFiltersToTop(TupleExpr query) {

    ProjectionAndFilterGatherer fg = new ProjectionAndFilterGatherer();
    query.visit(fg);
    List<ValueExpr> filterCond = new ArrayList<>(fg.filterCond);
    Projection projection = fg.projection;

    if (filterCond.size() == 0) {
        return query;
    }

    Filter first = new Filter();
    first.setCondition(filterCond.remove(0));
    Filter current = first;
    for (ValueExpr cond : filterCond) {
        Filter filter = new Filter(null, cond);
        current.setArg(filter);
        current = filter;
    }

    TupleExpr te = projection.getArg();
    projection.setArg(first);
    current.setArg(te);

    return query;

}
 
Example 6
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 7
Source File: SparqlToPipelineTransformVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmptyProjection() throws Exception {
    StatementPattern isClass = new StatementPattern(constant(UNDERGRAD), constant(RDF.TYPE), constant(OWL.CLASS));
    QueryRoot queryTree = new QueryRoot(new Projection(isClass, new ProjectionElemList()));
    SparqlToPipelineTransformVisitor visitor = new SparqlToPipelineTransformVisitor(collection);
    queryTree.visit(visitor);
    Assert.assertTrue(queryTree.getArg() instanceof Projection);
    Projection projectNode = (Projection) queryTree.getArg();
    Assert.assertTrue(projectNode.getArg() instanceof AggregationPipelineQueryNode);
    AggregationPipelineQueryNode pipelineNode = (AggregationPipelineQueryNode) projectNode.getArg();
    Assert.assertEquals(Sets.newHashSet(), pipelineNode.getAssuredBindingNames());
}
 
Example 8
Source File: PipelineQueryIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoVariableSP() throws Exception {
    // Insert data
    insert(OWL.THING, RDF.TYPE, OWL.CLASS);
    insert(FOAF.PERSON, RDF.TYPE, OWL.CLASS, 1);
    insert(FOAF.PERSON, RDFS.SUBCLASSOF, OWL.THING);
    insert(VF.createIRI("urn:Alice"), RDF.TYPE, FOAF.PERSON);
    dao.flush();
    // Define query and expected results
    final String query = "SELECT * WHERE {\n"
            + "  owl:Thing a owl:Class .\n"
            + "}";
    final Multiset<BindingSet> expectedSolutions = HashMultiset.create();
    expectedSolutions.add(new EmptyBindingSet());
    // Execute pipeline and verify results
    final QueryRoot queryTree = new QueryRoot(PARSER.parseQuery(query, null).getTupleExpr());
    final SparqlToPipelineTransformVisitor visitor = new SparqlToPipelineTransformVisitor(getRyaCollection());
    queryTree.visit(visitor);
    Assert.assertTrue(queryTree.getArg() instanceof Projection);
    final Projection projection = (Projection) queryTree.getArg();
    Assert.assertTrue(projection.getArg() instanceof AggregationPipelineQueryNode);
    final AggregationPipelineQueryNode pipelineNode = (AggregationPipelineQueryNode) projection.getArg();
    final Multiset<BindingSet> solutions = HashMultiset.create();
    final CloseableIteration<BindingSet, QueryEvaluationException> iter = pipelineNode.evaluate(new QueryBindingSet());
    while (iter.hasNext()) {
        solutions.add(iter.next());
    }
    Assert.assertEquals(expectedSolutions, solutions);
}
 
Example 9
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 10
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 11
Source File: TestSparqlStarParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testUseInProjection() throws Exception {
	String simpleSparqlQuery = "SELECT (<<<urn:A> <urn:B> 1>> as ?ref) WHERE {}";

	ParsedQuery q = parser.parseQuery(simpleSparqlQuery, null);

	assertNotNull(q);
	assertTrue("expect projection", q.getTupleExpr() instanceof Projection);
	Projection proj = (Projection) q.getTupleExpr();

	assertTrue("expect extension", proj.getArg() instanceof Extension);
	Extension ext = (Extension) proj.getArg();

	assertTrue("single extention elemrnt", ext.getElements().size() == 1);
	ExtensionElem elem = ext.getElements().get(0);

	assertEquals("name should match", elem.getName(), "ref");
	assertTrue("expect ValueExprTripleRef", elem.getExpr() instanceof ValueExprTripleRef);
	ValueExprTripleRef ref = (ValueExprTripleRef) elem.getExpr();

	assertTrue("expect not null subject", ref.getSubjectVar().getValue() != null);
	assertTrue("expect IRI subject", ref.getSubjectVar().getValue() instanceof IRI);
	assertEquals("subject should match", ref.getSubjectVar().getValue().toString(), "urn:A");

	assertTrue("expect not null predicate", ref.getPredicateVar().getValue() != null);
	assertTrue("expect IRI predicate", ref.getPredicateVar().getValue() instanceof IRI);
	assertEquals("predicate should match", ref.getPredicateVar().getValue().toString(), "urn:B");

	assertTrue("expect not null object", ref.getObjectVar().getValue() != null);
	assertTrue("expect Literal object", ref.getObjectVar().getValue() instanceof Literal);
	assertEquals("object should match", ((Literal) ref.getObjectVar().getValue()).intValue(), 1);
}
 
Example 12
Source File: ConstructConsequentVisitor.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
public void meet(Projection projection) {
    if (projection.getArg() instanceof Extension) {
        recordConsequent(projection.getProjectionElemList(),
                ((Extension) projection.getArg()).getElements());
    }
    else {
        recordConsequent(projection.getProjectionElemList(), Arrays.asList());
    }
}
 
Example 13
Source File: OptionalJoinSegmentPCJMatcherTest.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
public void testBasicSegment() throws MalformedQueryException {

	String query1 = ""//
			+ "SELECT ?e ?c ?l" //
			+ "{" //
			+ "  ?e a ?c . "//
			+ "  OPTIONAL {?e <uri:talksTo> ?l}  . "//
			+ "  ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l "//
			+ "}";//

	String query2 = ""//
			+ "SELECT ?e ?c ?l" //
			+ "{" //
			+ "  ?e a ?c . "//
			+ "  OPTIONAL {?e <uri:talksTo> ?l}  . "//
			+ "}";//

	SPARQLParser parser = new SPARQLParser();
	ParsedQuery pq1 = parser.parseQuery(query1, null);
	ParsedQuery pq2 = parser.parseQuery(query2, null);
	TupleExpr te1 = pq1.getTupleExpr();
	TupleExpr te2 = pq2.getTupleExpr();
	Projection proj = (Projection) te1;
	Join join = (Join) proj.getArg();

	
	ExternalSetMatcher<ExternalTupleSet> jsm = pcjFactory.getMatcher(qFactory.getQuerySegment(join));
	SimpleExternalTupleSet pcj = new SimpleExternalTupleSet((Projection)te2);
	Assert.assertEquals(true, jsm.match(pcj));
	TupleExpr te = jsm.getQuery();
	Assert.assertEquals(new HashSet<QueryModelNode>(), jsm.getUnmatchedArgNodes());

	Set<QueryModelNode> qNodes = LeftJoinQueryNodeGatherer.getNodes(te);
	List<QueryModelNode> nodes = jsm.getOrderedNodes();
	Set<QueryModelNode> nodeSet = new HashSet<>();
	nodeSet.add(nodes.get(0));
	nodeSet.add(pcj);

	Assert.assertEquals(nodeSet, new HashSet<QueryModelNode>(nodes));
	Assert.assertEquals(nodeSet, qNodes);

}
 
Example 14
Source File: IntersectionOfVisitorTest.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
public void testIntersectionOfDisabled() throws Exception {
    // Configure a mock instance engine with an ontology:
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    final Map<Resource, List<Set<Resource>>> intersections = new HashMap<>();
    final List<Set<Resource>> motherIntersections = Arrays.asList(
            Sets.newHashSet(ANIMAL, FEMALE, PARENT),
            Sets.newHashSet(FEMALE, LEADER, NUN)
        );
    final List<Set<Resource>> fatherIntersections = Arrays.asList(
            Sets.newHashSet(MAN, PARENT)
        );
    intersections.put(MOTHER, motherIntersections);
    when(inferenceEngine.getIntersectionsImplying(MOTHER)).thenReturn(motherIntersections);
    when(inferenceEngine.getIntersectionsImplying(FATHER)).thenReturn(fatherIntersections);
    // Query for a specific type and rewrite using the visitor:
    final Projection query = new Projection(
            new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", MOTHER)),
            new ProjectionElemList(new ProjectionElem("s", "subject")));

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

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

    // Expected structure: the original statement:
    assertTrue(query.getArg() instanceof StatementPattern);
    final StatementPattern actualMotherSp = (StatementPattern) query.getArg();
    final StatementPattern expectedMotherSp = new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", MOTHER));
    assertEquals(expectedMotherSp, actualMotherSp);


    // Query for a specific type and rewrite using the visitor:
    final Projection query2 = new Projection(
            new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", FATHER)),
            new ProjectionElemList(new ProjectionElem("s", "subject")));
    query2.visit(new IntersectionOfVisitor(disabledConf, inferenceEngine));

    // Expected structure: the original statement:
    assertTrue(query2.getArg() instanceof StatementPattern);
    final StatementPattern actualFatherSp = (StatementPattern) query2.getArg();
    final StatementPattern expectedFatherSp = new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", FATHER));
    assertEquals(expectedFatherSp, actualFatherSp);
}
 
Example 15
Source File: OptionalJoinSegmentPCJMatcherTest.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
public void testMultipleFilters() throws Exception {

	String query1 = ""//
			+ "SELECT ?e ?c ?l" //
			+ "{" //
			+ " Filter(?e = <uri:Bob>)" //
			+ " Filter(?c = <uri:Lawyer>)" //
			+ " ?l <uri:workAt> <uri:Company1> ."
			+ " OPTIONAL { ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l } . "//
			+ "  ?e a ?c . "//
			+ "  ?e <uri:talksTo> ?l  . "//
			+ "}";//

	String query2 = ""//
			+ "SELECT ?e ?c ?l" //
			+ "{" //
			+ " Filter(?e = <uri:Bob>)" //
			+ " ?e a ?c . "//
			+ " ?e <uri:talksTo> ?l . "//
			+ "}";//

	SPARQLParser parser = new SPARQLParser();
	ParsedQuery pq1 = parser.parseQuery(query1, null);
	ParsedQuery pq2 = parser.parseQuery(query2, null);
	TupleExpr te1 = pq1.getTupleExpr();
	TupleExpr te2 = pq2.getTupleExpr();
	Projection proj = (Projection) te1;
	Join join = (Join) proj.getArg();

	ExternalSetMatcher<ExternalTupleSet> jsm = pcjFactory.getMatcher(qFactory.getQuerySegment(join));
	SimpleExternalTupleSet pcj = new SimpleExternalTupleSet((Projection)te2);
	Assert.assertEquals(true, jsm.match(pcj));
	TupleExpr te = jsm.getQuery();
	Assert.assertEquals(new HashSet<QueryModelNode>(), jsm.getUnmatchedArgNodes());

	Set<QueryModelNode> qNodes = LeftJoinQueryNodeGatherer.getNodes(te);
	List<QueryModelNode> nodes = jsm.getOrderedNodes();
	Set<QueryModelNode> nodeSet = new HashSet<>();
	nodeSet.add(nodes.get(0));
	nodeSet.add(nodes.get(2));
	nodeSet.add(nodes.get(3));
	nodeSet.add(pcj);

	Assert.assertEquals(nodeSet, new HashSet<QueryModelNode>(nodes));
	Assert.assertEquals(nodeSet, qNodes);

}
 
Example 16
Source File: TestSparqlStarParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testUseInConstructFromStatementPattern() throws Exception {
	String simpleSparqlQuery = "CONSTRUCT {<<?s ?p ?o>> <urn:pred> <urn:value>} WHERE {?s ?p ?o}";

	ParsedQuery q = parser.parseQuery(simpleSparqlQuery, null);

	assertNotNull(q);
	assertTrue("expect Reduced", q.getTupleExpr() instanceof Reduced);
	assertTrue("expect projection", ((Reduced) q.getTupleExpr()).getArg() instanceof Projection);
	Projection proj = (Projection) ((Reduced) q.getTupleExpr()).getArg();

	List<ProjectionElem> list = proj.getProjectionElemList().getElements();
	final ArrayList<String> listTargetNames = new ArrayList<>();
	list.forEach(el -> {
		listTargetNames.add(el.getTargetName());
	});
	assertEquals("expect all bindings", 3, list.size());
	assertTrue("expect target subject", listTargetNames.contains("subject"));
	assertTrue("expect target predicate", listTargetNames.contains("predicate"));
	assertTrue("expect target oobject", listTargetNames.contains("object"));

	final ArrayList<String> listSourceNames = new ArrayList<>();
	list.forEach(el -> {
		listSourceNames.add(el.getSourceName());
	});

	assertTrue("expect extension", proj.getArg() instanceof Extension);
	Extension ext = (Extension) proj.getArg();
	assertTrue("three extention elements", ext.getElements().size() == 3);
	ExtensionElem elem = ext.getElements().get(0);

	assertEquals("anon name should match first", elem.getName(), listSourceNames.get(0));

	assertTrue("expect ValueExprTripleRef in extention element", elem.getExpr() instanceof ValueExprTripleRef);
	ValueExprTripleRef ref = (ValueExprTripleRef) elem.getExpr();
	assertEquals("subject var name", "s", ref.getSubjectVar().getName());
	assertEquals("predicate var name", "p", ref.getPredicateVar().getName());
	assertEquals("object var name", "o", ref.getObjectVar().getName());

	elem = ext.getElements().get(1);
	assertEquals("names should match", elem.getName(), listSourceNames.get(1));
	assertEquals("value should match", "urn:pred", ((ValueConstant) elem.getExpr()).getValue().toString());

	elem = ext.getElements().get(2);
	assertEquals("names should match", elem.getName(), listSourceNames.get(2));
	assertEquals("value should match", "urn:value", ((ValueConstant) elem.getExpr()).getValue().toString());

	assertTrue("expect StatementPattern", ext.getArg() instanceof StatementPattern);
	StatementPattern pattern = (StatementPattern) ext.getArg();

	assertEquals("subj var name should match", "s", pattern.getSubjectVar().getName());
	assertEquals("pred var name should match", "p", pattern.getPredicateVar().getName());
	assertEquals("obj var name should match", "o", pattern.getObjectVar().getName());
}
 
Example 17
Source File: OptionalJoinSegmentPCJMatcherTest.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
public void testWithUnmatchedNodes() throws Exception {

	String query1 = ""//
			+ "SELECT ?a ?b ?c ?d ?e" //
			+ "{" //
			+ " Filter(?a = <uri:s1>)" //
			+ " Filter(?b = <uri:s2>)" //
			+ " {?e <uri:p3> <uri:o2> } UNION {?d <uri:p4> <uri:o3>} ."
			+ " ?a <uri:workAt> <uri:Company1> ."
			+ "  ?b <uri:talksTo> ?c  . "//
			+ " OPTIONAL { ?b <uri:p1> ?c } . "//
			+ "  ?b <uri:p2> <uri:o1> . "//
			+ "}";//

	String query2 = ""//
			+ "SELECT ?e ?c ?l" //
			+ "{" //
			+ "  ?b <uri:talksTo> ?c  . "//
			+ " OPTIONAL { ?b <uri:p1> ?c } . "//
			+ "  ?b <uri:p2> <uri:o1> . "//
			+ " Filter(?b = <uri:s2>)" //
			+ "}";//

	SPARQLParser parser = new SPARQLParser();
	ParsedQuery pq1 = parser.parseQuery(query1, null);
	ParsedQuery pq2 = parser.parseQuery(query2, null);
	TupleExpr te1 = pq1.getTupleExpr();
	TupleExpr te2 = pq2.getTupleExpr();
	Projection proj = (Projection) te1;
	Join join = (Join) proj.getArg();

	ExternalSetMatcher<ExternalTupleSet> jsm = pcjFactory.getMatcher(qFactory.getQuerySegment(join));
	SimpleExternalTupleSet pcj = new SimpleExternalTupleSet((Projection)te2);
	Assert.assertEquals(true, jsm.match(pcj));
	TupleExpr te = jsm.getQuery();
	Set<QueryModelNode> qNodes = LeftJoinQueryNodeGatherer.getNodes(te);
	List<QueryModelNode> nodes = jsm.getOrderedNodes();

	Assert.assertEquals(1, jsm.getUnmatchedArgNodes().size());
	Assert.assertEquals(true, jsm.getUnmatchedArgNodes().contains(nodes.get(3)));

	Set<QueryModelNode> nodeSet = new HashSet<>();
	nodeSet.add(nodes.get(0));
	nodeSet.add(nodes.get(2));
	nodeSet.add(nodes.get(3));
	nodeSet.add(pcj);

	Assert.assertEquals(nodeSet, new HashSet<QueryModelNode>(nodes));
	Assert.assertEquals(nodeSet, qNodes);

}
 
Example 18
Source File: TestSparqlStarParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testUseNestedInStatementPatternWithVars() throws Exception {
	String simpleSparqlQuery = "SELECT * WHERE { <<<<?s ?p ?o>> ?q ?r>> <urn:pred> ?val}";

	ParsedQuery q = parser.parseQuery(simpleSparqlQuery, null);

	assertNotNull(q);
	assertTrue("expect projection", q.getTupleExpr() instanceof Projection);
	Projection proj = (Projection) q.getTupleExpr();
	List<ProjectionElem> list = proj.getProjectionElemList().getElements();
	final ArrayList<String> listNames = new ArrayList<>();
	list.forEach(el -> {
		listNames.add(el.getTargetName());
	});
	assertEquals("expect all bindings", 6, list.size());
	assertTrue("expect s", listNames.contains("s"));
	assertTrue("expect p", listNames.contains("p"));
	assertTrue("expect o", listNames.contains("o"));
	assertTrue("expect q", listNames.contains("q"));
	assertTrue("expect r", listNames.contains("r"));
	assertTrue("expect val", listNames.contains("val"));

	assertTrue("expect Join", proj.getArg() instanceof Join);
	Join join = (Join) proj.getArg();

	assertTrue("expect right arg of Join be StatementPattern", join.getRightArg() instanceof StatementPattern);
	StatementPattern pattern = (StatementPattern) join.getRightArg();
	String anonVar = pattern.getSubjectVar().getName();
	assertEquals("statement pattern predVar value", "urn:pred", pattern.getPredicateVar().getValue().toString());
	assertEquals("statement pattern obj var name", "val", pattern.getObjectVar().getName());

	assertTrue("expect left arg of first Join be Join", join.getLeftArg() instanceof Join);
	Join join2 = (Join) join.getLeftArg();

	assertTrue("expect left arg of second Join be TripleRef", join2.getLeftArg() instanceof TripleRef);
	TripleRef tripleLeft = (TripleRef) join2.getLeftArg();
	assertEquals("subj var name should match", "s", tripleLeft.getSubjectVar().getName());
	assertEquals("pred var name should match", "p", tripleLeft.getPredicateVar().getName());
	assertEquals("obj var name should match", "o", tripleLeft.getObjectVar().getName());
	String anonVarLeftTripleRef = tripleLeft.getExprVar().getName();

	assertTrue("expect right arg of second Join be TripleRef", join2.getRightArg() instanceof TripleRef);
	TripleRef triple = (TripleRef) join2.getRightArg();

	assertEquals("subj var name should match anon", anonVarLeftTripleRef, triple.getSubjectVar().getName());
	assertEquals("pred var name should match", "q", triple.getPredicateVar().getName());
	assertEquals("obj var name should match", "r", triple.getObjectVar().getName());

	assertEquals("ext var should match", anonVar, triple.getExprVar().getName());
}
 
Example 19
Source File: JoinSegmentPCJMatcherTest.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
public void testBasicMatchWithFilter() throws Exception {

	String query1 = ""//
			+ "SELECT ?e ?c ?l" //
			+ "{" //
			+ " Filter(?e = <uri:Bob>)" //
			+ " Filter(?c = <uri:Lawyer>)" //
			+ "  ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l . "//
			+ "  ?e a ?c . "//
			+ "  ?e <uri:talksTo> ?l  . "//
			+ "}";//

	String query2 = ""//
			+ "SELECT ?e ?c ?l" //
			+ "{" //
			+ " Filter(?e = <uri:Bob>)" //
			+ " ?e a ?c . "//
			+ " ?e <uri:talksTo> ?l . "//
			+ "}";//

	SPARQLParser parser = new SPARQLParser();
	ParsedQuery pq1 = parser.parseQuery(query1, null);
	ParsedQuery pq2 = parser.parseQuery(query2, null);
	TupleExpr te1 = pq1.getTupleExpr();
	TupleExpr te2 = pq2.getTupleExpr();
	Projection proj = (Projection) te1;
	Filter filter = (Filter) proj.getArg();

	ExternalSetMatcher<ExternalTupleSet> jsm = pcjFactory.getMatcher(qFactory.getQuerySegment(filter));
	SimpleExternalTupleSet pcj = new SimpleExternalTupleSet((Projection)te2);
	Assert.assertEquals(true, jsm.match(pcj));
	TupleExpr te = jsm.getQuery();
	Assert.assertEquals(new HashSet<QueryModelNode>(), jsm.getUnmatchedArgNodes());

	Set<QueryModelNode> qNodes = QueryNodeGatherer.getNodes(te);
	List<QueryModelNode> nodes = jsm.getOrderedNodes();
	Set<QueryModelNode> nodeSet = new HashSet<>();
	nodeSet.add(nodes.get(0));
	nodeSet.add(pcj);
	nodeSet.add(nodes.get(1));

	Assert.assertEquals(nodeSet, new HashSet<QueryModelNode>(nodes));
	Assert.assertEquals(nodeSet, qNodes);

}
 
Example 20
Source File: JoinSegmentPCJMatcherTest.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
public void testBasicSegment() throws MalformedQueryException {

	String query1 = ""//
			+ "SELECT ?e ?c ?l" //
			+ "{" //
			+ "  ?e a ?c . "//
			+ "  ?e <uri:talksTo> ?l  . "//
			+ "  ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l "//
			+ "}";//

	String query2 = ""//
			+ "SELECT ?e ?c ?l" //
			+ "{" //
			+ "  ?e a ?c . "//
			+ "  ?e <uri:talksTo> ?l  . "//
			+ "}";//

	SPARQLParser parser = new SPARQLParser();
	ParsedQuery pq1 = parser.parseQuery(query1, null);
	ParsedQuery pq2 = parser.parseQuery(query2, null);
	TupleExpr te1 = pq1.getTupleExpr();
	TupleExpr te2 = pq2.getTupleExpr();
	Projection proj = (Projection) te1;
	Join join = (Join) proj.getArg();

	ExternalSetMatcher<ExternalTupleSet> jsm = pcjFactory.getMatcher(qFactory.getQuerySegment(join));
	SimpleExternalTupleSet pcj = new SimpleExternalTupleSet((Projection)te2);
	Assert.assertEquals(true, jsm.match(pcj));
	TupleExpr te = jsm.getQuery();
	Assert.assertEquals(new HashSet<QueryModelNode>(), jsm.getUnmatchedArgNodes());

	Set<QueryModelNode> qNodes = QueryNodeGatherer.getNodes(te);
	List<QueryModelNode> nodes = jsm.getOrderedNodes();
	Set<QueryModelNode> nodeSet = new HashSet<>();
	nodeSet.add(nodes.get(0));
	nodeSet.add(pcj);

	Assert.assertEquals(nodeSet, new HashSet<QueryModelNode>(nodes));
	Assert.assertEquals(nodeSet, qNodes);

}