Search in sources :

Example 31 with OWLOntology

use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.

the class ConversionTester method testAxiomOwlToJenaResource.

public void testAxiomOwlToJenaResource() {
    JenaToOwlConvert j2o = new JenaToOwlConvert();
    OWLOntologyManager mgr = OWLManager.createOWLOntologyManager();
    OWLOntology ont = null;
    try {
        ont = mgr.createOntology();
    } catch (OWLOntologyCreationException e) {
        e.printStackTrace();
        fail("Can not create ontology");
    }
    OWLDataFactory factory = mgr.getOWLDataFactory();
    StmtIterator resource = null;
    OWLClass cls = factory.getOWLClass(IRI.create(CLAZZ));
    OWLDataProperty dp = factory.getOWLDataProperty(IRI.create(DP));
    OWLObjectProperty op = factory.getOWLObjectProperty(IRI.create(OP));
    OWLAnnotationProperty oa = factory.getOWLAnnotationProperty(IRI.create(label));
    OWLAnnotation oav = factory.getOWLAnnotation(oa, factory.getOWLStringLiteral(clazzlabel, "en"));
    OWLDatatype dt = factory.getOWLDatatype(IRI.create(DATATYPE));
    OWLNamedIndividual sub = factory.getOWLNamedIndividual(IRI.create(SUBJECT));
    OWLNamedIndividual obj = factory.getOWLNamedIndividual(IRI.create(OBJECT));
    OWLLiteral literal1 = factory.getOWLTypedLiteral(VALUE, dt);
    // Classe
    OWLDeclarationAxiom daxiomcls = factory.getOWLDeclarationAxiom(cls);
    // obj prop
    OWLDeclarationAxiom daxiomop = factory.getOWLDeclarationAxiom(op);
    // data prop
    OWLDeclarationAxiom daxiomdp = factory.getOWLDeclarationAxiom(dp);
    // subject
    OWLDeclarationAxiom daxiomsub = factory.getOWLDeclarationAxiom(sub);
    // object
    OWLDeclarationAxiom daxiomobj = factory.getOWLDeclarationAxiom(obj);
    // Istanza
    OWLClassAssertionAxiom axiomsub = factory.getOWLClassAssertionAxiom(cls, sub);
    // Istanza
    OWLClassAssertionAxiom axiomobj = factory.getOWLClassAssertionAxiom(cls, obj);
    // Obj
    OWLObjectPropertyAssertionAxiom axiomop = factory.getOWLObjectPropertyAssertionAxiom(op, sub, obj);
    // prop
    // tra
    // individui
    OWLDataPropertyAssertionAxiom axiomvalue = factory.getOWLDataPropertyAssertionAxiom(dp, obj, // Dataprop all'istanza;
    literal1);
    // Annotazione
    OWLAnnotationAssertionAxiom axioman = factory.getOWLAnnotationAssertionAxiom(cls.getIRI(), oav);
    mgr.addAxiom(ont, daxiomcls);
    mgr.addAxiom(ont, daxiomop);
    mgr.addAxiom(ont, daxiomdp);
    mgr.addAxiom(ont, daxiomsub);
    mgr.addAxiom(ont, daxiomobj);
    mgr.addAxiom(ont, axiomsub);
    mgr.addAxiom(ont, axiomobj);
    mgr.addAxiom(ont, axiomop);
    mgr.addAxiom(ont, axiomvalue);
    mgr.addAxiom(ont, axioman);
    Set<OWLAxiom> setaxiom = ont.getAxioms();
    try {
        resource = j2o.AxiomOwlToJenaResource(setaxiom, RDFXML);
        if (resource == null) {
            fail("Some errors occur");
        } else {
            String statment = "[http://www.w3.org/2000/01/rdf-schema#label, http://www.w3.org/2000/01/rdf-schema#range, http://www.w3.org/2000/01/rdf-schema#Literal] " + "[http://example.org/dummy#hasAge, http://www.w3.org/1999/02/22-rdf-syntax-ns#type, http://www.w3.org/2002/07/owl#DatatypeProperty] " + "[http://example.org/dummy#Linus, http://example.org/dummy#hasAge, \"8\"^^http://www.w3.org/2001/XMLSchema#int] " + "[http://example.org/dummy#Linus, http://www.w3.org/1999/02/22-rdf-syntax-ns#type, http://example.org/dummy#Peanut] " + "[http://example.org/dummy#hasSibling, http://www.w3.org/1999/02/22-rdf-syntax-ns#type, http://www.w3.org/2002/07/owl#ObjectProperty] " + "[http://example.org/dummy#Lucy, http://example.org/dummy#hasSibling, http://example.org/dummy#Linus] " + "[http://example.org/dummy#Lucy, http://www.w3.org/1999/02/22-rdf-syntax-ns#type, http://example.org/dummy#Peanut] " + "[http://www.w3.org/2000/01/rdf-schema#label, http://www.w3.org/1999/02/22-rdf-syntax-ns#type, http://www.w3.org/2002/07/owl#AnnotationProperty] " + "[http://example.org/dummy#Peanut, http://www.w3.org/2000/01/rdf-schema#label, \"Peanut\"@en] " + "[http://example.org/dummy#Peanut, http://www.w3.org/1999/02/22-rdf-syntax-ns#type, http://www.w3.org/2002/07/owl#Class]";
            int size = setaxiom.size();
            int count = 0;
            while (resource.hasNext()) {
                Statement stm = resource.nextStatement();
                Resource jsubj = stm.getSubject();
                if (jsubj.getURI().equals(OP.toString()) || jsubj.getURI().equals(DP.toString()) || jsubj.getURI().equals(CLAZZ.toString()) || jsubj.getURI().equals(OBJECT.toString()) || jsubj.getURI().equals(SUBJECT.toString()) || jsubj.getURI().equals(label.toString()))
                    if (statment.contains(stm.toString()))
                        count++;
            }
            assertEquals(size, count);
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail("Exception caugth");
    } finally {
        assertNotNull(resource);
    }
}
Also used : OWLDeclarationAxiom(org.semanticweb.owlapi.model.OWLDeclarationAxiom) OWLDatatype(org.semanticweb.owlapi.model.OWLDatatype) OWLAnnotationProperty(org.semanticweb.owlapi.model.OWLAnnotationProperty) OWLDataPropertyAssertionAxiom(org.semanticweb.owlapi.model.OWLDataPropertyAssertionAxiom) OWLDataProperty(org.semanticweb.owlapi.model.OWLDataProperty) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OWLNamedIndividual(org.semanticweb.owlapi.model.OWLNamedIndividual) OWLOntologyManager(org.semanticweb.owlapi.model.OWLOntologyManager) OWLAxiom(org.semanticweb.owlapi.model.OWLAxiom) OWLClassAssertionAxiom(org.semanticweb.owlapi.model.OWLClassAssertionAxiom) StmtIterator(com.hp.hpl.jena.rdf.model.StmtIterator) OWLAnnotationAssertionAxiom(org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom) OWLAnnotation(org.semanticweb.owlapi.model.OWLAnnotation) Statement(com.hp.hpl.jena.rdf.model.Statement) Resource(com.hp.hpl.jena.rdf.model.Resource) OWLObjectProperty(org.semanticweb.owlapi.model.OWLObjectProperty) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) OWLLiteral(org.semanticweb.owlapi.model.OWLLiteral) OWLObjectPropertyAssertionAxiom(org.semanticweb.owlapi.model.OWLObjectPropertyAssertionAxiom) OWLClass(org.semanticweb.owlapi.model.OWLClass) OWLDataFactory(org.semanticweb.owlapi.model.OWLDataFactory)

