Java Code Examples for org.eclipse.rdf4j.model.vocabulary.RDF#TYPE

The following examples show how to use org.eclipse.rdf4j.model.vocabulary.RDF#TYPE . 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: 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 2
Source File: OrderingTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSelect() {
	MemoryStore repository = new MemoryStore();
	repository.init();

	try (SailConnection connection = repository.getConnection()) {
		connection.begin(IsolationLevels.NONE);
		connection.addStatement(RDFS.RESOURCE, RDF.TYPE, RDFS.RESOURCE);
		connection.addStatement(RDFS.CLASS, RDF.TYPE, RDFS.RESOURCE);
		connection.addStatement(RDFS.SUBCLASSOF, RDF.TYPE, RDFS.RESOURCE);
		connection.commit();

		Select select = new Select(connection, "?a <" + RDF.TYPE + "> []", "*");
		List<Tuple> tuples = new MockConsumePlanNode(select).asList();

		String actual = Arrays.toString(tuples.toArray());

		Collections.sort(tuples);

		String expected = Arrays.toString(tuples.toArray());

		assertEquals(expected, actual);
	}
}
 
Example 3
Source File: MongoEntityIndex2IT.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test()
public void queryIsFullEntityWithExtra() throws Exception {
    // A pattern that has two different subjects.
    final String query = "SELECT * WHERE { " +
            "<urn:SSN:111-11-1111> <" + RDF.TYPE + "> <urn:person> ."+
            "<urn:SSN:111-11-1111> <urn:age> ?age . " +
            "<urn:SSN:111-11-1111> <urn:eye> ?eye . " +
            "<urn:SSN:111-11-1111> <urn:name> ?name . " +
            "<urn:SSN:222-22-2222> <urn:age> ?age . " +
            "<urn:SSN:222-22-2222> <urn:eye> ?eye . " +
            "<urn:SSN:222-22-2222> <urn:name> ?name . " +
        "}";

    final String expectedQuery = "SELECT * WHERE { " +
            "<urn:SSN:111-11-1111> <" + RDF.TYPE + "> <urn:person> ."+
            "<urn:SSN:111-11-1111> <urn:age> ?age . " +
            "<urn:SSN:111-11-1111> <urn:eye> ?eye . " +
            "<urn:SSN:111-11-1111> <urn:name> ?name . " +
        "}";

    final EntityQueryNode expected = new EntityQueryNode(PERSON_TYPE, getSPs(expectedQuery), entityStorage);
    assertOptimizer(query, expected);
}
 
Example 4
Source File: MongoEntityIndex2IT.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test()
public void queryIsSplitEntityWithOptional() throws Exception {
    // A pattern that has two different subjects.
    final String query = "SELECT * WHERE { " +
            "<urn:SSN:111-11-1111> <" + RDF.TYPE + "> <urn:person> ."+
            "<urn:SSN:111-11-1111> <urn:age> ?age . " +
            "<urn:SSN:111-11-1111> <urn:eye> ?eye . " +
            "  OPTIONAL{" +
            "    <urn:SSN:111-11-1111> <urn:name> ?name . " +
            " } . " +
        "}";

    final String expectedQuery = "SELECT * WHERE { " +
            "<urn:SSN:111-11-1111> <" + RDF.TYPE + "> <urn:person> ."+
            "<urn:SSN:111-11-1111> <urn:age> ?age . " +
            "<urn:SSN:111-11-1111> <urn:eye> ?eye . " +
        "}";

    final EntityQueryNode expected = new EntityQueryNode(PERSON_TYPE, getSPs(expectedQuery), entityStorage);
    assertOptimizer(query, expected);
}
 
