Search in sources :

Example 61 with Graph

use of org.apache.clerezza.commons.rdf.Graph 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 62 with Graph

use of org.apache.clerezza.commons.rdf.Graph 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 63 with Graph

use of org.apache.clerezza.commons.rdf.Graph in project stanbol by apache.

the class ClerezzaOntologyProvider method getOntologyNetworkConfiguration.

public OntologyNetworkConfiguration getOntologyNetworkConfiguration() {
    Map<String, Collection<OWLOntologyID>> coreOntologies = new HashMap<String, Collection<OWLOntologyID>>(), customOntologies = new HashMap<String, Collection<OWLOntologyID>>();
    Map<String, Collection<String>> attachedScopes = new HashMap<String, Collection<String>>();
    final Graph meta = store.getGraph(new IRI(metaGraphId));
    // Scopes first
    for (Iterator<Triple> it = meta.filter(null, RDF.type, SCOPE_URIREF); it.hasNext(); ) {
        // for each
        // scope
        Triple ta = it.next();
        BlankNodeOrIRI sub = ta.getSubject();
        if (sub instanceof IRI) {
            String s = ((IRI) sub).getUnicodeString(), prefix = _NS_STANBOL_INTERNAL + Scope.shortName + "/";
            if (s.startsWith(prefix)) {
                String scopeId = s.substring(prefix.length());
                log.info("Rebuilding scope \"{}\".", scopeId);
                coreOntologies.put(scopeId, new TreeSet<OWLOntologyID>());
                customOntologies.put(scopeId, new TreeSet<OWLOntologyID>());
                IRI core_ur = null, custom_ur = null;
                RDFTerm r;
                // Check core space
                Iterator<Triple> it2 = meta.filter(sub, HAS_SPACE_CORE_URIREF, null);
                if (it2.hasNext()) {
                    r = it2.next().getObject();
                    if (r instanceof IRI)
                        core_ur = (IRI) r;
                } else {
                    it2 = meta.filter(null, IS_SPACE_CORE_OF_URIREF, sub);
                    if (it2.hasNext()) {
                        r = it2.next().getSubject();
                        if (r instanceof IRI)
                            core_ur = (IRI) r;
                    }
                }
                // Check custom space
                it2 = meta.filter(sub, HAS_SPACE_CUSTOM_URIREF, null);
                if (it2.hasNext()) {
                    r = it2.next().getObject();
                    if (r instanceof IRI)
                        custom_ur = (IRI) r;
                } else {
                    it2 = meta.filter(null, IS_SPACE_CUSTOM_OF_URIREF, sub);
                    if (it2.hasNext()) {
                        r = it2.next().getSubject();
                        if (r instanceof IRI)
                            custom_ur = (IRI) r;
                    }
                }
                // retrieve the ontologies
                if (core_ur != null) {
                    for (it2 = meta.filter(core_ur, null, null); it2.hasNext(); ) {
                        Triple t = it2.next();
                        IRI predicate = t.getPredicate();
                        if (predicate.equals(MANAGES_URIREF)) {
                            if (t.getObject() instanceof IRI)
                                coreOntologies.get(scopeId).add(// FIXME must be very
                                keymap.buildPublicKey((IRI) t.getObject()));
                        }
                    }
                    for (it2 = meta.filter(null, null, core_ur); it2.hasNext(); ) {
                        Triple t = it2.next();
                        IRI predicate = t.getPredicate();
                        if (predicate.equals(IS_MANAGED_BY_URIREF)) {
                            if (t.getSubject() instanceof IRI)
                                coreOntologies.get(scopeId).add(// FIXME must be very
                                keymap.buildPublicKey((IRI) t.getSubject()));
                        }
                    }
                }
                if (custom_ur != null) {
                    for (it2 = meta.filter(custom_ur, null, null); it2.hasNext(); ) {
                        Triple t = it2.next();
                        IRI predicate = t.getPredicate();
                        if (predicate.equals(MANAGES_URIREF)) {
                            if (t.getObject() instanceof IRI)
                                customOntologies.get(scopeId).add(// FIXME must be very
                                keymap.buildPublicKey((IRI) t.getObject()));
                        }
                    }
                    for (it2 = meta.filter(null, null, custom_ur); it2.hasNext(); ) {
                        Triple t = it2.next();
                        IRI predicate = t.getPredicate();
                        if (predicate.equals(IS_MANAGED_BY_URIREF)) {
                            if (t.getSubject() instanceof IRI)
                                customOntologies.get(scopeId).add(// FIXME must be very
                                keymap.buildPublicKey((IRI) t.getSubject()));
                        }
                    }
                }
            }
        }
    }
    // Sessions next
    Map<String, Collection<OWLOntologyID>> sessionOntologies = new HashMap<String, Collection<OWLOntologyID>>();
    for (Iterator<Triple> it = meta.filter(null, RDF.type, SESSION_URIREF); it.hasNext(); ) {
        // for each
        // scope
        Triple ta = it.next();
        BlankNodeOrIRI sub = ta.getSubject();
        if (sub instanceof IRI) {
            IRI ses_ur = (IRI) sub;
            String s = ((IRI) sub).getUnicodeString();
            String prefix = _NS_STANBOL_INTERNAL + Session.shortName + "/";
            if (s.startsWith(prefix)) {
                String sessionId = s.substring(prefix.length());
                log.info("Rebuilding session \"{}\".", sessionId);
                sessionOntologies.put(sessionId, new TreeSet<OWLOntologyID>());
                attachedScopes.put(sessionId, new TreeSet<String>());
                // retrieve the ontologies
                if (ses_ur != null) {
                    for (Iterator<Triple> it2 = meta.filter(ses_ur, MANAGES_URIREF, null); it2.hasNext(); ) {
                        RDFTerm obj = it2.next().getObject();
                        if (obj instanceof IRI)
                            sessionOntologies.get(sessionId).add(// FIXME must be very temporary!
                            keymap.buildPublicKey((IRI) obj));
                    }
                    for (Iterator<Triple> it2 = meta.filter(null, IS_MANAGED_BY_URIREF, ses_ur); it2.hasNext(); ) {
                        RDFTerm subj = it2.next().getSubject();
                        if (subj instanceof IRI)
                            sessionOntologies.get(sessionId).add(// FIXME must be very temporary!
                            keymap.buildPublicKey((IRI) subj));
                    }
                    for (Iterator<Triple> it2 = meta.filter(null, APPENDED_TO_URIREF, ses_ur); it2.hasNext(); ) {
                        RDFTerm subj = it2.next().getSubject();
                        if (subj instanceof IRI) {
                            String s1 = ((IRI) subj).getUnicodeString();
                            String prefix1 = _NS_STANBOL_INTERNAL + Scope.shortName + "/";
                            if (s1.startsWith(prefix1)) {
                                String scopeId = s1.substring(prefix1.length());
                                attachedScopes.get(sessionId).add(scopeId);
                            }
                        }
                    }
                    for (Iterator<Triple> it2 = meta.filter(ses_ur, HAS_APPENDED_URIREF, null); it2.hasNext(); ) {
                        RDFTerm obj = it2.next().getObject();
                        if (obj instanceof IRI) {
                            String s1 = ((IRI) obj).getUnicodeString();
                            String prefix1 = _NS_STANBOL_INTERNAL + Scope.shortName + "/";
                            if (s1.startsWith(prefix1)) {
                                String scopeId = s1.substring(prefix1.length());
                                attachedScopes.get(sessionId).add(scopeId);
                            }
                        }
                    }
                }
            }
        }
    }
    return new OntologyNetworkConfiguration(coreOntologies, customOntologies, sessionOntologies, attachedScopes);
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) HashMap(java.util.HashMap) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm) OntologyNetworkConfiguration(org.apache.stanbol.ontologymanager.ontonet.api.OntologyNetworkConfiguration) Triple(org.apache.clerezza.commons.rdf.Triple) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) Graph(org.apache.clerezza.commons.rdf.Graph) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) Collection(java.util.Collection)

