org.eclipse.rdf4j.model.vocabulary.OWL Java Examples

The following examples show how to use org.eclipse.rdf4j.model.vocabulary.OWL. 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: InferenceEngine.java    From rya with Apache License 2.0 6 votes vote down vote up
private void refreshPropertyRestrictions() throws QueryEvaluationException {
    // Get a set of all property restrictions of any type
    final CloseableIteration<Statement, QueryEvaluationException> iter = RyaDAOHelper.query(ryaDAO, null, OWL.ONPROPERTY, null, conf);
    final Map<Resource, IRI> restrictions = new HashMap<>();
    try {
        while (iter.hasNext()) {
            final Statement st = iter.next();
            restrictions.put(st.getSubject(), (IRI) st.getObject());
        }
    } finally {
        if (iter != null) {
            iter.close();
        }
    }
    // Query for specific types of restriction and add their details to the schema
    refreshHasValueRestrictions(restrictions);
    refreshSomeValuesFromRestrictions(restrictions);
    refreshAllValuesFromRestrictions(restrictions);
    refreshHasSelfRestrictions(restrictions);
}
 
Example #2
Source File: Schema.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Add a particular characteristic to a property.
 */
private void addPropertyType(IRI p, Resource t) {
    OwlProperty prop = getProperty(p);
    if (t.equals(OWL.TRANSITIVEPROPERTY)) {
        prop.setTransitive();
    }
    else if (t.equals(OWL.SYMMETRICPROPERTY)) {
        prop.setSymmetric();
    }
    else if (t.equals(OWL2.ASYMMETRICPROPERTY)) {
        prop.setAsymmetric();
    }
    else if (t.equals(OWL.FUNCTIONALPROPERTY)) {
        prop.setFunctional();
    }
    else if (t.equals(OWL.INVERSEFUNCTIONALPROPERTY)) {
        prop.setInverseFunctional();
    }
    else if (t.equals(OWL2.IRREFLEXIVEPROPERTY)) {
        prop.setIrreflexive();
    }
}
 
Example #3
Source File: LocalReasonerTest.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * cls-maxqc2
 */
@Test
public void testMaxQCardinalityZeroThings() throws Exception {
    Resource r = TestUtils.bnode("restriction");
    IRI p = TestUtils.uri("impossiblePredicate2");
    schema.processTriple(TestUtils.statement(r, OWL2.MAXQUALIFIEDCARDINALITY,
        TestUtils.intLiteral("0")));
    schema.processTriple(TestUtils.statement(r, OWL.ONPROPERTY, p));
    schema.processTriple(TestUtils.statement(r, OWL2.ONCLASS, OWL.THING));
    reasoner.processFact(TestUtils.fact(TestUtils.NODE, p,
        TestUtils.uri("y")));
    reasoner.processFact(TestUtils.fact(TestUtils.NODE, RDF.TYPE, r));
    Assert.assertTrue("If p has maxQualifiedCardinality of 0 on owl:Thing;"
        + " then any (x p y) should be found inconsistent",
        reasoner.hasInconsistencies());
}
 
Example #4
Source File: LocalReasonerTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransitivePropertyOutgoingIncoming() throws Exception {
    schema.processTriple(TestUtils.statement(TestUtils.uri("subOrganizationOf"),
        RDF.TYPE, OWL.TRANSITIVEPROPERTY));
    reasoner.processFact(TestUtils.fact(TestUtils.NODE,
        TestUtils.uri("subOrganizationOf"), TestUtils.uri("z")));
    reasoner.processFact(TestUtils.fact(TestUtils.uri("y"),
        TestUtils.uri("subOrganizationOf"), TestUtils.NODE));
    for (Fact t : reasoner.getFacts()) {
        if (t.getSubject().equals(TestUtils.uri("y"))
            && t.getPredicate().equals(TestUtils.uri("subOrganizationOf"))
            && t.getObject().equals(TestUtils.uri("z"))) {
            Assert.fail("Transitive relation should not be inferred "
            + "(received outgoing edge first)");
        }
    }
}
 