Example 5
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 6
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 7
Source File: MongoEntityIndexIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void sparqlQuery_Test() throws Exception {
    final Sail sail = RyaSailFactory.getInstance(conf);
    final SailRepositoryConnection conn = new SailRepository(sail).getConnection();
    conn.begin();

    try(MongoEntityIndexer indexer = new MongoEntityIndexer()) {
        indexer.setConf(conf);
        indexer.init();

        setupTypes(indexer);
        addStatements(conn);

        final String query = "SELECT * WHERE { " +
                "<urn:strawberry> <" + RDF.TYPE + "> <urn:icecream> ."+
                "<urn:strawberry> <urn:brand> ?brand . " +
                "<urn:strawberry> <urn:flavor> ?flavor . " +
                "}";

        final TupleQueryResult rez = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate();
        final Set<BindingSet> results = new HashSet<>();
        while(rez.hasNext()) {
            final BindingSet bs = rez.next();
            results.add(bs);
        }
        final MapBindingSet expected = new MapBindingSet();
        expected.addBinding("flavor", VF.createLiteral("Strawberry"));
        expected.addBinding("brand", VF.createLiteral("Awesome Icecream"));

        assertEquals(1, results.size());
        assertEquals(expected, results.iterator().next());
    } finally {
        conn.close();
    }
}
 
Example 8
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 9
Source File: MongoEntityIndexIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void partialQuery_Test() throws Exception {
    final Sail sail = RyaSailFactory.getInstance(conf);
    final SailRepositoryConnection conn = new SailRepository(sail).getConnection();
    conn.begin();

    try(MongoEntityIndexer indexer = new MongoEntityIndexer()) {
        indexer.setConf(conf);
        indexer.init();

        setupTypes(indexer);
        addStatements(conn);
        conn.commit();

        final String query = "SELECT * WHERE { " +
                "<urn:george> <" + RDF.TYPE + "> <urn:person> ."+
                "<urn:george> <urn:name> ?name . " +
                "<urn:george> <urn:eye> ?eye . " +
                "}";

        final TupleQueryResult rez = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate();
        final Set<BindingSet> results = new HashSet<>();
        while(rez.hasNext()) {
            final BindingSet bs = rez.next();
            System.out.println(bs);
            results.add(bs);
        }
        final MapBindingSet expected = new MapBindingSet();
        //expected.addBinding("name", VF.createIRI("http://www.w3.org/2001/SMLSchema#string", "George"));
        expected.addBinding("name", VF.createLiteral("George"));
        expected.addBinding("eye", VF.createLiteral("blue"));

        assertEquals(1, results.size());
        assertEquals(expected, results.iterator().next());
    } finally {
        conn.close();
    }
}
 
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: 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 12
Source File: MongoEntityIndex2IT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test()
public void queryIsPartEntity() throws Exception {
    // A pattern that has two different subjects.
    final String query = "SELECT * WHERE { " +
            "<urn:SSN:111-11-1111> <" + RDF.TYPE + "> <urn:person> ."+
            "<urn:SSN:111-11-1111> <urn:age> ?age . " +
        "}";

    final EntityQueryNode expected = new EntityQueryNode(PERSON_TYPE, getSPs(query), entityStorage);
    assertOptimizer(query, expected);
}
 
Example 13
Source File: AllValuesFromVisitor.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether the StatementPattern is a type query whose solutions could be inferred
 * by allValuesFrom inference, and if so, replaces the node with a union of itself and any
 * possible inference.
 */
