Search in sources :

Example 36 with OWLOntology

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

the class RegistryManagerImpl method populateOntology.

protected RegistryOntology populateOntology(OWLNamedObject ind, Set<OWLOntology> registries) throws RegistryContentException {
    IRI ontId = ind.getIRI();
    RegistryItem ront = null;
    if (population.containsKey(ontId)) {
        // We are not allowing multityping either.
        ront = population.get(ontId);
        if (!(ront instanceof RegistryOntology))
            throw new RegistryContentException("Inconsistent multityping: for item " + ontId + " : {" + RegistryOntology.class + ", " + ront.getClass() + "}");
    } else {
        ront = riFactory.createRegistryOntology(ind);
        try {
            population.put(ront.getIRI(), ront);
        } catch (Exception e) {
            log.error("Invalid identifier for library item " + ront, e);
            return null;
        }
    }
    // EXIT nodes.
    Set<OWLNamedObject> libs = new HashSet<OWLNamedObject>();
    OWLDataFactory df = OWLManager.getOWLDataFactory();
    for (OWLOntology o : registries) {
        if (ind instanceof OWLIndividual) {
            // Get usages of isOntologyOf as an object property
            for (OWLIndividual value : ((OWLIndividual) ind).getObjectPropertyValues(isOntologyOf, o)) if (value.isNamed())
                libs.add(value.asOWLNamedIndividual());
            // Get usages of isOntologyOf as an annotation property
            for (OWLAnnotationAssertionAxiom ann : o.getAnnotationAssertionAxioms(ind.getIRI())) if (isOntologyOfAnn.equals(ann.getProperty())) {
                OWLAnnotationValue value = ann.getValue();
                if (value instanceof OWLNamedObject)
                    libs.add((OWLNamedObject) value);
                else if (value instanceof IRI)
                    libs.add(df.getOWLNamedIndividual((IRI) value));
            }
        }
    }
    for (OWLNamedObject ilib : libs) {
        IRI parentId = ilib.getIRI();
        // If some populate*() method has created it, it will be there.
        RegistryItem rlib = population.get(parentId);
        // Otherwise populating it will also put it in population.
        if (rlib == null)
            rlib = populateLibrary(ilib, registries);
        ront.addParent(rlib);
        if (ontologyIndex.get(ontId) == null)
            ontologyIndex.put(ontId, new HashSet<IRI>());
        ontologyIndex.get(ontId).add(parentId);
    }
    return (RegistryOntology) ront;
}
Also used : IRI(org.semanticweb.owlapi.model.IRI) OWLAnnotationAssertionAxiom(org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom) RegistryOntology(org.apache.stanbol.ontologymanager.registry.api.model.RegistryOntology) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) OWLOntologyAlreadyExistsException(org.semanticweb.owlapi.model.OWLOntologyAlreadyExistsException) RegistryContentException(org.apache.stanbol.ontologymanager.registry.api.RegistryContentException) OWLNamedObject(org.semanticweb.owlapi.model.OWLNamedObject) OWLAnnotationValue(org.semanticweb.owlapi.model.OWLAnnotationValue) RegistryContentException(org.apache.stanbol.ontologymanager.registry.api.RegistryContentException) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OWLDataFactory(org.semanticweb.owlapi.model.OWLDataFactory) RegistryItem(org.apache.stanbol.ontologymanager.registry.api.model.RegistryItem) HashSet(java.util.HashSet) OWLIndividual(org.semanticweb.owlapi.model.OWLIndividual)

Example 37 with OWLOntology

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

the class RegistryManagerImpl method createModel.