Example #5
Source File: LocalReasonerTest.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * cls-svf2
 */
@Test
public void testSomeValuesFromThing() throws Exception {
    schema.processTriple(TestUtils.statement(TestUtils.uri("x"),
        OWL.SOMEVALUESFROM, OWL.THING));
    schema.processTriple(TestUtils.statement(TestUtils.uri("x"),
        OWL.ONPROPERTY, TestUtils.uri("foo")));
    reasoner.processFact(TestUtils.fact(TestUtils.NODE,
        TestUtils.uri("foo"), TestUtils.uri("bar")));
    reasoner.getTypes();
    for (Fact t : reasoner.getFacts()) {
        if (t.getSubject().equals(TestUtils.NODE)
            && t.getPredicate().equals(RDF.TYPE)
            && t.getObject().equals(TestUtils.uri("x"))) {
            return;
        }
    }
    Assert.fail("If x is a property restriction [owl:someValuesFrom owl:Thing]"
        + " on property p; (y p z) should imply (y type x) for any z.");
}
 
Example #6
Source File: CustomFederationConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSize() throws Exception {
	Federation federation = new Federation();

	SailRepository repository = new SailRepository(new MemoryStore());
	federation.addMember(repository);

	federation.initialize();
	try {
		try (SailConnection connection = federation.getConnection()) {
			assertEquals("Should get size", 0, connection.size());

			connection.begin();
			assertEquals("Should get size", 0, connection.size());

			connection.addStatement(OWL.CLASS, RDFS.COMMENT, RDF.REST);
			assertEquals("Should get size", 1, connection.size());

			connection.commit();
			assertEquals("Should get size", 1, connection.size());
		}
	} finally {
		federation.shutDown();
	}
}
 
Example #7
Source File: OntologyRest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Add a new class to ontology identified by the provided IDs from the server associated with the requester's
 * InProgressCommit.
 *
 * @param context     the context of the request.
 * @param recordIdStr the String representing the record Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:".
 * @param classJson   the String representing the new class model.
 * @return a Response indicating whether it was successfully added.
 */