@Override
protected void meetSP(StatementPattern node) throws Exception {
    final Var subjVar = node.getSubjectVar();
    final Var predVar = node.getPredicateVar();
    final Var objVar = node.getObjectVar();
    // Only applies to type queries where the type is defined
    if (predVar != null && RDF.TYPE.equals(predVar.getValue()) && objVar != null && objVar.getValue() instanceof Resource) {
        final Resource typeToInfer = (Resource) objVar.getValue();
        Map<Resource, Set<IRI>> relevantAvfRestrictions = inferenceEngine.getAllValuesFromByValueType(typeToInfer);
        if (!relevantAvfRestrictions.isEmpty()) {
            // We can infer the queried type if, for an allValuesFrom restriction type
            // associated  with the queried type, some anonymous neighboring node belongs to the
            // restriction type and has the node in question (subjVar) as a value for the
            // restriction's property.
            final Var avfTypeVar = new Var("t-" + UUID.randomUUID());
            final Var avfPredVar = new Var("p-" + UUID.randomUUID());
            final Var neighborVar = new Var("n-" + UUID.randomUUID());
            neighborVar.setAnonymous(true);
            final StatementPattern membershipPattern = new DoNotExpandSP(neighborVar,
                    new Var(RDF.TYPE.stringValue(), RDF.TYPE), avfTypeVar);
            final StatementPattern valuePattern = new StatementPattern(neighborVar, avfPredVar, subjVar);
            final InferJoin avfPattern = new InferJoin(membershipPattern, valuePattern);
            // Use a FixedStatementPattern to contain the appropriate (restriction, predicate)
            // pairs, and check each one against the general pattern.
            final FixedStatementPattern avfPropertyTypes = new FixedStatementPattern(avfTypeVar,
                    new Var(OWL.ONPROPERTY.stringValue(), OWL.ONPROPERTY), avfPredVar);
            for (Resource avfRestrictionType : relevantAvfRestrictions.keySet()) {
                for (IRI avfProperty : relevantAvfRestrictions.get(avfRestrictionType)) {
                    avfPropertyTypes.statements.add(new NullableStatementImpl(avfRestrictionType,
                            OWL.ONPROPERTY, avfProperty));
                }
            }
            final InferJoin avfInferenceQuery = new InferJoin(avfPropertyTypes, avfPattern);
            node.replaceWith(new InferUnion(node.clone(), avfInferenceQuery));
        }
    }
}
 
Example 14
Source File: SomeValuesFromVisitor.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether the StatementPattern is a type query whose solutions could be inferred by
 * someValuesFrom inference, and if so, replaces the node with a union of itself and any
 * possible inference.
 */
@Override
protected void meetSP(StatementPattern node) throws Exception {
    final Var subjVar = node.getSubjectVar();
    final Var predVar = node.getPredicateVar();
    final Var objVar = node.getObjectVar();
    // Only applies to type queries where the type is defined
    if (predVar != null && RDF.TYPE.equals(predVar.getValue()) && objVar != null && objVar.getValue() instanceof Resource) {
        final Resource typeToInfer = (Resource) objVar.getValue();
        Map<Resource, Set<IRI>> relevantSvfRestrictions = inferenceEngine.getSomeValuesFromByRestrictionType(typeToInfer);
        if (!relevantSvfRestrictions.isEmpty()) {
            // We can infer the queried type if it is to a someValuesFrom restriction (or a
            // supertype of one), and the node in question (subjVar) is the subject of a triple
            // whose predicate is the restriction's property and whose object is an arbitrary
            // node of the restriction's value type.
            final Var valueTypeVar = new Var("t-" + UUID.randomUUID());
            final Var svfPredVar = new Var("p-" + UUID.randomUUID());
            final Var neighborVar = new Var("n-" + UUID.randomUUID());
            neighborVar.setAnonymous(true);
            final StatementPattern membershipPattern = new DoNotExpandSP(neighborVar,
                    new Var(RDF.TYPE.stringValue(), RDF.TYPE), valueTypeVar);
            final StatementPattern valuePattern = new StatementPattern(subjVar, svfPredVar, neighborVar);
            final InferJoin svfPattern = new InferJoin(membershipPattern, valuePattern);
            // Use a FixedStatementPattern to contain the appropriate (predicate, value type)
            // pairs, and check each one against the general pattern.
            final FixedStatementPattern svfPropertyTypes = new FixedStatementPattern(svfPredVar,
                    new Var(OWL.SOMEVALUESFROM.stringValue(), OWL.SOMEVALUESFROM), valueTypeVar);
            for (Resource svfValueType : relevantSvfRestrictions.keySet()) {
                for (IRI svfProperty : relevantSvfRestrictions.get(svfValueType)) {
                    svfPropertyTypes.statements.add(new NullableStatementImpl(svfProperty,
                            OWL.SOMEVALUESFROM, svfValueType));
                }
            }
            final InferJoin svfInferenceQuery = new InferJoin(svfPropertyTypes, svfPattern);
            node.replaceWith(new InferUnion(node.clone(), svfInferenceQuery));
        }
    }
}
 