Example 32 with OWLOntology

use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.

the class ClerezzaOntologyProvider method toOWLOntology.

/**
     * 
     * @param graphName
     * @param forceMerge
     *            if set to false, the selected import management policy will be applied.
     * @return
     * @throws OWLOntologyCreationException
     */
protected OWLOntology toOWLOntology(IRI graphName, boolean forceMerge) throws OWLOntologyCreationException {
    log.debug("Exporting graph to OWLOntology");
    log.debug(" -- ImmutableGraph name : {}", graphName);
    OWLOntologyManager mgr = OWLManager.createOWLOntologyManager();
    // Never try to import
    mgr.addIRIMapper(new PhonyIRIMapper(Collections.<org.semanticweb.owlapi.model.IRI>emptySet()));
    Set<OWLOntologyID> loaded = new HashSet<OWLOntologyID>();
    Graph graph = store.getGraph(graphName);
    IRI ontologyId = null;
    // Get the id of this ontology.
    Iterator<Triple> itt = graph.filter(null, RDF.type, OWL.Ontology);
    if (itt.hasNext()) {
        BlankNodeOrIRI nl = itt.next().getSubject();
        if (nl instanceof IRI)
            ontologyId = (IRI) nl;
    }
    List<OWLOntologyID> revImps = new Stack<OWLOntologyID>();
    List<OWLOntologyID> lvl1 = new Stack<OWLOntologyID>();
    fillImportsReverse(keymap.getReverseMapping(graphName), revImps, lvl1);
    // If not set to merge (either by policy of by force), adopt the set import policy.
    if (!forceMerge && !ImportManagementPolicy.MERGE.equals(getImportManagementPolicy())) {
        OWLOntology o = OWLAPIToClerezzaConverter.clerezzaGraphToOWLOntology(graph, mgr);
        // TODO make it not flat.
        // Examining the reverse imports stack will flatten all imports.
        List<OWLOntologyChange> changes = new ArrayList<OWLOntologyChange>();
        OWLDataFactory df = OWLManager.getOWLDataFactory();
        List<OWLOntologyID> listToUse;
        switch(getImportManagementPolicy()) {
            case FLATTEN:
                listToUse = revImps;
                break;
            case PRESERVE:
                listToUse = lvl1;
                break;
            default:
                listToUse = lvl1;
                break;
        }
        for (OWLOntologyID ref : listToUse) if (!loaded.contains(ref) && !ref.equals(keymap.getReverseMapping(graphName))) {
            changes.add(new AddImport(o, df.getOWLImportsDeclaration(ref.getOntologyIRI())));
            loaded.add(ref);
        }
        o.getOWLOntologyManager().applyChanges(changes);
        return o;
    } else {
        // If there is just the root ontology, convert it straight away.
        if (revImps.size() == 1 && revImps.contains(graphName)) {
            OWLOntology o = OWLAPIToClerezzaConverter.clerezzaGraphToOWLOntology(graph, mgr);
            return o;
        }
        // FIXME when there's more than one ontology, this way of merging them seems inefficient...
        Graph tempGraph = new IndexedGraph();
        // The set of triples that will be excluded from the merge
        Set<Triple> exclusions = new HashSet<Triple>();
        // Examine all reverse imports
        for (OWLOntologyID ref : revImps) if (!loaded.contains(ref)) {
            // Get the triples
            Graph imported = // store.getTriples(ref);
            getStoredOntology(getKey(ref), Graph.class, false);
            // For each owl:Ontology
            Iterator<Triple> remove = imported.filter(null, RDF.type, OWL.Ontology);
            while (remove.hasNext()) {
                BlankNodeOrIRI subj = remove.next().getSubject();
                /*
                         * If it's not the root ontology, trash all its triples. If the root ontology is
                         * anonymous, all ontology annotations are to be trashed without distinction.
                         */
                if (ontologyId == null || !subj.equals(ontologyId)) {
                    Iterator<Triple> it = imported.filter(subj, null, null);
                    while (it.hasNext()) {
                        Triple t = it.next();
                        exclusions.add(t);
                    }
                }
            }
            Iterator<Triple> it = imported.iterator();
            while (it.hasNext()) {
                Triple t = it.next();
                if (!exclusions.contains(t))
                    tempGraph.add(t);
            }
            loaded.add(ref);
        }
        // online.
        return OWLAPIToClerezzaConverter.clerezzaGraphToOWLOntology(tempGraph, mgr);
    }
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) ArrayList(java.util.ArrayList) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) AddImport(org.semanticweb.owlapi.model.AddImport) Stack(java.util.Stack) Triple(org.apache.clerezza.commons.rdf.Triple) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) Graph(org.apache.clerezza.commons.rdf.Graph) OWLOntologyChange(org.semanticweb.owlapi.model.OWLOntologyChange) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) PhonyIRIMapper(org.apache.stanbol.commons.owl.PhonyIRIMapper) Iterator(java.util.Iterator) OWLOntologyManager(org.semanticweb.owlapi.model.OWLOntologyManager) OWLDataFactory(org.semanticweb.owlapi.model.OWLDataFactory) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) HashSet(java.util.HashSet)

