Search in sources :

Example 26 with OWLOntologyID

use of org.semanticweb.owlapi.model.OWLOntologyID 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 27 with OWLOntologyID

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

the class ClerezzaOntologyProvider method computeAliasClosure.

protected void computeAliasClosure(OWLOntologyID publicKey, Set<OWLOntologyID> target) {
    target.add(publicKey);
    Graph meta = getMetaGraph(Graph.class);
    IRI ont = keymap.buildResource(publicKey);
    Set<RDFTerm> resources = new HashSet<RDFTerm>();
    // Forwards
    for (Iterator<Triple> it = meta.filter(ont, OWL.sameAs, null); it.hasNext(); ) resources.add(it.next().getObject());
    // Backwards
    for (Iterator<Triple> it = meta.filter(null, OWL.sameAs, ont); it.hasNext(); ) resources.add(it.next().getSubject());
    for (RDFTerm r : resources) if (r instanceof IRI) {
        OWLOntologyID newKey = keymap.buildPublicKey((IRI) r);
        if (!target.contains(newKey))
            computeAliasClosure(newKey, target);
    }
}
Also used : Triple(org.apache.clerezza.commons.rdf.Triple) 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) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm) HashSet(java.util.HashSet)

Example 28 with OWLOntologyID

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

the class SessionManagerImpl method rebuildSessions.

private void rebuildSessions() {
    if (ontologyProvider == null) {
        log.warn("No ontology provider supplied. Cannot rebuild sessions");
        return;
    }
    OntologyNetworkConfiguration struct = ontologyProvider.getOntologyNetworkConfiguration();
    for (String sessionId : struct.getSessionIDs()) {
        long before = System.currentTimeMillis();
        log.debug("Rebuilding session with ID \"{}\"", sessionId);
        Session session;
        try {
            session = createSession(sessionId);
        } catch (DuplicateSessionIDException e) {
            log.warn("Session \"{}\" already exists and will be reused.", sessionId);
            session = getSession(sessionId);
        } catch (SessionLimitException e) {
            log.error("Cannot create session {}. Session limit of {} reached.", sessionId, getActiveSessionLimit());
            break;
        }
        // Register even if some ontologies were to fail to be restored afterwards.
        sessionsByID.put(sessionId, session);
        // Restored sessions are inactive at first.
        session.setActive(false);
        for (OWLOntologyID key : struct.getOntologyKeysForSession(sessionId)) try {
            session.addOntology(new StoredOntologySource(key));
        } catch (MissingOntologyException ex) {
            log.error("Could not find an ontology with public key {} to be managed by session \"{}\". Proceeding to next ontology.", key, sessionId);
            continue;
        } catch (Exception ex) {
            log.error("Exception caught while trying to add ontology with public key " + key + " to rebuilt session \"" + sessionId + "\". Proceeding to next ontology.", ex);
            continue;
        }
        for (String scopeId : struct.getAttachedScopes(sessionId)) {
            /*
                 * The scope is attached by reference, so we won't have to bother checking if the scope has
                 * been rebuilt by then (which could not happen if the SessionManager is being activated
                 * first).
                 */
            session.attachScope(scopeId);
        }
        log.info("Session \"{}\" rebuilt in {} ms.", sessionId, System.currentTimeMillis() - before);
    }
}
Also used : MissingOntologyException(org.apache.stanbol.ontologymanager.servicesapi.collector.MissingOntologyException) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) SessionLimitException(org.apache.stanbol.ontologymanager.servicesapi.session.SessionLimitException) StoredOntologySource(org.apache.stanbol.ontologymanager.servicesapi.io.StoredOntologySource) NonReferenceableSessionException(org.apache.stanbol.ontologymanager.servicesapi.session.NonReferenceableSessionException) MissingOntologyException(org.apache.stanbol.ontologymanager.servicesapi.collector.MissingOntologyException) SessionLimitException(org.apache.stanbol.ontologymanager.servicesapi.session.SessionLimitException) OWLOntologyStorageException(org.semanticweb.owlapi.model.OWLOntologyStorageException) IOException(java.io.IOException) DuplicateSessionIDException(org.apache.stanbol.ontologymanager.servicesapi.session.DuplicateSessionIDException) OntologyNetworkConfiguration(org.apache.stanbol.ontologymanager.ontonet.api.OntologyNetworkConfiguration) Session(org.apache.stanbol.ontologymanager.servicesapi.session.Session) DuplicateSessionIDException(org.apache.stanbol.ontologymanager.servicesapi.session.DuplicateSessionIDException)