@Override
public Set<Registry> createModel(Set<OWLOntology> registryOntologies) {
    Set<Registry> results = new HashSet<Registry>();
    // Reset population
    population.clear();
    // Build the transitive imports closure of the union.
    Set<OWLOntology> closure = new HashSet<OWLOntology>();
    for (OWLOntology rego : registryOntologies) closure.addAll(rego.getOWLOntologyManager().getImportsClosure(rego));
    /*
         * For each value in this map, index 0 is the score of the library class, while 1 is the score of the
         * ontology class.
         */
    final Map<IRI, int[]> candidateTypes = new HashMap<IRI, int[]>();
    /*
         * Scans class assertions and object property values and tries to determine the type of each
         * individual it finds.
         */
    OWLAxiomVisitor scanner = new OWLAxiomVisitorAdapter() {

        /*
             * For a given identifier, returns the array of integers whose value determine the likelihood if
             * the corresponding entity being a library or an ontology. If no such array exists, it is
             * created.
             */
        private int[] checkScores(IRI key) {
            int[] scores;
            if (candidateTypes.containsKey(key))
                scores = candidateTypes.get(key);
            else {
                scores = new int[] { 0, 0 };
                candidateTypes.put(key, scores);
            }
            return scores;
        }

        @Override
        public void visit(OWLAnnotationAssertionAxiom axiom) {
            /*
                 * Works like object property assertions, in case hasOntology and isOntologyOf are not
                 * detected to be object properties (e.g. due to a failure to load codolight or the registry
                 * metamodel).
                 */
            OWLAnnotationProperty prop = axiom.getProperty();
            if (hasOntologyAnn.equals(prop)) {
                IRI iri;
                // The axiom subject gets a +1 in its library score.
                OWLObject ind = axiom.getSubject();
                if (ind instanceof IRI) {
                    iri = (IRI) ind;
                    checkScores(iri)[0]++;
                }
                // The axiom object gets a +1 in its ontology score.
                ind = axiom.getValue();
                if (ind instanceof IRI) {
                    iri = (IRI) ind;
                    checkScores(iri)[1]++;
                }
            } else if (isOntologyOfAnn.equals(prop)) {
                IRI iri;
                // The axiom subject gets a +1 in its ontology score.
                OWLObject ind = axiom.getSubject();
                if (ind instanceof IRI) {
                    iri = (IRI) ind;
                    checkScores(iri)[1]++;
                }
                // The axiom object gets a +1 in its library score.
                ind = axiom.getValue();
                if (ind instanceof IRI) {
                    iri = (IRI) ind;
                    checkScores(iri)[0]++;
                }
            }
        }

        @Override
        public void visit(OWLClassAssertionAxiom axiom) {
            OWLIndividual ind = axiom.getIndividual();
            // Do not accept anonymous registry items.
            if (ind.isAnonymous())
                return;
            IRI iri = ind.asOWLNamedIndividual().getIRI();
            int[] scores = checkScores(iri);
            OWLClassExpression type = axiom.getClassExpression();
            // If the type is stated to be a library, increase its library score.
            if (cRegistryLibrary.equals(type)) {
                scores[0]++;
            } else // If the type is stated to be an ontology, increase its ontology score.
            if (cOntology.equals(type)) {
                scores[1]++;
            }
        }

        @Override
        public void visit(OWLObjectPropertyAssertionAxiom axiom) {
            OWLObjectPropertyExpression prop = axiom.getProperty();
            if (hasOntology.equals(prop)) {
                IRI iri;
                // The axiom subject gets a +1 in its library score.
                OWLIndividual ind = axiom.getSubject();
                if (!ind.isAnonymous()) {
                    iri = ind.asOWLNamedIndividual().getIRI();
                    checkScores(iri)[0]++;
                }
                // The axiom object gets a +1 in its ontology score.
                ind = axiom.getObject();
                if (!ind.isAnonymous()) {
                    iri = ind.asOWLNamedIndividual().getIRI();
                    checkScores(iri)[1]++;
                }
            } else if (isOntologyOf.equals(prop)) {
                IRI iri;
                // The axiom subject gets a +1 in its ontology score.
                OWLIndividual ind = axiom.getSubject();
                if (!ind.isAnonymous()) {
                    iri = ind.asOWLNamedIndividual().getIRI();
                    checkScores(iri)[1]++;
                }
                // The axiom object gets a +1 in its library score.
                ind = axiom.getObject();
                if (!ind.isAnonymous()) {
                    iri = ind.asOWLNamedIndividual().getIRI();
                    checkScores(iri)[0]++;
                }
            }
        }
    };
    // First pass to determine the types.
    for (OWLOntology o : closure) for (OWLAxiom ax : o.getAxioms()) ax.accept(scanner);
    // Then populate on the registry
    OWLDataFactory df = OWLManager.getOWLDataFactory();
    for (IRI iri : candidateTypes.keySet()) {
        int[] scores = candidateTypes.get(iri);
        if (scores != null && (scores[0] > 0 || scores[1] > 0)) {
            if (scores[0] > 0 && scores[1] == 0)
                population.put(iri, riFactory.createLibrary(df.getOWLNamedIndividual(iri)));
            else if (scores[0] == 0 && scores[1] > 0)
                population.put(iri, riFactory.createRegistryOntology(df.getOWLNamedIndividual(iri)));
        }
    // else log.warn("Unable to determine type for registry item {}", iri);
    }
    for (OWLOntology oReg : registryOntologies) {
        try {
            results.add(populateRegistry(oReg));
        } catch (RegistryContentException e) {
            log.error("An error occurred while populating an ontology registry.", e);
        }
    }
    return results;
}
Also used : OWLObject(org.semanticweb.owlapi.model.OWLObject) IRI(org.semanticweb.owlapi.model.IRI) OWLAnnotationAssertionAxiom(org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom) OWLAxiomVisitor(org.semanticweb.owlapi.model.OWLAxiomVisitor) HashMap(java.util.HashMap) Registry(org.apache.stanbol.ontologymanager.registry.api.model.Registry) OWLClassExpression(org.semanticweb.owlapi.model.OWLClassExpression) OWLAxiomVisitorAdapter(org.semanticweb.owlapi.util.OWLAxiomVisitorAdapter) OWLAnnotationProperty(org.semanticweb.owlapi.model.OWLAnnotationProperty) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OWLObjectPropertyExpression(org.semanticweb.owlapi.model.OWLObjectPropertyExpression) RegistryContentException(org.apache.stanbol.ontologymanager.registry.api.RegistryContentException) OWLObjectPropertyAssertionAxiom(org.semanticweb.owlapi.model.OWLObjectPropertyAssertionAxiom) OWLAxiom(org.semanticweb.owlapi.model.OWLAxiom) OWLClassAssertionAxiom(org.semanticweb.owlapi.model.OWLClassAssertionAxiom) OWLDataFactory(org.semanticweb.owlapi.model.OWLDataFactory) HashSet(java.util.HashSet) OWLIndividual(org.semanticweb.owlapi.model.OWLIndividual)