Example 33 with OWLOntology

use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.

the class ClerezzaOntologyProvider method getStoredOntology.

/**
     * In this implementation the identifier is the ImmutableGraph Name (e.g. ontonet::blabla)
     */
@SuppressWarnings("unchecked")
@Override
@Deprecated
public <O> O getStoredOntology(String identifier, Class<O> returnType, boolean forceMerge) {
    if (identifier == null || identifier.isEmpty())
        throw new IllegalArgumentException("Identifier cannot be null or empty.");
    if (returnType == null) {
        // Defaults to OWLOntology
        returnType = (Class<O>) OWLOntology.class;
        log.warn("No return type given for the ontology. Will return a {}", returnType.getCanonicalName());
    }
    boolean canDo = false;
    for (Class<?> clazz : getSupportedReturnTypes()) if (clazz.isAssignableFrom(returnType)) {
        canDo = true;
        break;
    }
    if (!canDo)
        throw new UnsupportedOperationException("Return type " + returnType.getCanonicalName() + " is not allowed in this implementation. Only allowed return types are " + supported);
    Graph tc = store.getGraph(new IRI(identifier));
    if (tc == null)
        return null;
    if (Graph.class.equals(returnType) || Graph.class.isAssignableFrom(returnType)) {
        return returnType.cast(tc);
    } else if (OWLOntology.class.isAssignableFrom(returnType)) {
        try {
            return (O) toOWLOntology(new IRI(identifier), forceMerge);
        } catch (OWLOntologyCreationException e) {
            log.error("Failed to return stored ontology " + identifier + " as type " + returnType.getCanonicalName(), e);
        }
    }
    return null;
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) Graph(org.apache.clerezza.commons.rdf.Graph) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) OWLOntology(org.semanticweb.owlapi.model.OWLOntology)