Example 15
Source File: SPARQLConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testHandlingAddsRemoves() throws Exception {
	ArgumentCaptor<String> sparqlUpdateCaptor = ArgumentCaptor.forClass(String.class);

	subject.begin();
	subject.add(FOAF.PERSON, RDF.TYPE, RDFS.CLASS);
	subject.add(FOAF.AGENT, RDF.TYPE, RDFS.CLASS);
	subject.remove(FOAF.BIRTHDAY, RDF.TYPE, RDF.PROPERTY);
	subject.add(FOAF.AGE, RDF.TYPE, RDF.PROPERTY);
	subject.commit();

	verify(client).sendUpdate(any(), sparqlUpdateCaptor.capture(), any(), any(), anyBoolean(), anyInt(), any());

	String sparqlUpdate = sparqlUpdateCaptor.getValue();

	String expectedAddedTriple1 = "<" + FOAF.PERSON + "> <" + RDF.TYPE + "> <" + RDFS.CLASS + "> .";
	String expectedAddedTriple2 = "<" + FOAF.AGENT + "> <" + RDF.TYPE + "> <" + RDFS.CLASS + "> .";
	String expectedAddedTriple3 = "<" + FOAF.AGE + "> <" + RDF.TYPE + "> <" + RDF.PROPERTY + "> ";
	String expectedRemovedTriple1 = "<" + FOAF.BIRTHDAY + "> <" + RDF.TYPE + "> <" + RDF.PROPERTY + "> .";

	String expectedSequence = "INSERT DATA[^{]*\\{[^}]*\\}[^D]+DELETE DATA[^{]*\\{[^}]*\\}[^I]+INSERT DATA.*";

	assertThat(sparqlUpdate).containsPattern(expectedSequence);
	assertThat(sparqlUpdate).contains(expectedAddedTriple1)
			.contains(expectedAddedTriple2)
			.contains(expectedAddedTriple3)
			.contains(expectedRemovedTriple1);

}
 
