Search in sources :

Example 96 with OWLOntology

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

the class JenaToOwlConvert method EntityOwlToJenaResource.

// //////////////////////////////////////////////////////////////////////////////
/**
     * This function converts any thingths relatives to an OWL entity in an iterator over Jena statement
     * 
     * @param entity
     *            {It could be a class, an object property or a data property}
     * @param owlmodel
     *            {OWLOntology model where to retrieve information about the entity}
     * @param format
     *            {RDF/XML or TURTLE}
     * @return {An iterator over jena statement}
     */
public synchronized StmtIterator EntityOwlToJenaResource(OWLEntity entity, OWLOntology owlmodel, String format) {
    while (available == false) {
        try {
            wait();
        } catch (InterruptedException e) {
            System.err.println("EntityOwlToJenaResource::: " + e);
        }
    }
    available = false;
    try {
        OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
        OWLOntology ontology = manager.createOntology(IRI.create("http://www.semanticweb.org/owlapi/ontologies/ontology"));
        // If the entity is a class
        if (entity.isOWLClass()) {
            OWLClass owldata = entity.asOWLClass();
            Iterator<OWLClassAxiom> entityaxiom = owlmodel.getAxioms(owldata).iterator();
            while (entityaxiom.hasNext()) manager.addAxiom(ontology, entityaxiom.next());
            Iterator<OWLAnnotationAssertionAxiom> annotations = entity.getAnnotationAssertionAxioms(owlmodel).iterator();
            while (annotations.hasNext()) manager.addAxiom(ontology, annotations.next());
        }
        // If the entity is a data property
        if (entity.isOWLDataProperty()) {
            OWLDataProperty owldata = entity.asOWLDataProperty();
            Iterator<OWLDataPropertyAxiom> entityaxiom = owlmodel.getAxioms(owldata).iterator();
            while (entityaxiom.hasNext()) manager.addAxiom(ontology, entityaxiom.next());
            Iterator<OWLAnnotationAssertionAxiom> annotations = entity.getAnnotationAssertionAxioms(owlmodel).iterator();
            while (annotations.hasNext()) manager.addAxiom(ontology, annotations.next());
        }
        // If the entity is an object property
        if (entity.isOWLObjectProperty()) {
            OWLObjectProperty owldata = entity.asOWLObjectProperty();
            Iterator<OWLObjectPropertyAxiom> entityaxiom = owlmodel.getAxioms(owldata).iterator();
            while (entityaxiom.hasNext()) manager.addAxiom(ontology, entityaxiom.next());
            Iterator<OWLAnnotationAssertionAxiom> annotations = entity.getAnnotationAssertionAxioms(owlmodel).iterator();
            while (annotations.hasNext()) manager.addAxiom(ontology, annotations.next());
        }
        // If the entity is a data type
        if (entity.isOWLDatatype()) {
            OWLDatatype owldata = entity.asOWLDatatype();
            Iterator<OWLDatatypeDefinitionAxiom> entityaxiom = owlmodel.getAxioms(owldata).iterator();
            while (entityaxiom.hasNext()) manager.addAxiom(ontology, entityaxiom.next());
            Iterator<OWLAnnotationAssertionAxiom> annotations = entity.getAnnotationAssertionAxioms(owlmodel).iterator();
            while (annotations.hasNext()) manager.addAxiom(ontology, annotations.next());
        }
        // If the entity is an individual
        if (entity.isOWLNamedIndividual()) {
            OWLNamedIndividual owldata = entity.asOWLNamedIndividual();
            Iterator<OWLIndividualAxiom> entityaxiom = owlmodel.getAxioms(owldata).iterator();
            while (entityaxiom.hasNext()) manager.addAxiom(ontology, entityaxiom.next());
            Iterator<OWLAnnotationAssertionAxiom> annotations = entity.getAnnotationAssertionAxioms(owlmodel).iterator();
            while (annotations.hasNext()) manager.addAxiom(ontology, annotations.next());
        }
        // If the entity is an annotations property
        if (entity.isOWLAnnotationProperty()) {
            OWLAnnotationProperty owldata = entity.asOWLAnnotationProperty();
            Iterator<OWLAnnotationAxiom> entityaxiom = owlmodel.getAxioms(owldata).iterator();
            while (entityaxiom.hasNext()) manager.addAxiom(ontology, entityaxiom.next());
            Iterator<OWLAnnotationAssertionAxiom> annotations = entity.getAnnotationAssertionAxioms(owlmodel).iterator();
            while (annotations.hasNext()) manager.addAxiom(ontology, annotations.next());
        }
        OntModel ontmodel = ModelOwlToJenaConvert(ontology, format);
        StmtIterator statement = ontmodel.listStatements();
        available = true;
        notifyAll();
        return statement;
    } catch (OWLOntologyCreationException eoc) {
        System.err.print("EntityOwlToJenaResource::: ");
        eoc.printStackTrace();
        return null;
    }
}
Also used : OWLDatatype(org.semanticweb.owlapi.model.OWLDatatype) OWLClassAxiom(org.semanticweb.owlapi.model.OWLClassAxiom) OWLAnnotationProperty(org.semanticweb.owlapi.model.OWLAnnotationProperty) OWLDataProperty(org.semanticweb.owlapi.model.OWLDataProperty) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OWLNamedIndividual(org.semanticweb.owlapi.model.OWLNamedIndividual) OntModel(com.hp.hpl.jena.ontology.OntModel) OWLOntologyManager(org.semanticweb.owlapi.model.OWLOntologyManager) OWLAnnotationAssertionAxiom(org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom) StmtIterator(com.hp.hpl.jena.rdf.model.StmtIterator) OWLIndividualAxiom(org.semanticweb.owlapi.model.OWLIndividualAxiom) OWLObjectProperty(org.semanticweb.owlapi.model.OWLObjectProperty) OWLObjectPropertyAxiom(org.semanticweb.owlapi.model.OWLObjectPropertyAxiom) OWLDatatypeDefinitionAxiom(org.semanticweb.owlapi.model.OWLDatatypeDefinitionAxiom) OWLDataPropertyAxiom(org.semanticweb.owlapi.model.OWLDataPropertyAxiom) OWLAnnotationAxiom(org.semanticweb.owlapi.model.OWLAnnotationAxiom) OWLClass(org.semanticweb.owlapi.model.OWLClass)