Example 34 with OWLOntology

use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.

the class TestOntologyReconciliation method versioned.

/*
     * Two versioned ontologies that share their ontology IRI are stored with separate public keys that manage
     * their full ontology IDs.
     */
@Test
public void versioned() throws Exception {
    OWLOntologyManager onMgr = OWLManager.createOWLOntologyManager();
    // Load the first ontology
    String location = "/ontologies/versiontest_v1.owl";
    InputStream in = getClass().getResourceAsStream(location);
    in.mark(Integer.MAX_VALUE);
    // Keep tack of the original in a separate ontology.
    OWLOntology o1 = onMgr.loadOntologyFromOntologyDocument(in);
    assertFalse(o1.isAnonymous());
    OWLOntologyID id1 = o1.getOntologyID();
    in.reset();
    // in = getClass().getResourceAsStream(location); // use if stream cannot be reset
    OWLOntologyID key = ontologyProvider.loadInStore(in, RDF_XML, false);
    assertNotNull(key);
    assertFalse(key.isAnonymous());
    log.info("Named ontology loaded with public key {}", key);
    assertEquals(id1, key);
    log.info(" -- (matches actual ontology ID).");
    // The unversioned ID should return no match...
    OWLOntologyID unversioned = new OWLOntologyID(key.getOntologyIRI());
    assertSame(Status.NO_MATCH, ontologyProvider.getStatus(unversioned));
    // ...but a query on the available versions should return only the public key.
    Set<OWLOntologyID> versions = ontologyProvider.listVersions(key.getOntologyIRI());
    assertFalse(versions.isEmpty());
    assertSame(1, versions.size());
    assertTrue(versions.contains(id1));
    // Now load the second version.
    location = "/ontologies/versiontest_v2.owl";
    in = getClass().getResourceAsStream(location);
    in.mark(Integer.MAX_VALUE);
    // Keep tack of the original in a separate ontology.
    OWLOntology o2 = onMgr.loadOntologyFromOntologyDocument(in);
    assertFalse(o2.isAnonymous());
    OWLOntologyID id2 = o2.getOntologyID();
    in.reset();
    // in = getClass().getResourceAsStream(location); // use if stream cannot be reset
    key = ontologyProvider.loadInStore(in, RDF_XML, false);
    assertNotNull(key);
    assertFalse(key.isAnonymous());
    log.info("Named ontology loaded with public key {}", key);
    assertEquals(id2, key);
    log.info(" -- (matches actual ontology ID).");
    // The unversioned ID should still return no match...
    assertSame(Status.NO_MATCH, ontologyProvider.getStatus(unversioned));
    // ...but a query on the available versions should return both public keys now.
    versions = ontologyProvider.listVersions(key.getOntologyIRI());
    assertFalse(versions.isEmpty());
    assertSame(2, versions.size());
    assertTrue(versions.contains(id1));
    assertTrue(versions.contains(id2));
    // Check that axioms match for version 1
    log.info("Version 1:");
    OWLOntology o1_1 = ontologyProvider.getStoredOntology(id1, OWLOntology.class, false);
    assertFalse(o1_1.isAnonymous());
    // Cannot equal OWLOntology objects
    assertEquals(o1.getOntologyID(), o1_1.getOntologyID());
    log.warn("Plain OWL API seems to be failing to preserve owl:versionInfo. Will test non-annotation axioms only.");
    assertEquals(o1.getTBoxAxioms(false), o1_1.getTBoxAxioms(false));
    log.info(" -- TBox axiom check successful.");
    assertEquals(o1.getABoxAxioms(false), o1_1.getABoxAxioms(false));
    log.info(" -- ABox axiom check successful.");
    // Check that axioms match for version 2 (therefore differ from each other)
    log.info("Version 2:");
    OWLOntology o2_1 = ontologyProvider.getStoredOntology(id2, OWLOntology.class, false);
    assertFalse(o2_1.isAnonymous());
    // Cannot equal OWLOntology objects
    assertEquals(o2.getOntologyID(), o2_1.getOntologyID());
    log.warn("Plain OWL API seems to be failing to preserve owl:versionInfo. Will test non-annotation axioms only.");
    assertEquals(o2.getTBoxAxioms(false), o2_1.getTBoxAxioms(false));
    log.info(" -- TBox axiom check successful.");
    assertEquals(o2.getABoxAxioms(false), o2_1.getABoxAxioms(false));
    log.info(" -- ABox axiom check successful.");
    // There should be no aliases.
    assertSame(0, ontologyProvider.listAliases(unversioned).size());
    assertSame(0, ontologyProvider.listAliases(id1).size());
    assertSame(0, ontologyProvider.listAliases(id2).size());
}
Also used : InputStream(java.io.InputStream) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) OWLOntologyManager(org.semanticweb.owlapi.model.OWLOntologyManager) Test(org.junit.Test)