Example 29 with OWLOntologyID

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

the class AbstractOntologyCollectorImpl method removeOntology.

@Override
public void removeOntology(OWLOntologyID publicKey) throws OntologyCollectorModificationException {
    if (publicKey == null)
        throw new IllegalArgumentException("Cannot remove an ontology by providing a null public key.");
    if (publicKey.getOntologyIRI() == null)
        throw new IllegalArgumentException("Cannot remove an ontology whose public key has a null ontology IRI.");
    if (locked)
        throw new UnmodifiableOntologyCollectorException(this);
    Set<OWLOntologyID> aliases = ontologyProvider.listAliases(publicKey);
    aliases.add(publicKey);
    boolean removed = false;
    for (OWLOntologyID alias : aliases) removed |= managedOntologies.remove(alias);
    // Don't fire if the ontology wasn't there in the first place.
    if (removed)
        fireOntologyRemoved(publicKey);
    else
        throw new MissingOntologyException(this, publicKey);
}
Also used : MissingOntologyException(org.apache.stanbol.ontologymanager.servicesapi.collector.MissingOntologyException) UnmodifiableOntologyCollectorException(org.apache.stanbol.ontologymanager.servicesapi.collector.UnmodifiableOntologyCollectorException) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID)

Example 30 with OWLOntologyID

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

the class AbstractOntologyCollectorImpl method exportToGraph.

/**
 * This method has no conversion calls, to it can be invoked by subclasses that wish to modify it
 * afterwards.
 *
 * @param merge
 * @return
 */