Example 97 with OWLOntology

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

the class ScopeSetRenderer method getScopes.

public static OWLOntology getScopes(Set<Scope> scopes) {
    OWLOntologyManager mgr = OWLManager.createOWLOntologyManager();
    OWLOntology ont = null;
    try {
        ont = mgr.createOntology();
    } catch (OWLOntologyCreationException e) {
        LoggerFactory.getLogger(ScopeSetRenderer.class).error("KReS :: could not create empty ontology for rendering scopes.", e);
        return null;
    }
    List<OWLOntologyChange> additions = new LinkedList<OWLOntologyChange>();
    // The ODP metadata vocabulary is always imported.
    // TODO : also import the ONM meta when it goes online.
    additions.add(new AddImport(ont, __factory.getOWLImportsDeclaration(IRI.create("http://www.ontologydesignpatterns.org/schemas/meta.owl"))));
    for (Scope scope : scopes) {
        OWLNamedIndividual iScope = __factory.getOWLNamedIndividual(IRI.create(scope.getDefaultNamespace() + scope.getID()));
        OWLAxiom ax = __factory.getOWLClassAssertionAxiom(cScope, iScope);
        additions.add(new AddAxiom(ont, ax));
    }
    mgr.applyChanges(additions);
    return ont;
}
Also used : AddAxiom(org.semanticweb.owlapi.model.AddAxiom) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) Scope(org.apache.stanbol.ontologymanager.servicesapi.scope.Scope) OWLOntologyChange(org.semanticweb.owlapi.model.OWLOntologyChange) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OWLNamedIndividual(org.semanticweb.owlapi.model.OWLNamedIndividual) OWLOntologyManager(org.semanticweb.owlapi.model.OWLOntologyManager) OWLAxiom(org.semanticweb.owlapi.model.OWLAxiom) AddImport(org.semanticweb.owlapi.model.AddImport) LinkedList(java.util.LinkedList)

Example 98 with OWLOntology

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

the class CustomSpaceImpl method getOntologyAsOWLOntology.