Example 38 with OWLOntology

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

the class ODPRegistryCacheManager method retrieveRemoteResource.

/**
     * Gets the remote ontology and saves it locally
     * 
     * @param uri
     * @return
     * @throws OWLOntologyCreationException
     * @throws UnknownOWLOntologyException
     * @throws OWLOntologyStorageException
     */
private static synchronized OWLOntology retrieveRemoteResource(URI uri) throws OWLOntologyCreationException, UnknownOWLOntologyException, OWLOntologyStorageException {
    manager.setSilentMissingImportsHandling(true);
    manager.addMissingImportListener(new MissingImportListener() {

        public void importMissing(MissingImportEvent arg0) {
            if (!getUnresolvedURIs().contains(arg0.getImportedOntologyURI()))
                getUnresolvedURIs().add(arg0.getImportedOntologyURI().toURI());
        }
    });
    manager.addOntologyLoaderListener(new OWLOntologyLoaderListener() {

        @Override
        public void startedLoadingOntology(LoadingStartedEvent event) {
        // Nothing to do
        }

        @Override
        public void finishedLoadingOntology(LoadingFinishedEvent event) {
            URI onturi = event.getDocumentIRI().toURI();
            if (event.getException() != null) {
                getUnresolvedURIs().add(onturi);
                LoggerFactory.getLogger(ODPRegistryCacheManager.class).warn("Failed to resolve ontology at " + onturi + " . Skipping.", event.getException());
                return;
            }
            try {
                if (!uris.containsKey(onturi)) {
                    cacheOntology(onturi, newFile(), manager.getOntology(event.getOntologyID()));
                }
            } catch (UnknownOWLOntologyException e) {
                LoggerFactory.getLogger(ODPRegistryCacheManager.class).warn("Failed to cache ontology at " + onturi + " . Skipping.", e);
                getUnresolvedURIs().add(onturi);
            } catch (OWLOntologyStorageException e) {
                LoggerFactory.getLogger(ODPRegistryCacheManager.class).warn("Failed to cache ontology at " + onturi + " . Skipping.", e);
                getUnresolvedURIs().add(onturi);
            }
        }
    });
    OWLOntology ont;
    try {
        ont = manager.loadOntologyFromOntologyDocument(IRI.create(uri));
    } catch (OWLOntologyAlreadyExistsException e) {
        ont = manager.getOntology(e.getOntologyID().getOntologyIRI());
    }
    File file = newFile();
    cacheOntology(uri, file, ont);
    return ont;
}
Also used : MissingImportEvent(org.semanticweb.owlapi.model.MissingImportEvent) UnknownOWLOntologyException(org.semanticweb.owlapi.model.UnknownOWLOntologyException) URI(java.net.URI) OWLOntologyAlreadyExistsException(org.semanticweb.owlapi.model.OWLOntologyAlreadyExistsException) MissingImportListener(org.semanticweb.owlapi.model.MissingImportListener) OWLOntologyLoaderListener(org.semanticweb.owlapi.model.OWLOntologyLoaderListener) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) File(java.io.File) OWLOntologyStorageException(org.semanticweb.owlapi.model.OWLOntologyStorageException)