protected Graph exportToGraph(boolean merge, org.semanticweb.owlapi.model.IRI prefix) {
    // if (merge) throw new UnsupportedOperationException(
    // "Merge not implemented yet for Clerezza triple collections.");
    long before = System.currentTimeMillis();
    // No need to store, give it a name, or anything.
    Graph root = new SimpleGraph();
    IRI iri = new IRI(prefix + _id);
    // Add the import declarations for directly managed ontologies.
    if (root != null) {
        // Set the ontology ID
        root.add(new TripleImpl(iri, RDF.type, OWL.Ontology));
        if (merge) {
            log.warn("Merging of Clerezza triple collections is only implemented one level down. Import statements will be preserved for further levels.");
            Iterator<Triple> it;
            Set<RDFTerm> importTargets = new HashSet<RDFTerm>();
            for (OWLOntologyID ontologyId : managedOntologies) {
                ImmutableGraph g = getOntology(ontologyId, ImmutableGraph.class, false);
                root.addAll(g);
                it = g.filter(null, OWL.imports, null);
                while (it.hasNext()) {
                    org.semanticweb.owlapi.model.IRI tgt;
                    RDFTerm r = it.next().getObject();
                    try {
                        if (r instanceof IRI)
                            tgt = org.semanticweb.owlapi.model.IRI.create(((IRI) r).getUnicodeString());
                        else if (r instanceof Literal)
                            tgt = org.semanticweb.owlapi.model.IRI.create(((Literal) r).getLexicalForm());
                        else
                            tgt = org.semanticweb.owlapi.model.IRI.create(r.toString());
                        tgt = URIUtils.sanitize(tgt);
                        importTargets.add(new IRI(tgt.toString()));
                    } catch (Exception ex) {
                        log.error("FAILED to obtain import target from resource {}", r);
                        continue;
                    }
                }
                it = g.filter(null, RDF.type, OWL.Ontology);
                while (it.hasNext()) {
                    BlankNodeOrIRI ontology = it.next().getSubject();
                    log.debug("Removing all triples related to {} from {}", ontology, iri);
                    Iterator<Triple> it2 = g.filter(ontology, null, null);
                    while (it2.hasNext()) root.remove(it2.next());
                }
                /*
                     * Reinstate import statements, though. If imported ontologies were not merged earlier, we
                     * are not doing it now anyway.
                     */
                for (RDFTerm target : importTargets) root.add(new TripleImpl(iri, OWL.imports, target));
            }
        } else {
            String base = prefix + getID();
            for (int i = 0; i < backwardPathLength; i++) base = URIUtils.upOne(URI.create(base)).toString();
            base += "/";
            // The key set of managedOntologies contains the ontology IRIs, not their storage keys.
            for (OWLOntologyID ontologyId : managedOntologies) {
                org.semanticweb.owlapi.model.IRI physIRI = // .create(base + ontologyId.getVersionIRI()));
                org.semanticweb.owlapi.model.IRI.create(base + OntologyUtils.encode(ontologyId));
                root.add(new TripleImpl(iri, OWL.imports, new IRI(physIRI.toString())));
            }
        }
        log.debug("Clerezza export of {} completed in {} ms.", getID(), System.currentTimeMillis() - before);
    }
    return root;
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) MissingOntologyException(org.apache.stanbol.ontologymanager.servicesapi.collector.MissingOntologyException) OWLOntologyAlreadyExistsException(org.semanticweb.owlapi.model.OWLOntologyAlreadyExistsException) UnmodifiableOntologyCollectorException(org.apache.stanbol.ontologymanager.servicesapi.collector.UnmodifiableOntologyCollectorException) OntologyCollectorModificationException(org.apache.stanbol.ontologymanager.servicesapi.collector.OntologyCollectorModificationException) Triple(org.apache.clerezza.commons.rdf.Triple) ImmutableGraph(org.apache.clerezza.commons.rdf.ImmutableGraph) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) SimpleGraph(org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph) Graph(org.apache.clerezza.commons.rdf.Graph) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) Literal(org.apache.clerezza.commons.rdf.Literal) SimpleGraph(org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph) TripleImpl(org.apache.clerezza.commons.rdf.impl.utils.TripleImpl) ImmutableGraph(org.apache.clerezza.commons.rdf.ImmutableGraph) HashSet(java.util.HashSet)

Aggregations

OWLOntologyID (org.semanticweb.owlapi.model.OWLOntologyID)101 Test (org.junit.Test)32 OWLOntology (org.semanticweb.owlapi.model.OWLOntology)32 OWLOntologyCreationException (org.semanticweb.owlapi.model.OWLOntologyCreationException)23 HashSet (java.util.HashSet)22 OWLOntologyManager (org.semanticweb.owlapi.model.OWLOntologyManager)21 InputStream (java.io.InputStream)20 BlankNodeOrIRI (org.apache.clerezza.commons.rdf.BlankNodeOrIRI)19 Triple (org.apache.clerezza.commons.rdf.Triple)19 IRI (org.semanticweb.owlapi.model.IRI)18 IRI (org.apache.clerezza.commons.rdf.IRI)17 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)16 RDFTerm (org.apache.clerezza.commons.rdf.RDFTerm)13 IOException (java.io.IOException)12 UnmodifiableOntologyCollectorException (org.apache.stanbol.ontologymanager.servicesapi.collector.UnmodifiableOntologyCollectorException)12 WebApplicationException (javax.ws.rs.WebApplicationException)11 Graph (org.apache.clerezza.commons.rdf.Graph)10 AddImport (org.semanticweb.owlapi.model.AddImport)10 Path (javax.ws.rs.Path)9 OntologySpace (org.apache.stanbol.ontologymanager.servicesapi.scope.OntologySpace)8