@Override
protected OWLOntology getOntologyAsOWLOntology(OWLOntologyID ontologyId, boolean merge, org.semanticweb.owlapi.model.IRI universalPrefix) {
    OWLOntology o = super.getOntologyAsOWLOntology(ontologyId, merge, universalPrefix);
    switch(getConnectivityPolicy()) {
        case LOOSE:
            break;
        case TIGHT:
            String s = getID();
            // strip "custom"
            s = s.substring(0, s.indexOf(SUFFIX));
            // concatenate "core"
            s += SpaceType.CORE.getIRISuffix();
            org.semanticweb.owlapi.model.IRI target = org.semanticweb.owlapi.model.IRI.create(universalPrefix + s);
            o.getOWLOntologyManager().applyChange(new AddImport(o, OWLManager.getOWLDataFactory().getOWLImportsDeclaration(target)));
            break;
        default:
            break;
    }
    return o;
}
Also used : OWLOntology(org.semanticweb.owlapi.model.OWLOntology) AddImport(org.semanticweb.owlapi.model.AddImport)

Example 99 with OWLOntology

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

the class SessionImpl method exportToOWLOntology.

/**
     * TODO support merging for attached scopes as well?
     */
@Override
protected OWLOntology exportToOWLOntology(boolean merge, org.semanticweb.owlapi.model.IRI universalPrefix) {
    OWLOntology o = super.exportToOWLOntology(merge, universalPrefix);
    org.semanticweb.owlapi.model.IRI iri = o.getOntologyID().getOntologyIRI();
    if (merge) {
        // Re-merge
        // FIXME try to avoid this.
        ScopeManager onm = ScopeManagerImpl.get();
        final Set<OWLOntology> set = new HashSet<OWLOntology>();
        set.add(o);
        for (String scopeID : attachedScopes) {
            log.debug(" ... Merging with attached scope {}.", scopeID);
            Scope sc = onm.getScope(scopeID);
            if (sc != null)
                set.add(sc.export(OWLOntology.class, merge));
            for (OWLOntologyID ontologyId : managedOntologies) {
                set.add(getOntology(ontologyId, OWLOntology.class, true));
            }
            OWLOntologySetProvider provider = new OWLOntologySetProvider() {

                @Override
                public Set<OWLOntology> getOntologies() {
                    return set;
                }
            };
            OWLOntologyMerger merger = new OWLOntologyMerger(provider);
            try {
                o = merger.createMergedOntology(OWLManager.createOWLOntologyManager(), iri);
            } catch (OWLOntologyCreationException e) {
                log.error("Failed to merge imports for ontology " + iri, e);
                o = null;
            }
        }
    } else
        attachScopeImportsOwlApi(o, universalPrefix);
    return o;
}
Also used : OWLOntologyMerger(org.semanticweb.owlapi.util.OWLOntologyMerger) OWLOntologySetProvider(org.semanticweb.owlapi.model.OWLOntologySetProvider) ScopeManager(org.apache.stanbol.ontologymanager.servicesapi.scope.ScopeManager) Scope(org.apache.stanbol.ontologymanager.servicesapi.scope.Scope) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) HashSet(java.util.HashSet)

Example 100 with OWLOntology

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

the class ClerezzaOntologyProvider method loadInStore.