Example 16
Source File: SomeValuesFromVisitorTest.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
public void testSomeValuesFrom() throws Exception {
    // 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 and rewrite using the visitor:
    StatementPattern originalSP = new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", person));
    final Projection query = new Projection(originalSP, new ProjectionElemList(new ProjectionElem("s", "subject")));
    query.visit(new SomeValuesFromVisitor(conf, inferenceEngine));
    // Expected structure: a union of two elements: one is equal to the original statement
    // pattern, and the other one joins a list of predicate/value type combinations
    // with another join querying for any nodes who are the subject of a triple with that
    // predicate and with an object of that type.
    //
    // Union(
    //     SP(?node a :impliedType),
    //     Join(
    //         FSP(<?property someValuesFrom ?valueType> {
    //             takesCourse/Course;
    //             takesCourse/GraduateCourse;
    //             headOf/Department;
    //             headOf/Organization;
    //             worksFor/Organization;
    //         }),
    //         Join(
    //             SP(_:object a ?valueType),
    //             SP(?node ?property _:object)
    //         )
    //     )
    Assert.assertTrue(query.getArg() instanceof Union);
    TupleExpr left = ((Union) query.getArg()).getLeftArg();
    TupleExpr right = ((Union) query.getArg()).getRightArg();
    Assert.assertEquals(originalSP, left);
    Assert.assertTrue(right instanceof Join);
    final Join join = (Join) right;
    Assert.assertTrue(join.getLeftArg() instanceof FixedStatementPattern);
    Assert.assertTrue(join.getRightArg() instanceof Join);
    FixedStatementPattern fsp = (FixedStatementPattern) join.getLeftArg();
    left = ((Join) join.getRightArg()).getLeftArg();
    right = ((Join) join.getRightArg()).getRightArg();
    Assert.assertTrue(left instanceof StatementPattern);
    Assert.assertTrue(right instanceof StatementPattern);
    // Verify expected predicate/type pairs
    Assert.assertTrue(fsp.statements.contains(new NullableStatementImpl(takesCourse, OWL.SOMEVALUESFROM, course)));
    Assert.assertTrue(fsp.statements.contains(new NullableStatementImpl(takesCourse, OWL.SOMEVALUESFROM, gradCourse)));
    Assert.assertTrue(fsp.statements.contains(new NullableStatementImpl(headOf, OWL.SOMEVALUESFROM, department)));
    Assert.assertTrue(fsp.statements.contains(new NullableStatementImpl(headOf, OWL.SOMEVALUESFROM, organization)));
    Assert.assertTrue(fsp.statements.contains(new NullableStatementImpl(worksFor, OWL.SOMEVALUESFROM, organization)));
    Assert.assertEquals(5, fsp.statements.size());
    // Verify pattern for matching instances of each pair: a Join of <_:x rdf:type ?t> and
    // <?s ?p _:x> where p and t are the predicate/type pair and s is the original subject
    // variable.
    StatementPattern leftSP = (StatementPattern) left;
    StatementPattern rightSP = (StatementPattern) right;
    Assert.assertEquals(rightSP.getObjectVar(), leftSP.getSubjectVar());
    Assert.assertEquals(RDF.TYPE, leftSP.getPredicateVar().getValue());
    Assert.assertEquals(fsp.getObjectVar(), leftSP.getObjectVar());
    Assert.assertEquals(originalSP.getSubjectVar(), rightSP.getSubjectVar());
    Assert.assertEquals(fsp.getSubjectVar(), rightSP.getPredicateVar());
}
 