Example 35 with OWLOntology

use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.

the class TestClerezzaSpaces method testCreateSpace.

@Test
public void testCreateSpace() throws Exception {
    OntologySpace space = factory.createCustomOntologySpace(scopeId, dropSrc);
    OWLOntologyID logicalId = null;
    Object o = dropSrc.getRootOntology();
    if (o instanceof Graph)
        logicalId = OWLUtils.extractOntologyID((Graph) o);
    else if (o instanceof OWLOntology)
        logicalId = OWLUtils.extractOntologyID((OWLOntology) o);
    assertNotNull(logicalId);
    assertTrue(space.hasOntology(logicalId));
}
Also used : Graph(org.apache.clerezza.commons.rdf.Graph) OntologySpace(org.apache.stanbol.ontologymanager.servicesapi.scope.OntologySpace) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) Test(org.junit.Test)

Aggregations

OWLOntology (org.semanticweb.owlapi.model.OWLOntology)118 OWLOntologyCreationException (org.semanticweb.owlapi.model.OWLOntologyCreationException)59 OWLOntologyManager (org.semanticweb.owlapi.model.OWLOntologyManager)50 IRI (org.semanticweb.owlapi.model.IRI)31 OWLOntologyID (org.semanticweb.owlapi.model.OWLOntologyID)31 Test (org.junit.Test)25 OWLAxiom (org.semanticweb.owlapi.model.OWLAxiom)24 OWLDataFactory (org.semanticweb.owlapi.model.OWLDataFactory)22 HashSet (java.util.HashSet)21 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)18 Produces (javax.ws.rs.Produces)17 AddImport (org.semanticweb.owlapi.model.AddImport)16 OntModel (com.hp.hpl.jena.ontology.OntModel)15 OWLOntologyStorageException (org.semanticweb.owlapi.model.OWLOntologyStorageException)15 InputStream (java.io.InputStream)14 GET (javax.ws.rs.GET)14 OWLClass (org.semanticweb.owlapi.model.OWLClass)14 ArrayList (java.util.ArrayList)13 Graph (org.apache.clerezza.commons.rdf.Graph)12 ReasoningServiceException (org.apache.stanbol.reasoners.servicesapi.ReasoningServiceException)11