@POST
@Path("{recordId}/classes")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Adds a new class to the identified ontology.")
@ActionId(Modify.TYPE)
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response addClassToOntology(@Context ContainerRequestContext context,
                                   @PathParam("recordId") String recordIdStr,
                                   String classJson) {
    verifyJsonldType(classJson, OWL.CLASS.stringValue());
    try {
        return additionsToInProgressCommit(context, recordIdStr, getModelFromJson(classJson));
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example #8
Source File: OntologyRest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Adds a new object property to the ontology identified by the provided IDs from the server associated with the
 * requester's InProgressCommit.
 *
 * @param context            the context of the request.
 * @param recordIdStr        the String representing the record Resource id. NOTE: Assumes id represents an IRI
 *                           unless String begins with "_:".
 * @param objectPropertyJson the String representing the new property model.
 * @return a Response indicating whether it was successfully added.
 */
@POST
@Path("{recordId}/object-properties")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Adds a new object property to the identified ontology.")
@ActionId(Modify.TYPE)
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response addObjectPropertyToOntology(@Context ContainerRequestContext context,
                                            @PathParam("recordId") String recordIdStr,
                                            String objectPropertyJson) {
    verifyJsonldType(objectPropertyJson, OWL.OBJECTPROPERTY.stringValue());
    try {
        return additionsToInProgressCommit(context, recordIdStr, getModelFromJson(objectPropertyJson));
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example #9
Source File: OntologyRest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Adds a new data property to the ontology identified by the provided IDs from the server associated with the
 * requester's InProgressCommit.
 *
 * @param context          the context of the request.
 * @param recordIdStr      the String representing the record Resource id. NOTE: Assumes id represents an IRI unless
 *                         String begins with "_:".
 * @param dataPropertyJson the String representing the new property model.
 * @return a Response indicating whether it was successfully added.
 */
@POST
@Path("{recordId}/data-properties")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Adds a new data property to the identified ontology.")
@ActionId(Modify.TYPE)
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response addDataPropertyToOntology(@Context ContainerRequestContext context,
                                          @PathParam("recordId") String recordIdStr,
                                          String dataPropertyJson) {
    verifyJsonldType(dataPropertyJson, OWL.DATATYPEPROPERTY.stringValue());
    try {
        return additionsToInProgressCommit(context, recordIdStr, getModelFromJson(dataPropertyJson));
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example #10
Source File: InferenceEngine.java    From rya with Apache License 2.0 6 votes vote down vote up
private void refreshSomeValuesFromRestrictions(final Map<Resource, IRI> restrictions) throws QueryEvaluationException {
    someValuesFromByRestrictionType.clear();
    ryaDaoQueryWrapper.queryAll(null, OWL.SOMEVALUESFROM, null, new AbstractRDFHandler() {
        @Override
        public void handleStatement(final Statement statement) throws RDFHandlerException {
            final Resource restrictionClass = statement.getSubject();
            if (restrictions.containsKey(restrictionClass) && statement.getObject() instanceof Resource) {
                final IRI property = restrictions.get(restrictionClass);
                final Resource valueClass = (Resource) statement.getObject();
                // Should also be triggered by subclasses of the value class
                final Set<Resource> valueClasses = new HashSet<>();
                valueClasses.add(valueClass);
                if (valueClass instanceof IRI) {
                    valueClasses.addAll(getSubClasses((IRI) valueClass));
                }
                for (final Resource valueSubClass : valueClasses) {
                    if (!someValuesFromByRestrictionType.containsKey(restrictionClass)) {
                        someValuesFromByRestrictionType.put(restrictionClass, new ConcurrentHashMap<>());
                    }
                    someValuesFromByRestrictionType.get(restrictionClass).put(valueSubClass, property);
                }
            }
        }
    });
}
 
Example #11
Source File: LocalReasonerTest.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * prp-symp
 */
@Test
public void testSymmetry() throws Exception {
    schema.processTriple(TestUtils.statement(SKOS.RELATED, RDF.TYPE,
        OWL.SYMMETRICPROPERTY));
    reasoner.processFact(TestUtils.fact(TestUtils.uri("y"), SKOS.RELATED,
        TestUtils.NODE));
    for (Fact t : reasoner.getFacts()) {
        if (t.getSubject().equals(TestUtils.NODE)
            && t.getPredicate().equals(SKOS.RELATED)
            && t.getObject().equals(TestUtils.uri("y"))) {
            return;
        }
    }
    Assert.fail("Symmetric property not inferred");
}
 
Example #12
Source File: SchemaReasoningTest.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * scm-avf1
 */
@Test
public void testAllValuesSubClass() throws Exception {
    Resource c1 = TestUtils.bnode("c1");
    Resource c2 = TestUtils.bnode("c2");
    schema.processTriple(TestUtils.statement(c1, OWL.ALLVALUESFROM,
        TestUtils.uri("ResearchGroup")));
    schema.processTriple(TestUtils.statement(c1, OWL.ONPROPERTY,
        TestUtils.uri("worksFor")));
    schema.processTriple(TestUtils.statement(c2, OWL.ALLVALUESFROM,
        TestUtils.uri("Organization")));
    schema.processTriple(TestUtils.statement(c2, OWL.ONPROPERTY,
        TestUtils.uri("worksFor")));
    schema.closure();
    Assert.assertTrue("[allValuesFrom <subclass> on p] should be subclass of"
        + " [allValuesFrom <superclass> on p]",
        schema.getClass(c1).getSuperClasses().contains(c2));
}
 
Example #13
Source File: SimpleOntology.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public OntologyId getOntologyId() {
    try (DatasetConnection conn = getDatasetConnection()) {
        long start = getStartTime();
        Model iris = RepositoryResults.asModelNoContext(
                conn.getStatements(null, vf.createIRI(RDF.TYPE.stringValue()),
                        vf.createIRI(OWL.ONTOLOGY.stringValue()), conn.getSystemDefaultNamedGraph()), mf);
        iris.addAll(RepositoryResults.asModelNoContext(
                conn.getStatements(null, vf.createIRI(OWL.VERSIONIRI.stringValue()),
                        null, conn.getSystemDefaultNamedGraph()), mf));
        OntologyId id = ontologyManager.createOntologyId(iris);
        undoApplyDifferenceIfPresent(conn);
        logTrace("getOntologyId()", start);
        return id;
    }
}
 
Example #14
Source File: OntologyRest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Adds a new individual to the ontology identified by the provided IDs from the server associated with the
 * requester's InProgressCommit.
 *
 * @param context        the context of the request.
 * @param recordIdStr    the String representing the record Resource id. NOTE: Assumes id represents an IRI unless
 *                       String begins with "_:".
 * @param individualJson the String representing the new individual model.
 * @return a Response indicating whether it was successfully added.
 */
@POST
@Path("{recordId}/named-individuals")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Adds a new individual to the identified ontology.")
@ActionId(Modify.TYPE)
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response addIndividualToOntology(@Context ContainerRequestContext context,
                                        @PathParam("recordId") String recordIdStr,
                                        String individualJson) {
    verifyJsonldType(individualJson, OWL.INDIVIDUAL.stringValue());
    try {
        return additionsToInProgressCommit(context, recordIdStr, getModelFromJson(individualJson));
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example #15
Source File: LocalReasonerTest.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * cls-hv2
 */
@Test
public void testHasValueInferClass() throws Exception {
    schema.processTriple(TestUtils.statement(TestUtils.uri("x"), OWL.HASVALUE,
        TestUtils.uri("y")));
    schema.processTriple(TestUtils.statement(TestUtils.uri("x"),
        OWL.ONPROPERTY, TestUtils.uri("p")));
    reasoner.processFact(TestUtils.fact(TestUtils.NODE,
        TestUtils.uri("p"), TestUtils.uri("y")));
    reasoner.getTypes();
    for (Fact t : reasoner.getFacts()) {
        if (t.getSubject().equals(TestUtils.NODE)
            && t.getPredicate().equals(RDF.TYPE)
            && t.getObject().equals(TestUtils.uri("x"))) {
            return;
        }
    }
    Assert.fail("If x is a property restriction [owl:hasValue y]"
        + " on property p; (u p y) should imply (u type x) for any u.");
}
 
Example #16
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Identify all of the subjects in the ontology that have the rdf:type of
 * owl:Class.
 *
 * @return The {@link Collection} of {@link IRI}s that are classes in the
 * ontology
 */
private Collection<IRI> identifyClasses() {
    final Model owlClasses = this.model.filter(null, RDF.TYPE, OWL.CLASS);
    final Model rdfsClasses = this.model.filter(null, RDF.TYPE, RDFS.CLASS);
    classIris = new HashSet<>(owlClasses.size() + rdfsClasses.size());

    owlClasses.stream()
            .map(org.eclipse.rdf4j.model.Statement::getSubject)
            .filter(subject -> subject instanceof IRI)
            .map(subject -> (IRI) subject)
            .forEach(classIris::add);

    rdfsClasses.stream()
            .map(org.eclipse.rdf4j.model.Statement::getSubject)
            .filter(subject -> subject instanceof IRI)
            .map(subject -> (IRI) subject)
            .forEach(classIris::add);
    return classIris;
}
 
Example #17
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Simple method to LOG some warnings if we aren't importing referenced ontologies.
 */
private static void checkImports(final Model checkingModel, final List<ReferenceOntology> referenceOntologies) {
    checkingModel.filter(null, OWL.IMPORTS, null).stream().forEach(stmt -> {
        boolean contains = false;
        for (ReferenceOntology refOnt : referenceOntologies) {
            Optional<org.eclipse.rdf4j.model.Resource> resource = refOnt.getOntologyModel().filter(null, RDF.TYPE, OWL.ONTOLOGY).stream().filter(ontStmt -> ontStmt.getSubject().equals(stmt.getObject())).map(ontStmt -> ontStmt.getSubject()).findFirst();
            if (resource.isPresent()) {
                contains = true;
                break;
            }
        }
        if (!contains) {
            LOG.warn(String.format("Potential error: Generate ontology '%s' specifies that it imports '%s', but it isn't referenced", stmt.getSubject().stringValue(), stmt.getObject().stringValue()));
        }
    });
}
 
Example #18
Source File: SchemaReasoningTest.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * scm-hv
 */
@Test
public void testHasValueSubProp() throws Exception {
    Resource c1 = TestUtils.bnode("c1");
    Resource c2 = TestUtils.bnode("c2");
    schema.processTriple(TestUtils.statement(c1, OWL.HASVALUE,
        TestUtils.stringLiteral("big data")));
    schema.processTriple(TestUtils.statement(c1, OWL.ONPROPERTY,
        TestUtils.uri("researchSpecialty")));
    schema.processTriple(TestUtils.statement(c2, OWL.HASVALUE,
        TestUtils.stringLiteral("big data")));
    schema.processTriple(TestUtils.statement(c2, OWL.ONPROPERTY,
        TestUtils.uri("researchInterest")));
    schema.closure();
    Assert.assertTrue("[hasValue x on <subproperty>] should be subclass of"
        + " [hasValue x on <superproperty>]",
        schema.getClass(c1).getSuperClasses().contains(c2));
}
 
Example #19
Source File: PipelineQueryIT.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiConstruct() throws Exception {
    // Insert data
    final IRI alice = VF.createIRI("urn:Alice");
    final IRI bob = VF.createIRI("urn:Bob");
    final IRI eve = VF.createIRI("urn:Eve");
    final IRI friend = VF.createIRI("urn:friend");
    final IRI knows = VF.createIRI("urn:knows");
    final IRI person = VF.createIRI("urn:Person");
    insert(alice, friend, bob);
    insert(bob, knows, eve);
    insert(eve, knows, alice);
    // Define query and expected results
    final String query = "CONSTRUCT {\n"
            + "    ?x rdf:type owl:Thing .\n"
            + "    ?x rdf:type <urn:Person> .\n"
            + "} WHERE { ?x <urn:knows> ?y }";
    final Multiset<BindingSet> expected = HashMultiset.create();
    final List<String> varNames = Arrays.asList("subject", "predicate", "object");
    expected.add(new ListBindingSet(varNames, bob, RDF.TYPE, OWL.THING));
    expected.add(new ListBindingSet(varNames, bob, RDF.TYPE, person));
    expected.add(new ListBindingSet(varNames, eve, RDF.TYPE, OWL.THING));
    expected.add(new ListBindingSet(varNames, eve, RDF.TYPE, person));
    // Test query
    testPipelineQuery(query, expected);
}
 
Example #20
Source File: SchemaReasoningTest.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * scm-svf1
 */
@Test
public void testSomeValuesSubClass() throws Exception {
    Resource c1 = TestUtils.bnode("c1");
    Resource c2 = TestUtils.bnode("c2");
    schema.processTriple(TestUtils.statement(c1, OWL.SOMEVALUESFROM,
        TestUtils.uri("ResearchGroup")));
    schema.processTriple(TestUtils.statement(c1, OWL.ONPROPERTY,
        TestUtils.uri("worksFor")));
    schema.processTriple(TestUtils.statement(c2, OWL.SOMEVALUESFROM,
        TestUtils.uri("Organization")));
    schema.processTriple(TestUtils.statement(c2, OWL.ONPROPERTY,
        TestUtils.uri("worksFor")));
    schema.closure();
    Assert.assertTrue("[someValuesFrom <subclass> on p] should be subclass of"
        + " [someValuesFrom <superclass> on p]",
        schema.getClass(c1).getSuperClasses().contains(c2));
}
 
Example #21
Source File: SimpleOntology.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Set<OClass> getAllClasses() {
    try (DatasetConnection conn = getDatasetConnection()) {
        long start = getStartTime();
        List<Statement> statements = RepositoryResults.asList(conn.getStatements(null,
                vf.createIRI(RDF.TYPE.stringValue()), vf.createIRI(OWL.CLASS.stringValue()),
                conn.getSystemDefaultNamedGraph()));
        Set<OClass> owlClasses = statements.stream()
                .map(Statement::getSubject)
                .filter(subject -> subject instanceof IRI)
                .map(subject -> new SimpleClass((IRI) subject))
                .collect(Collectors.toSet());
        statements = RepositoryResults.asList(conn.getStatements(null,
                vf.createIRI(RDF.TYPE.stringValue()), vf.createIRI(RDFS.CLASS.stringValue()),
                conn.getSystemDefaultNamedGraph()));
        Set<OClass> rdfsClasses = statements.stream()
                .map(Statement::getSubject)
                .filter(subject -> subject instanceof IRI)
                .map(subject -> new SimpleClass((IRI) subject))
                .collect(Collectors.toSet());
        owlClasses.addAll(rdfsClasses);
        undoApplyDifferenceIfPresent(conn);
        logTrace("getAllClasses()", start);
        return owlClasses;
    }
}
 
Example #22
Source File: SimpleOntology.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Set<AnnotationProperty> getAllAnnotationProperties() {
    try (DatasetConnection conn = getDatasetConnection()) {
        long start = getStartTime();
        List<Statement> statements = RepositoryResults.asList(conn.getStatements(null,
                vf.createIRI(RDF.TYPE.stringValue()), vf.createIRI(OWL.ANNOTATIONPROPERTY.stringValue()),
                conn.getSystemDefaultNamedGraph()));
        Set<AnnotationProperty> annotationProperties = statements.stream()
                .map(Statement::getSubject)
                .map(subject -> new SimpleAnnotationProperty((IRI) subject))
                .collect(Collectors.toSet());
        undoApplyDifferenceIfPresent(conn);
        logTrace("getAllAnnotationProperties()", start);
        return annotationProperties;
    }
}
 
Example #23
Source File: SimpleOntologyIdTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Before
public void setUp() {
    vf = getValueFactory();
    mf = getModelFactory();

    ontologyIRI = vf.createIRI(ontologyIRIString);
    versionIRI = vf.createIRI(versionIRIString);
    identifierIRI = vf.createIRI(identifierString);

    ontologyType = vf.createIRI(OWL.ONTOLOGY.stringValue());
    typeIRI = vf.createIRI(RDF.TYPE.stringValue());
    versionIRIPred = vf.createIRI(OWL.VERSIONIRI.stringValue());

    ArgumentCaptor<IRI> mobiIRI = ArgumentCaptor.forClass(IRI.class);
    ArgumentCaptor<org.semanticweb.owlapi.model.IRI> owlapiIRI = ArgumentCaptor.forClass(org.semanticweb.owlapi.model.IRI.class);

    mockStatic(SimpleOntologyValues.class);
    when(SimpleOntologyValues.owlapiIRI(mobiIRI.capture())).thenAnswer(invocation -> org.semanticweb.owlapi.model.IRI.create(mobiIRI.getValue().stringValue()));
    when(SimpleOntologyValues.mobiIRI(owlapiIRI.capture())).thenAnswer(invocation -> vf.createIRI(owlapiIRI.getValue().getIRIString()));
}
 
Example #24
Source File: SchemaTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testInputDisjointClassReverse() throws Exception {
    Schema schema = new Schema();
    schema.processTriple(TestUtils.statement(SKOS.CONCEPT,
        OWL.DISJOINTWITH, SKOS.COLLECTION));
    Assert.assertTrue("(x disjointWith y): x not found in y's disjoint classes",
        schema.getClass(SKOS.COLLECTION).getDisjointClasses().contains(SKOS.CONCEPT));
}
 
Example #25
Source File: SpinConstructRuleTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnonymousConsequent() throws Exception {
    String text = "CONSTRUCT {\n"
            + "  ?x ?p2 _:something"
            + "} WHERE {\n"
            + "  ?x ?p1 ?y .\n"
            + "  ?p1 rdfs:subPropertyOf ?p2 .\n"
            + "}";
    ParsedGraphQuery query = (ParsedGraphQuery) PARSER.parseQuery(text, null);
    SpinConstructRule rule = new SpinConstructRule(OWL.THING, RL_PRP_SPO1, query);
    Multiset<StatementPattern> expectedAntecedents = HashMultiset.create(Arrays.asList(
            new StatementPattern(new Var("p1"), ac(RDFS.SUBPROPERTYOF), new Var("p2")),
            new StatementPattern(new Var("x"), new Var("p1"), new Var("y"))));
    Assert.assertEquals(expectedAntecedents, HashMultiset.create(rule.getAntecedentPatterns()));
    // should have detected anonymous node
    Assert.assertTrue(rule.hasAnonymousConsequent());
    Var anonymousObject = new Var("object");
    anonymousObject.setAnonymous(true);
    Multiset<StatementPattern> expectedConsequents = HashMultiset.create(Arrays.asList(
            new StatementPattern(new Var("subject"), new Var("predicate"), anonymousObject)));
    Assert.assertEquals(expectedConsequents, HashMultiset.create(rule.getConsequentPatterns()));
    // Pattern matches should be unaffected by anonymous node status
    Assert.assertTrue(rule.canConclude(new StatementPattern(new Var("a"), new Var("b"), new Var("c"))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(new Var("x"), c(RDFS.SUBPROPERTYOF), c(OWL.THING))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(OWL.NOTHING), new Var("prop"), c(OWL.THING))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(FOAF.PERSON), c(RDFS.SUBCLASSOF), new Var("x"))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(OWL.NOTHING), c(RDFS.SUBCLASSOF), c(FOAF.PERSON))));
}
 
Example #26
Source File: SchemaTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testWritabe() throws Exception {
    Resource c1 = TestUtils.bnode("c1");
    Resource c2 = TestUtils.bnode("c2");
    ByteArrayOutputStream outToArray = null;
    {
        SchemaWritable schema = new SchemaWritable();
        // Load up as much variety to make sure it gets de/serialized.
        schema.processTriple(TestUtils.statement(TestUtils.uri("x"), OWL.HASVALUE, TestUtils.uri("y")));
        schema.processTriple(TestUtils.statement(c1, OWL.SOMEVALUESFROM, TestUtils.uri("Organization")));
        schema.processTriple(TestUtils.statement(c1, OWL.ONPROPERTY, TestUtils.uri("worksFor")));
        schema.processTriple(TestUtils.statement(c2, OWL.SOMEVALUESFROM, TestUtils.uri("Organization")));
        schema.processTriple(TestUtils.statement(c2, OWL.ONPROPERTY, TestUtils.uri("memberOf")));
        schema.processTriple(TestUtils.statement(TestUtils.uri("worksFor"), RDFS.SUBPROPERTYOF, TestUtils.uri("memberOf")));
        schema.closure();

        // now serialize and then read/deserialize
        outToArray = new ByteArrayOutputStream();
        DataOutput out = new java.io.DataOutputStream(outToArray);
        schema.write(out);
    }
    byte inputArray[] = outToArray.toByteArray();
    SchemaWritable schema2 = new SchemaWritable();
    schema2.readFields(new DataInputStream(new ByteArrayInputStream(inputArray)));
    Assert.assertTrue("hasValue should be returned for restriction x after serializeing and deserializing.", schema2.getClass(TestUtils.uri("x")).hasValue().contains(TestUtils.uri("y")));
    Assert.assertTrue("[someValuesFrom y on <subproperty>] should be subclass of" + " [someValuesFrom y on <superproperty>]", schema2.getClass(c1).getSuperClasses().contains(c2));
}
 
Example #27
Source File: SimpleOntology.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public boolean containsClass(IRI iri) {
    try (DatasetConnection conn = getDatasetConnection()) {
        long start = getStartTime();
        boolean containsOwl = conn.contains(iri, vf.createIRI(RDF.TYPE.stringValue()),
                vf.createIRI(OWL.CLASS.stringValue()));
        boolean containsRdfs = conn.contains(iri, vf.createIRI(RDF.TYPE.stringValue()),
                vf.createIRI(RDFS.CLASS.stringValue()));
        undoApplyDifferenceIfPresent(conn);
        logTrace("containsClass(" + iri.stringValue() + ")", start);
        return containsOwl || containsRdfs;
    }
}
 
Example #28
Source File: KnowledgeBaseServiceRemoteTest.java    From inception with Apache License 2.0 5 votes vote down vote up
public static KnowledgeBase setOWLSchemaMapping(KnowledgeBase kb)
{
    kb.setClassIri(OWL.CLASS);
    kb.setSubclassIri(RDFS.SUBCLASSOF);
    kb.setTypeIri(RDF.TYPE);
    kb.setDescriptionIri(RDFS.COMMENT);
    kb.setLabelIri(RDFS.LABEL);
    kb.setPropertyTypeIri(RDF.PROPERTY);
    return kb;
}
 
Example #29
Source File: LocalRepositoryManagerIntegrationTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testRestartManagerWithTransaction() throws Exception {
	Repository rep = subject.getRepository(TEST_REPO);
	assertNotNull("Expected repository to exist.", rep);
	assertTrue("Expected repository to be initialized.", rep.isInitialized());
	try (RepositoryConnection conn = rep.getConnection()) {
		conn.begin();
		conn.add(conn.getValueFactory().createIRI("urn:sesame:test:subject"), RDF.TYPE, OWL.ONTOLOGY);
		conn.commit();
		assertEquals(1, conn.size());
	} finally {
		rep.shutDown();
		subject.shutDown();
	}

	subject = new LocalRepositoryManager(datadir);
	subject.initialize();
	Repository rep2 = subject.getRepository(TEST_REPO);
	assertNotNull("Expected repository to exist.", rep2);
	assertTrue("Expected repository to be initialized.", rep2.isInitialized());
	try (RepositoryConnection conn2 = rep2.getConnection()) {
		assertEquals(1, conn2.size());
	} finally {
		rep2.shutDown();
		subject.shutDown();
	}

}
 
Example #30
Source File: GraphQueryResultTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void buildQueries() {
	emptyDescribeQuery = "DESCRIBE <urn:test:non-existent-uri>";
	singleDescribeQuery = "DESCRIBE <" + OWL.THING.stringValue() + ">";
	multipleDescribeQuery = "DESCRIBE <" + OWL.CLASS.stringValue() + ">";

	emptyConstructQuery = "CONSTRUCT { <urn:test:non-existent-uri> ?p ?o . } WHERE { <urn:test:non-existent-uri> ?p ?o . }";
	singleConstructQuery = "CONSTRUCT { ?s ?p <" + OWL.THING.stringValue() + "> . } WHERE { ?s ?p <"
			+ OWL.THING.stringValue() + "> . }";
	multipleConstructQuery = "CONSTRUCT { ?s ?p <" + OWL.CLASS.stringValue() + "> . } WHERE { ?s ?p <"
			+ OWL.CLASS.stringValue() + "> . }";
}