Example 17
Source File: DomainRangeVisitorTest.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
public void testRewriteTypePattern() throws Exception {
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    final Set<IRI> domainPredicates = new HashSet<>();
    final Set<IRI> rangePredicates = new HashSet<>();
    domainPredicates.add(advisor);
    domainPredicates.add(takesCourse);
    rangePredicates.add(advisor);
    when(inferenceEngine.getPropertiesWithDomain(person)).thenReturn(domainPredicates);
    when(inferenceEngine.getPropertiesWithRange(person)).thenReturn(rangePredicates);
    final Var subjVar = new Var("s");
    final StatementPattern originalSP = new StatementPattern(subjVar, new Var("p", RDF.TYPE), new Var("o", person));
    final Projection query = new Projection(originalSP, new ProjectionElemList(new ProjectionElem("s", "subject")));
    query.visit(new DomainRangeVisitor(conf, inferenceEngine));
    // Resulting tree should consist of Unions of:
    // 1. The original StatementPattern
    // 2. A join checking for domain inference
    // 3. A join checking for range inference
    boolean containsOriginal = false;
    boolean containsDomain = false;
    boolean containsRange = false;
    final Stack<TupleExpr> nodes = new Stack<>();
    nodes.push(query.getArg());
    while (!nodes.isEmpty()) {
        final TupleExpr currentNode = nodes.pop();
        if (currentNode instanceof Union) {
            nodes.push(((Union) currentNode).getLeftArg());
            nodes.push(((Union) currentNode).getRightArg());
        }
        else if (currentNode instanceof StatementPattern) {
            Assert.assertFalse(containsOriginal);
            Assert.assertEquals(originalSP, currentNode);
            containsOriginal = true;
        }
        else if (currentNode instanceof Join) {
            final TupleExpr left = ((Join) currentNode).getLeftArg();
            final TupleExpr right = ((Join) currentNode).getRightArg();
            Assert.assertTrue("Left-hand side should enumerate domain/range predicates",
                    left instanceof FixedStatementPattern);
            Assert.assertTrue("Right-hand side should be a non-expandable SP matching triples satisfying domain/range",
                    right instanceof DoNotExpandSP);
            final FixedStatementPattern fsp = (FixedStatementPattern) left;
            final StatementPattern sp = (StatementPattern) right;
            // fsp should be <predicate var, domain/range, original type var>
            boolean isDomain = RDFS.DOMAIN.equals(fsp.getPredicateVar().getValue());
            boolean isRange = RDFS.RANGE.equals(fsp.getPredicateVar().getValue());
            Assert.assertTrue(isDomain || isRange);
            Assert.assertEquals(originalSP.getObjectVar(), fsp.getObjectVar());
            // sp should have same predicate var
            Assert.assertEquals(fsp.getSubjectVar(), sp.getPredicateVar());
            // collect predicates that are enumerated in the FixedStatementPattern
            final Set<Resource> queryPredicates = new HashSet<>();
            for (Statement statement : fsp.statements) {
                queryPredicates.add(statement.getSubject());
            }
            if (isDomain) {
                Assert.assertFalse(containsDomain);
                // sp should be <original subject var, predicate var, unbound object var> for domain
                Assert.assertEquals(originalSP.getSubjectVar(), sp.getSubjectVar());
                Assert.assertFalse(sp.getObjectVar().hasValue());
                // verify predicates
                Assert.assertEquals(2, fsp.statements.size());
                Assert.assertEquals(domainPredicates, queryPredicates);
                Assert.assertTrue(queryPredicates.contains(advisor));
                Assert.assertTrue(queryPredicates.contains(takesCourse));
                containsDomain = true;
            }
            else {
                Assert.assertFalse(containsRange);
                // sp should be <unbound subject var, predicate var, original subject var> for range
                Assert.assertFalse(sp.getSubjectVar().hasValue());
                Assert.assertEquals(originalSP.getSubjectVar(), sp.getObjectVar());
                // verify predicates
                Assert.assertEquals(1, fsp.statements.size());
                Assert.assertEquals(rangePredicates, queryPredicates);
                Assert.assertTrue(queryPredicates.contains(advisor));
                containsRange = true;
            }
        }
        else {
            Assert.fail("Expected nested Unions of Joins and StatementPatterns, found: " + currentNode.toString());
        }
    }
    Assert.assertTrue(containsOriginal && containsDomain && containsRange);
}
 
Example 18
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 19
Source File: HasValueVisitor.java    From rya with Apache License 2.0 4 votes vote down vote up
/**
 * Checks whether facts matching the StatementPattern could be derived using
 * has-value inference, and if so, replaces the StatementPattern node with a
 * union of itself and any such possible derivations.
 */