@Override
public OWLOntologyID loadInStore(Object ontology, final boolean force, Origin<?>... origins) {
    if (ontology == null)
        throw new IllegalArgumentException("No ontology supplied.");
    checkReplaceability(origins);
    long before = System.currentTimeMillis();
    // The final graph
    Graph targetGraph;
    // The supplied ontology converted to Graph
    Graph rdfData;
    if (ontology instanceof OWLOntology) {
        // This will be in memory!
        rdfData = OWLAPIToClerezzaConverter.owlOntologyToClerezzaGraph((OWLOntology) ontology);
    } else if (ontology instanceof Graph) {
        // This might be in memory or in persistent storage.
        rdfData = (Graph) ontology;
    } else
        throw new UnsupportedOperationException("This ontology provider can only accept objects assignable to " + Graph.class + " or " + OWLOntology.class);
    // XXX Force is ignored for the content, but the imports?
    // Now we proceed to assign the primary key to the ontology.
    OWLOntologyID primaryKey = null;
    /*
         * Compute aliases
         */
    IRI graphName = null;
    // Priority aliases.
    List<OWLOntologyID> overrides = new ArrayList<OWLOntologyID>();
    // Second-choice aliases.
    List<org.semanticweb.owlapi.model.IRI> sources = new ArrayList<org.semanticweb.owlapi.model.IRI>();
    // Scan origins ONCE.
    for (int i = 0; i < origins.length; i++) {
        Origin<?> origin = origins[i];
        log.debug("Found origin at index {}", i);
        if (origin == null) {
            log.warn("Null origin at index {}. Skipping.", i);
            continue;
        }
        Object ref = origin.getReference();
        if (ref == null) {
            log.warn("Null reference at index {}. Skipping.", i);
            continue;
        }
        log.debug(" ... Reference is a {}", ref.getClass().getCanonicalName());
        log.debug(" ... Value : {}", ref);
        if (ref instanceof OWLOntologyID) {
            OWLOntologyID key = (OWLOntologyID) ref;
            if (primaryKey == null) {
                primaryKey = key;
                log.debug(" ... assigned as primary key.");
            } else if (primaryKey.equals(key)) {
                log.debug(" ... matches primary key. Skipping.");
            } else {
                overrides.add(key);
                log.debug(" ... assigned as a priority alias for {}", primaryKey);
            }
        } else if (ref instanceof org.semanticweb.owlapi.model.IRI) {
            sources.add((org.semanticweb.owlapi.model.IRI) ref);
            log.debug(" ... assigned as a secondary alias (source) for {}", primaryKey);
        } else if (ref instanceof IRI) {
            if (graphName != null)
                log.warn("ImmutableGraph name already assigned as {}. Skipping.", graphName);
            else {
                graphName = (IRI) ref;
                log.debug(" ... assigned as a graph name for {}", primaryKey);
            }
        } else {
            log.warn("Unhandled type for origin at index {} : {}. Skipping.", i, ref.getClass());
        }
    }
    // The actual logical ID will be dereferenceable no matter what.
    OWLOntologyID extractedId = OWLUtils.extractOntologyID(rdfData);
    if (// Not overridden: set as primary key.
    primaryKey == null)
        // Not overridden: set as primary key.
        primaryKey = extractedId;
    else
        // Overridden: must be an alias anyway.
        overrides.add(extractedId);
    if (// No overrides, no extracted ID.
    primaryKey == null) {
        org.semanticweb.owlapi.model.IRI z;
        // The first IRI found becomes the primary key.
        if (!sources.isEmpty())
            z = sources.iterator().next();
        else // Try the graph name
        if (graphName != null)
            z = org.semanticweb.owlapi.model.IRI.create(graphName.getUnicodeString());
        else
            // Extrema ratio : compute a timestamped primary key.
            z = org.semanticweb.owlapi.model.IRI.create(getClass().getCanonicalName() + "-time:" + System.currentTimeMillis());
        primaryKey = new OWLOntologyID(z);
    }
    // Check if it is possible to avoid reloading the ontology content from its source.
    boolean mustLoad = true;
    if (!force && graphName != null && store.listGraphs().contains(graphName)) {
        // Any failed check will abort the scan.
        boolean condition = true;
        // Check if the extracted ontology ID matches that of the supplied graph.
        // XXX note that anonymous ontologies should be considered a match... or should they not?
        Graph tc = store.getGraph(graphName);
        OWLOntologyID idFromStore = OWLUtils.extractOntologyID(tc);
        condition &= (extractedId == null && idFromStore == null) || extractedId.equals(idFromStore);
        // FIXME not a good policy for graphs that change without altering the size.
        if (condition && rdfData instanceof Graph)
            condition &= tc.size() == rdfData.size();
        mustLoad &= !condition;
    }
    if (!mustLoad && graphName != null) {
        log.debug("ImmutableGraph with ID {} already in store. Default action is to skip storage.", graphName);
        targetGraph = store.getGraph(graphName);
    } else {
        String iri = null;
        if (primaryKey.getOntologyIRI() != null)
            iri = primaryKey.getOntologyIRI().toString();
        if (primaryKey.getVersionIRI() != null)
            iri += ":::" + primaryKey.getVersionIRI().toString();
        // s will become the graph name
        String s = (iri.startsWith(prefix + "::")) ? "" : (prefix + "::");
        s += iri;
        graphName = new IRI(URIUtils.sanitize(s));
        log.debug("Storing ontology with graph ID {}", graphName);
        try {
            targetGraph = store.createGraph(graphName);
        } catch (EntityAlreadyExistsException e) {
            if (graphName.equals(e.getEntityName()))
                targetGraph = store.getGraph(graphName);
            else
                targetGraph = store.createGraph(graphName);
        }
        targetGraph.addAll(rdfData);
    }
    // All is already sanitized by the time we get here.
    // Now do the mappings
    String mappedIds = "";
    // Discard unconventional ontology IDs with only the version IRI
    if (primaryKey != null && primaryKey.getOntologyIRI() != null) {
        // Versioned or not, the real ID mapping is always added
        keymap.setMapping(primaryKey, graphName);
        mappedIds += primaryKey;
        // TODO map unversioned ID as well?
        Triple t = new TripleImpl(keymap.buildResource(primaryKey), SIZE_IN_TRIPLES_URIREF, LiteralFactory.getInstance().createTypedLiteral(Integer.valueOf(rdfData.size())));
        getMetaGraph(Graph.class).add(t);
    }
    // Add aliases.
    for (org.semanticweb.owlapi.model.IRI source : sources) if (source != null)
        overrides.add(new OWLOntologyID(source));
    for (OWLOntologyID alias : overrides) if (alias != null && !alias.equals(primaryKey)) {
        addAlias(primaryKey, alias);
        mappedIds += " , " + alias;
    }
    // Do this AFTER registering the ontology, otherwise import cycles will cause infinite loops.
    if (resolveImports) {
        // Scan resources of type owl:Ontology, but only get the first.
        Iterator<Triple> it = targetGraph.filter(null, RDF.type, OWL.Ontology);
        if (it.hasNext()) {
            // Scan import statements for the one owl:Ontology considered.
            Iterator<Triple> it2 = targetGraph.filter(it.next().getSubject(), OWL.imports, null);
            while (it2.hasNext()) {
                RDFTerm obj = it2.next().getObject();
                log.info("Resolving import target {}", obj);
                if (obj instanceof IRI)
                    try {
                        // TODO try locals first
                        IRI target = (IRI) obj;
                        OWLOntologyID id = new OWLOntologyID(org.semanticweb.owlapi.model.IRI.create(target.getUnicodeString()));
                        if (keymap.getMapping(id) == null) {
                            // Check if it's not there already.
                            if (isOfflineMode())
                                throw new RuntimeException("Cannot load imported ontology " + obj + " while Stanbol is in offline mode.");
                            // TODO manage origins for imported ontologies too?
                            OWLOntologyID id2 = loadInStore(org.semanticweb.owlapi.model.IRI.create(((IRI) obj).getUnicodeString()), null, false);
                            if (id2 != null)
                                id = id2;
                            log.info("Import {} resolved.", obj);
                            log.debug("");
                        } else {
                            log.info("Requested import already stored. Setting dependency only.");
                        }
                        descriptor.setDependency(primaryKey, id);
                    } catch (UnsupportedFormatException e) {
                        log.warn("Failed to parse format for resource " + obj, e);
                    // / XXX configure to continue?
                    } catch (IOException e) {
                        log.warn("Failed to load ontology from resource " + obj, e);
                    // / XXX configure to continue?
                    }
            }
        }
    }
    log.debug(" Ontology {}", mappedIds);
    if (targetGraph != null)
        log.debug(" ... ({} triples)", targetGraph.size());
    log.debug(" ... primary public key : {}", primaryKey);
    // log.debug("--- {}", URIUtils.sanitize(s));
    log.debug("Time: {} ms", (System.currentTimeMillis() - before));
    // return URIUtils.sanitize(s);
    return primaryKey;
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) EntityAlreadyExistsException(org.apache.clerezza.rdf.core.access.EntityAlreadyExistsException) ArrayList(java.util.ArrayList) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) TripleImpl(org.apache.clerezza.commons.rdf.impl.utils.TripleImpl) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm) IOException(java.io.IOException) Triple(org.apache.clerezza.commons.rdf.Triple) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) Graph(org.apache.clerezza.commons.rdf.Graph) UnsupportedFormatException(org.apache.clerezza.rdf.core.serializedform.UnsupportedFormatException)

Aggregations

OWLOntology (org.semanticweb.owlapi.model.OWLOntology)116 OWLOntologyCreationException (org.semanticweb.owlapi.model.OWLOntologyCreationException)58 OWLOntologyManager (org.semanticweb.owlapi.model.OWLOntologyManager)49 OWLOntologyID (org.semanticweb.owlapi.model.OWLOntologyID)31 IRI (org.semanticweb.owlapi.model.IRI)30 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