Example 64 with Graph

use of org.apache.clerezza.commons.rdf.Graph 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 65 with Graph

use of org.apache.clerezza.commons.rdf.Graph in project stanbol by apache.

the class ClerezzaOntologyProvider method loadInStore.

@Override
public OWLOntologyID loadInStore(InputStream data, String formatIdentifier, boolean force, Origin<?>... references) {
    if (data == null)
        throw new IllegalArgumentException("No data to load ontologies from.");
    if (formatIdentifier == null || formatIdentifier.trim().isEmpty())
        throw new IllegalArgumentException("A non-null, non-blank format identifier is required for parsing the data stream.");
    checkReplaceability(references);
    // This method only tries the supplied format once.
    log.debug("Trying to parse data stream with format {}", formatIdentifier);
    Graph rdfData = parser.parse(data, formatIdentifier);
    log.debug("SUCCESS format {}.", formatIdentifier);
    return loadInStore(rdfData, force, references);
}
Also used : IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) Graph(org.apache.clerezza.commons.rdf.Graph)

Aggregations

Graph (org.apache.clerezza.commons.rdf.Graph)172 IRI (org.apache.clerezza.commons.rdf.IRI)110 TripleImpl (org.apache.clerezza.commons.rdf.impl.utils.TripleImpl)66 SimpleGraph (org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph)57 Triple (org.apache.clerezza.commons.rdf.Triple)45 IndexedGraph (org.apache.stanbol.commons.indexedgraph.IndexedGraph)43 Test (org.junit.Test)38 BlankNodeOrIRI (org.apache.clerezza.commons.rdf.BlankNodeOrIRI)36 PlainLiteralImpl (org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl)34 IOException (java.io.IOException)27 ImmutableGraph (org.apache.clerezza.commons.rdf.ImmutableGraph)26 HashSet (java.util.HashSet)24 RDFTerm (org.apache.clerezza.commons.rdf.RDFTerm)24 EngineException (org.apache.stanbol.enhancer.servicesapi.EngineException)24 InputStream (java.io.InputStream)21 HashMap (java.util.HashMap)20 Language (org.apache.clerezza.commons.rdf.Language)17 Blob (org.apache.stanbol.enhancer.servicesapi.Blob)17 ArrayList (java.util.ArrayList)16 LiteralFactory (org.apache.clerezza.rdf.core.LiteralFactory)15