@Override
protected void meetSP(StatementPattern node) throws Exception {
    final Var subjVar = node.getSubjectVar();
    final Var predVar = node.getPredicateVar();
    final Var objVar = node.getObjectVar();
    // We can reason over two types of statement patterns:
    // { ?var rdf:type :Restriction } and { ?var :property ?value }
    // Both require defined predicate
    if (predVar != null && predVar.getValue() != null) {
        final IRI predIRI = (IRI) predVar.getValue();
        if (RDF.TYPE.equals(predIRI) && objVar != null && objVar.getValue() != null
                && objVar.getValue() instanceof Resource) {
            // If the predicate is rdf:type and the type is specified, check whether it can be
            // inferred using any hasValue restriction(s)
            final Resource objType = (Resource) objVar.getValue();
            final Map<IRI, Set<Value>> sufficientValues = inferenceEngine.getHasValueByType(objType);
            if (sufficientValues.size() > 0) {
                final Var valueVar = new Var("v-" + UUID.randomUUID());
                TupleExpr currentNode = node.clone();
                for (IRI property : sufficientValues.keySet()) {
                    final Var propVar = new Var(property.toString(), property);
                    final TupleExpr valueSP = new DoNotExpandSP(subjVar, propVar, valueVar);
                    final FixedStatementPattern relevantValues = new FixedStatementPattern(objVar, propVar, valueVar);
                    for (Value value : sufficientValues.get(property)) {
                        relevantValues.statements.add(new NullableStatementImpl(objType, property, value));
                    }
                    currentNode = new InferUnion(currentNode, new InferJoin(relevantValues, valueSP));
                }
                node.replaceWith(currentNode);
            }
        }
        else {
            // If the predicate has some hasValue restriction associated with it, then finding
            // that the object belongs to the appropriate type implies a value.
            final Map<Resource, Set<Value>> impliedValues = inferenceEngine.getHasValueByProperty(predIRI);
            if (impliedValues.size() > 0) {
                final Var rdfTypeVar = new Var(RDF.TYPE.stringValue(), RDF.TYPE);
                final Var typeVar = new Var("t-" + UUID.randomUUID());
                final Var hasValueVar = new Var(OWL.HASVALUE.stringValue(), OWL.HASVALUE);
                final TupleExpr typeSP = new DoNotExpandSP(subjVar, rdfTypeVar, typeVar);
                final FixedStatementPattern typeToValue = new FixedStatementPattern(typeVar, hasValueVar, objVar);
                final TupleExpr directValueSP = node.clone();
                for (Resource type : impliedValues.keySet()) {
                    // { ?var rdf:type :type } implies { ?var :property :val } for certain (:type, :val) pairs
                    for (Value impliedValue : impliedValues.get(type)) {
                        typeToValue.statements.add(new NullableStatementImpl(type, OWL.HASVALUE, impliedValue));
                    }
                }
                node.replaceWith(new InferUnion(new InferJoin(typeToValue, typeSP), directValueSP));
            }
        }
    }
}
 
Example 20
Source File: IntersectionOfVisitor.java    From rya with Apache License 2.0 4 votes vote down vote up
/**
 * Recursively creates a {@link TupleExpr} tree comprised of
 * {@link InferJoin}s and {@link StatementPattern}s. The left arg is a
 * {@link StatementPattern} and the right arg is either a
 * {@link StatementPattern} if it's the final element or a nested
 * {@link InferJoin}.<p>
 * A list of {@code [:A, :B, :C, :D, :E]} with type {@code ?x} returns:
 * <pre>
 * InferJoin(
 *     StatementPattern(?x, rdf:type, :A),
 *     InferJoin(
 *         StatementPattern(?x, rdf:type, :B),
 *         InferJoin(
 *             StatementPattern(?x, rdf:type, :C),
 *             InferJoin(
 *                 StatementPattern(?x, rdf:type, :D),
 *                 StatementPattern(?x, rdf:type, :E)
 *             )
 *         )
 *     )
 * )
 * </pre>
 * @param intersection a {@link List} of {@link Resource}s.
 * @param typeVar the type {@link Var} to use as the subject for the
 * {@link StatementPattern}.
 * @param conVar the {@link Var} to use as the context for the
 * {@link StatementPattern}.
 * @return the {@link TupleExpr} tree. Returns {@code null} if
 * {@code intersection} is empty. Returns a {@link StatementPattern} if
 * {@code intersection}'s size is 1.  Otherwise, returns an
 * {@link InferJoin} which may contain more nested {@link InferJoin}s.
 */
private static TupleExpr createJoinTree(final List<Resource> intersection, final Var typeVar, final Var conVar) {
    if (intersection.isEmpty()) {
        return null;
    } else {
        final Var predVar = new Var(RDF.TYPE.toString(), RDF.TYPE);
        final Resource resource = intersection.get(0);
        final Var valueVar = new Var(resource.toString(), resource);
        final StatementPattern left = new StatementPattern(typeVar, predVar, valueVar, conVar);
        if (intersection.size() == 1) {
            return left;
        } else {
            final List<Resource> subList = intersection.subList(1, intersection.size());
            final TupleExpr right = createJoinTree(subList, typeVar, conVar);
            final InferJoin join = new InferJoin(left, right);
            join.getProperties().put(InferConstants.INFERRED, InferConstants.TRUE);
            return join;
        }
    }
}