Example 39 with OWLOntology

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

the class TestClerezzaProvider method testVersionIRISplit.

@Test
public void testVersionIRISplit() throws Exception {
    // Check the first version
    InputStream data = getClass().getResourceAsStream(fn1);
    OWLOntologyID key1 = ontologyProvider.loadInStore(data, RDF_XML, true);
    assertNotNull(key1);
    assertFalse(key1.isAnonymous());
    // Check the second version
    data = getClass().getResourceAsStream(fn2);
    OWLOntologyID key2 = ontologyProvider.loadInStore(data, RDF_XML, true);
    assertNotNull(key2);
    assertFalse(key2.isAnonymous());
    // Must be 2 different graphs
    assertFalse(key1.equals(key2));
    assertEquals(2, ontologyProvider.listPrimaryKeys().size());
    // Ontologies must not be tainting each other
    // Don't use keys any more here. They're not the real public keys!
    Set<OWLOntology> oAll = new HashSet<OWLOntology>();
    for (OWLOntologyID key : ontologyProvider.listPrimaryKeys()) {
        log.info("Found public key {}", key);
        oAll.add(ontologyProvider.getStoredOntology(key, OWLOntology.class, true));
    }
    Iterator<OWLOntology> it = oAll.iterator();
    OWLOntology o1 = it.next();
    OWLOntology o2 = it.next();
    for (OWLNamedIndividual i : o1.getIndividualsInSignature()) {
        Set<OWLClassExpression> tAll = i.getTypes(oAll), t1 = i.getTypes(o1), t2 = i.getTypes(o2);
        // Should be obvious from the OWL API
        assertTrue(tAll.containsAll(t1));
        // Should be obvious from the OWL API
        assertTrue(tAll.containsAll(t2));
        assertFalse(t1.containsAll(t2));
        assertFalse(t2.containsAll(t1));
    }
}
Also used : InputStream(java.io.InputStream) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OWLNamedIndividual(org.semanticweb.owlapi.model.OWLNamedIndividual) OWLClassExpression(org.semanticweb.owlapi.model.OWLClassExpression) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 40 with OWLOntology

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

the class TestOntologyReconciliation method anonymousFromURLWithCustomKeys.

/*
     * If an anonymous ontology is loaded from a URL and at least one override is provided, the first override
     * should be the primary key, while everything else, including the URL, should be an alias for that key.
     */
@Test
public void anonymousFromURLWithCustomKeys() throws Exception {
    OWLOntologyID myKey = new OWLOntologyID(IRI.create("nameless"), IRI.create(getClass().getCanonicalName() + "#anonymousFromURLWithCustomKeys()"));
    OWLOntologyID alias = new OWLOntologyID(IRI.create("nameless"), IRI.create(getClass().getCanonicalName() + "#anonymousFromURLWithCustomKeys().alias"));
    URL url = getClass().getResource(location_nameless);
    OWLOntologyManager onMgr = OWLManager.createOWLOntologyManager();
    OWLOntology o1 = onMgr.loadOntologyFromOntologyDocument(IRI.create(url));
    assertTrue(o1.isAnonymous());
    OWLOntologyID key = ontologyProvider.loadInStore(IRI.create(url), RDF_XML, false, Origin.create(myKey), Origin.create(alias));
    assertNotNull(key);
    assertFalse(key.isAnonymous());
    assertEquals(myKey, key);
    log.info("Anonymous ontology loaded with non-anonymous public key {} (submitted)", key);
    // should have 2 aliases: the physical location and the submitted alias.
    assertEquals(2, ontologyProvider.listAliases(key).size());
    for (OWLOntologyID al : ontologyProvider.listAliases(key)) {
        assertFalse(al.isAnonymous());
        log.info("Named alias detected {}", al);
    }
    // Now retrieve using the alias...
    OWLOntology o2 = ontologyProvider.getStoredOntology(alias, OWLOntology.class, false);
    assertTrue(o2.isAnonymous());
    // Cannot equal OWLOntology objects
    assertEquals(o1.getAxioms(), o2.getAxioms());
    // ... and using the physical IRI
    o2 = ontologyProvider.getStoredOntology(new OWLOntologyID(IRI.create(url)), OWLOntology.class, false);
    assertTrue(o2.isAnonymous());
    // Cannot equal OWLOntology objects
    assertEquals(o1.getAxioms(), o2.getAxioms());
}
Also used : OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OWLOntologyManager(org.semanticweb.owlapi.model.OWLOntologyManager) URL(java.net.URL) 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