You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stanbol.apache.org by al...@apache.org on 2012/06/20 11:42:27 UTC

svn commit: r1352018 [2/3] - in /incubator/stanbol/trunk: commons/owl/src/main/java/org/apache/stanbol/commons/owl/util/ commons/owl/src/test/java/org/apache/stanbol/commons/owl/util/ commons/owl/src/test/java/org/apache/stanbol/owl/ ontologymanager/on...

Modified: incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/ClerezzaOntologyProvider.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/ClerezzaOntologyProvider.java?rev=1352018&r1=1352017&r2=1352018&view=diff
==============================================================================
--- incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/ClerezzaOntologyProvider.java (original)
+++ incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/ClerezzaOntologyProvider.java Wed Jun 20 09:42:24 2012
@@ -16,6 +16,13 @@
  */
 package org.apache.stanbol.ontologymanager.ontonet.impl.clerezza;
 
+import static org.apache.stanbol.ontologymanager.ontonet.api.Vocabulary.IS_MANAGED_BY_CORE;
+import static org.apache.stanbol.ontologymanager.ontonet.api.Vocabulary.IS_MANAGED_BY_CUSTOM;
+import static org.apache.stanbol.ontologymanager.ontonet.api.Vocabulary.MANAGES_IN_CORE;
+import static org.apache.stanbol.ontologymanager.ontonet.api.Vocabulary.MANAGES_IN_CUSTOM;
+import static org.apache.stanbol.ontologymanager.ontonet.api.Vocabulary.SCOPE;
+import static org.apache.stanbol.ontologymanager.ontonet.api.Vocabulary._NS_ONTONET;
+
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.URLConnection;
@@ -30,6 +37,8 @@ import java.util.List;
 import java.util.Set;
 import java.util.Stack;
 
+import org.apache.clerezza.rdf.core.Literal;
+import org.apache.clerezza.rdf.core.LiteralFactory;
 import org.apache.clerezza.rdf.core.MGraph;
 import org.apache.clerezza.rdf.core.NonLiteral;
 import org.apache.clerezza.rdf.core.Resource;
@@ -63,7 +72,14 @@ import org.apache.stanbol.commons.owl.ut
 import org.apache.stanbol.commons.stanboltools.offline.OfflineMode;
 import org.apache.stanbol.ontologymanager.ontonet.api.OfflineConfiguration;
 import org.apache.stanbol.ontologymanager.ontonet.api.collector.ImportManagementPolicy;
+import org.apache.stanbol.ontologymanager.ontonet.api.collector.OntologyCollector;
+import org.apache.stanbol.ontologymanager.ontonet.api.collector.OntologyCollectorListener;
 import org.apache.stanbol.ontologymanager.ontonet.api.ontology.OntologyProvider;
+import org.apache.stanbol.ontologymanager.ontonet.api.scope.CoreOntologySpace;
+import org.apache.stanbol.ontologymanager.ontonet.api.scope.CustomOntologySpace;
+import org.apache.stanbol.ontologymanager.ontonet.api.scope.OntologyScope;
+import org.apache.stanbol.ontologymanager.ontonet.api.scope.ScopeEventListener;
+import org.apache.stanbol.ontologymanager.ontonet.api.session.Session;
 import org.apache.stanbol.ontologymanager.ontonet.impl.util.OntologyUtils;
 import org.osgi.service.component.ComponentContext;
 import org.semanticweb.owlapi.apibinding.OWLManager;
@@ -88,7 +104,26 @@ import org.slf4j.LoggerFactory;
  */
 @Component(immediate = true, metatype = true)
 @Service(OntologyProvider.class)
-public class ClerezzaOntologyProvider implements OntologyProvider<TcProvider> {
+public class ClerezzaOntologyProvider implements OntologyProvider<TcProvider>, ScopeEventListener,
+        OntologyCollectorListener {
+
+    private class InvalidMetaGraphStateException extends RuntimeException {
+
+        /**
+         * 
+         */
+        private static final long serialVersionUID = 3915817349833358738L;
+
+        @SuppressWarnings("unused")
+        InvalidMetaGraphStateException() {
+            super();
+        }
+
+        InvalidMetaGraphStateException(String message) {
+            super(message);
+        }
+
+    }
 
     /**
      * Internally, the Clerezza ontology provider uses a reserved graph to store the associations between
@@ -108,15 +143,15 @@ public class ClerezzaOntologyProvider im
          */
         private class Vocabulary {
 
-            static final String _BASE_VOCAB = "http://stanbol.apache.org/ontology/ontonet/meta#";
+            static final String ENTRY = _NS_ONTONET + "Entry";
 
-            static final String ENTRY = _BASE_VOCAB + "Entry";
+            static final String HAS_ONTOLOGY_IRI = _NS_ONTONET + "hasOntologyIRI";
 
-            static final String HAS_ONTOLOGY_IRI = _BASE_VOCAB + "hasOntologyIRI";
+            static final String HAS_VERSION_IRI = _NS_ONTONET + "hasVersionIRI";
 
-            static final String HAS_VERSION_IRI = _BASE_VOCAB + "hasVersionIRI";
+            static final String MAPS_TO_GRAPH = _NS_ONTONET + "mapsToGraph";
 
-            static final String MAPS_TO_GRAPH = _BASE_VOCAB + "mapsToGraph";
+            static final String RETRIEVED_FROM = _NS_ONTONET + "retrievedFrom";
 
         }
 
@@ -183,12 +218,12 @@ public class ClerezzaOntologyProvider im
          * @param ontologyReference
          * @return
          */
-        private UriRef buildResource(OWLOntologyID ontologyReference) {
-            // The UriRef is of the form ontologyIRI[/versionIRI] (TODO use something less conventional?)
+        UriRef buildResource(OWLOntologyID ontologyReference) {
+            // The UriRef is of the form ontologyIRI[:::versionIRI] (TODO use something less conventional?)
             IRI ontologyIRI = ontologyReference.getOntologyIRI(), versionIri = ontologyReference
                     .getVersionIRI();
             UriRef entry = new UriRef(ontologyIRI.toString()
-                                      + ((versionIri == null) ? "" : ("/" + versionIri.toString())));
+                                      + ((versionIri == null) ? "" : (":::" + versionIri.toString())));
             return entry;
         }
 
@@ -216,6 +251,25 @@ public class ClerezzaOntologyProvider im
             return result;
         }
 
+        void mapLocator(IRI locator, UriRef graphName) {
+            if (graphName == null) throw new IllegalArgumentException("A null graph name is not allowed.");
+            // Null locator is a legal argument, will remove all locator mappings from the supplied graph
+            UriRef retrieved_from = new UriRef(Vocabulary.RETRIEVED_FROM);
+            boolean isOntology = true;
+            Set<Triple> remove = new HashSet<Triple>();
+            for (Iterator<Triple> nodes = graph.filter(graphName, null, null); nodes.hasNext();) {
+                Triple t = nodes.next();
+                // isOntology |= RDF.type.equals(t.getPredicate()) && OWL.Ontology.equals(t.getObject());
+                if (retrieved_from.equals(t.getPredicate())) remove.add(t);
+            }
+            graph.removeAll(remove);
+            if (locator != null) {
+                Literal litloc = LiteralFactory.getInstance().createTypedLiteral(
+                    new UriRef(locator.toString()));
+                graph.add(new TripleImpl(graphName, retrieved_from, litloc));
+            }
+        }
+
         void removeMapping(OWLOntologyID ontologyReference) {
             Iterator<Triple> it = graph.filter(buildResource(ontologyReference), new UriRef(
                     Vocabulary.MAPS_TO_GRAPH), null);
@@ -463,8 +517,13 @@ public class ClerezzaOntologyProvider im
     @Override
     public String getKey(IRI ontologyIri) {
         ontologyIri = URIUtils.sanitizeID(ontologyIri);
-        UriRef ur = keymap.getMapping(new OWLOntologyID(ontologyIri));
-        log.debug("key for {} is {}", ontologyIri, ur);
+        return getKey(new OWLOntologyID(ontologyIri));
+    }
+
+    @Override
+    public String getKey(OWLOntologyID ontologyId) {
+        UriRef ur = keymap.getMapping(ontologyId);
+        log.debug("key for {} is {}", ontologyId, ur);
         return (ur == null) ? null : ur.getUnicodeString();
     }
 
@@ -482,6 +541,12 @@ public class ClerezzaOntologyProvider im
     }
 
     @Override
+    public Set<String> getOntologyVersionKeys(IRI ontologyIRI) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
     public TcProvider getStore() {
         return store;
     }
@@ -579,7 +644,7 @@ public class ClerezzaOntologyProvider im
     }
 
     @Override
-    public String loadInStore(InputStream data, String formatIdentifier, String preferredKey, boolean force) {
+    public String loadInStore(InputStream data, String formatIdentifier, boolean force) {
 
         if (data == null) throw new IllegalArgumentException("No data to load ontologies from.");
 
@@ -595,7 +660,7 @@ public class ClerezzaOntologyProvider im
         for (String format : formats) {
             try {
                 TripleCollection rdfData = parser.parse(data, format);
-                return loadInStore(rdfData, preferredKey, force);
+                return loadInStore(rdfData, force);
             } catch (UnsupportedFormatException e) {
                 log.debug("Unsupported format format {}. Trying next one.", format);
                 continue;
@@ -610,10 +675,7 @@ public class ClerezzaOntologyProvider im
     }
 
     @Override
-    public String loadInStore(final IRI ontologyIri,
-                              String formatIdentifier,
-                              String preferredKey,
-                              boolean force) throws IOException {
+    public String loadInStore(final IRI ontologyIri, String formatIdentifier, boolean force) throws IOException {
         log.debug("Loading {}", ontologyIri);
         if (ontologyIri == null) throw new IllegalArgumentException("Ontology IRI cannot be null.");
 
@@ -647,7 +709,10 @@ public class ClerezzaOntologyProvider im
                      * formats again. Also, we provide the ontologyIRI as the preferred key, since we already
                      * know it.
                      */
-                    return loadInStore(is, currentFormat, ontologyIri.toString(), force);
+                    String key = loadInStore(is, currentFormat, force);
+                    // If parsing failed, an exception will be thrown before getting here, so no risk.
+                    if (key != null && !key.isEmpty()) setLocatorMapping(ontologyIri, key);
+                    return key;
                 }
             } catch (UnsupportedFormatException e) {
                 log.debug("Unsupported format format {}. Trying next one.", currentFormat);
@@ -664,7 +729,7 @@ public class ClerezzaOntologyProvider im
     }
 
     @Override
-    public String loadInStore(Object ontology, String preferredKey, boolean force) {
+    public String loadInStore(Object ontology, boolean force) {
 
         if (ontology == null) throw new IllegalArgumentException("No ontology supplied.");
 
@@ -689,18 +754,19 @@ public class ClerezzaOntologyProvider im
         // FIXME Profile this method. Are we getting rid of rdfData after adding its triples?
 
         // preferredKey should be the "guessed" ontology id
-        String iri = preferredKey;
-        OWLOntologyID realId = OWLUtils.guessOWLOntologyID(rdfData);
+        String iri = null;
+        OWLOntologyID realId = OWLUtils.guessOntologyIdentifier(rdfData);
 
         // String alternateId = OWLUtils.guessOntologyIdentifier(rdfData).getUnicodeString();
         if ((iri == null || iri.isEmpty()) && realId != null) {
             if (realId.getOntologyIRI() != null) iri = realId.getOntologyIRI().toString();
             if (realId.getVersionIRI() != null) iri += ":::" + realId.getVersionIRI().toString();
-        } else try {
-            new UriRef(iri); // Can I make a UriRef from it?
-        } catch (Exception ex) {
-            iri = OWLUtils.guessOntologyIdentifier(rdfData).getUnicodeString();
         }
+        // else try {
+        // new UriRef(iri); // Can I make a UriRef from it?
+        // } catch (Exception ex) {
+        // iri = OWLUtils.guessOntologyIdentifier(rdfData).getUnicodeString();
+        // }
 
         ontologyIri = IRI.create(iri);
         while (s.endsWith("#"))
@@ -741,7 +807,11 @@ public class ClerezzaOntologyProvider im
                 while (it2.hasNext()) {
                     Resource obj = it2.next().getObject();
                     if (obj instanceof UriRef) try {
-                        loadInStore(IRI.create(((UriRef) obj).getUnicodeString()), null, null, false);
+                        // TODO try locals first
+                        if (isOfflineMode()) throw new RuntimeException(
+                                "Camnnot load imported ontology " + obj
+                                        + " while Stanbol is in offline mode.");
+                        else loadInStore(IRI.create(((UriRef) obj).getUnicodeString()), null, false);
                     } catch (UnsupportedFormatException e) {
                         log.warn("Failed to parse format for resource " + obj, e);
                     } catch (IOException e) {
@@ -789,11 +859,87 @@ public class ClerezzaOntologyProvider im
     }
 
     @Override
+    public void scopeActivated(OntologyScope scope) {}
+
+    @Override
+    public void scopeCreated(OntologyScope scope) {}
+
+    @Override
+    public void scopeDeactivated(OntologyScope scope) {}
+
+    @Override
+    public void scopeDeregistered(OntologyScope scope) {
+        UriRef graphId = new UriRef(metaGraphId);
+        MGraph graph = store.getMGraph(graphId);
+        if (graph == null) try {
+            graph = store.createMGraph(graphId);
+        } catch (EntityAlreadyExistsException e) {
+            log.error("Could not get meta graph {} for writing scope registration. ", graphId);
+        }
+        boolean removable = false, conflict = false;
+        UriRef sid = new UriRef(scope.getNamespace() + scope.getID());
+        Set<Triple> removeUs = new HashSet<Triple>();
+        for (Iterator<Triple> it = graph.filter(sid, null, null); it.hasNext();) {
+            Triple t = it.next();
+            if (RDF.type.equals(t.getPredicate())) {
+                if (new UriRef(SCOPE).equals(t.getObject())) removable = true;
+                else conflict = true;
+            }
+            removeUs.add(t);
+        }
+        for (Iterator<Triple> it = graph.filter(null, null, sid); it.hasNext();)
+            removeUs.add(it.next());
+        if (!removable) log
+                .error(
+                    "Cannot write scope deregistration to persistence: resource {} is not typed as a {} in the meta-graph.",
+                    sid, SCOPE);
+        else if (conflict) log.error(
+            "Conflict upon scope deregistration: resource {} has incompatible types in the meta-graph.", sid,
+            SCOPE);
+        else {
+            log.info("Removing all triples for {}", sid);
+            graph.removeAll(removeUs);
+        }
+    }
+
+    @Override
+    public void scopeRegistered(OntologyScope scope) {
+        UriRef graphId = new UriRef(metaGraphId);
+        MGraph graph = store.getMGraph(graphId);
+        if (graph == null) try {
+            graph = store.createMGraph(graphId);
+        } catch (EntityAlreadyExistsException e) {
+            log.error("Could not get meta graph {} for writing scope registration. ", graphId);
+        }
+        Triple t = new TripleImpl(new UriRef(scope.getNamespace() + scope.getID()), RDF.type, new UriRef(
+                SCOPE));
+        if (graph.contains(t)) log.info("Not adding triple {}", t);
+        else {
+            log.info("Adding triple {}", t);
+            graph.add(t);
+        }
+    }
+
+    @Override
     public void setImportManagementPolicy(ImportManagementPolicy policy) {
         if (policy == null) throw new IllegalArgumentException("Import management policy cannot be null.");
         importPolicyString = policy.toString();
     }
 
+    @Override
+    public void setLocatorMapping(IRI locator, String key) {
+        if (key == null || key.isEmpty()) throw new IllegalArgumentException(
+                "key must be non-null and non-empty.");
+        if (!store.listTripleCollections().contains(new UriRef(key))) throw new IllegalArgumentException(
+                "No ontology found with storage key " + key);
+        if (locator == null) log
+                .warn(
+                    "Setting null locator for {}. This will remove all physical mappings for the corresponding graph.",
+                    key);
+        else log.info("Setting {} as the resource locator for ontology {}", locator, key);
+        keymap.mapLocator(locator, new UriRef(key));
+    }
+
     /**
      * 
      * @param graphName
@@ -902,4 +1048,120 @@ public class ClerezzaOntologyProvider im
         }
     }
 
+    @Override
+    public void onOntologyAdded(OntologyCollector collector, OWLOntologyID addedOntology) {
+
+        // When the ontology provider hears an ontology has been added to a collector, it has to register this
+        // into the metadata graph.
+
+        // log.info("Heard addition of ontology {} to collector {}", addedOntology, collector.getID());
+        // log.info("This ontology is stored as {}", getKey(addedOntology));
+        UriRef c = new UriRef(collector.getNamespace() + collector.getID());
+        UriRef u = keymap.buildResource(addedOntology);
+
+        // TODO OntologyProvider should not be aware of scopes, spaces or sessions. Move elsewhere.
+        MGraph meta = getMetaGraph(MGraph.class);
+        String sMan = "";
+        for (Iterator<Triple> it = meta.filter(u, new UriRef(IS_MANAGED_BY_CUSTOM), null); it.hasNext();)
+            sMan += it.next() + ", ";
+        for (Iterator<Triple> it = meta.filter(u, new UriRef(IS_MANAGED_BY_CORE), null); it.hasNext();)
+            sMan += it.next() + ", ";
+        for (Iterator<Triple> it = meta.filter(null, new UriRef(MANAGES_IN_CUSTOM), u); it.hasNext();)
+            sMan += it.next() + "(inverse), ";
+        for (Iterator<Triple> it = meta.filter(null, new UriRef(MANAGES_IN_CORE), u); it.hasNext();)
+            sMan += it.next() + "(inverse), ";
+        if (!sMan.isEmpty()) log.warn("Ontology {} is already managed by the following collectors : " + sMan,
+            addedOntology);
+
+        // Add both inverse triples. This graph has to be traversed efficiently, no need for reasoners.
+        UriRef predicate1 = null, predicate2 = null;
+        if (collector instanceof CoreOntologySpace) {
+            predicate1 = new UriRef(MANAGES_IN_CORE);
+            predicate2 = new UriRef(IS_MANAGED_BY_CORE);
+        } else if (collector instanceof CustomOntologySpace) {
+            predicate1 = new UriRef(MANAGES_IN_CUSTOM);
+            predicate2 = new UriRef(IS_MANAGED_BY_CUSTOM);
+        } else if (collector instanceof Session) {
+            // TODO implement model for sessions.
+        }
+        synchronized (meta) {
+            Triple t;
+            if (predicate1 != null) {
+                t = new TripleImpl(c, predicate1, u);
+                boolean b = meta.add(t);
+                log.debug((b ? "Successful" : "Redundant") + " addition of meta triple {} ", t);
+            }
+            if (predicate2 != null) {
+                t = new TripleImpl(u, predicate2, c);
+                boolean b = meta.add(t);
+                log.debug((b ? "Successful" : "Redundant") + " addition of meta triple {} ", t);
+            }
+        }
+    }
+
+    @Override
+    public void onOntologyRemoved(OntologyCollector collector, OWLOntologyID removedOntology) {
+        log.info("Heard removal of ontology {} from collector {}", removedOntology, collector.getID());
+
+        UriRef c = new UriRef(collector.getNamespace() + collector.getID());
+        UriRef u = keymap.buildResource(removedOntology);
+
+        // XXX condense the following code
+        MGraph meta = getMetaGraph(MGraph.class);
+        boolean badState = true;
+
+        log.debug("Checking ({},{}) pattern", c, u);
+
+        for (Iterator<Triple> it = meta.filter(c, null, u); it.hasNext();) {
+            UriRef property = it.next().getPredicate();
+
+            if (collector instanceof CoreOntologySpace) {
+                if (property.equals(new UriRef(MANAGES_IN_CORE))) badState = false;
+                if (property.equals(new UriRef(MANAGES_IN_CUSTOM))) log
+                        .warn("Ontology {} is still managed by custom space {}. "
+                              + "Removal from core space might alter axiom interpretation within the scope.");
+            }
+
+            if (collector instanceof CustomOntologySpace) {
+                if (property.equals(new UriRef(MANAGES_IN_CORE))) log
+                        .warn("Ontology {} is still managed by core space {}. "
+                              + "Removal from the custom space will most likely have no effect on the scope.");
+                if (property.equals(new UriRef(MANAGES_IN_CUSTOM))) badState = false;
+            }
+        }
+
+        log.debug("Checking ({},{}) pattern", u, c);
+
+        for (Iterator<Triple> it = meta.filter(u, null, c); it.hasNext();) {
+            UriRef property = it.next().getPredicate();
+
+            if (collector instanceof CoreOntologySpace) {
+                if (property.equals(new UriRef(IS_MANAGED_BY_CORE))) badState = false;
+                if (property.equals(new UriRef(IS_MANAGED_BY_CUSTOM))) log
+                        .warn("Ontology {} is still managed by custom space {}. "
+                              + "Removal from core space might alter axiom interpretation within the scope.");
+            }
+
+            if (collector instanceof CustomOntologySpace) {
+                if (property.equals(new UriRef(IS_MANAGED_BY_CORE))) log
+                        .warn("Ontology {} is still managed by core space {}. "
+                              + "Removal from the custom space will most likely have no effect on the scope.");
+                if (property.equals(new UriRef(IS_MANAGED_BY_CUSTOM))) badState = false;
+            }
+        }
+
+        if (badState) throw new InvalidMetaGraphStateException(
+                "No relationship found for ontology-collector pair {" + u + " , " + c + "}");
+
+        synchronized (meta) {
+            if (collector instanceof CoreOntologySpace) {
+                meta.remove(new TripleImpl(c, new UriRef(MANAGES_IN_CORE), u));
+                meta.remove(new TripleImpl(u, new UriRef(IS_MANAGED_BY_CORE), c));
+            } else if (collector instanceof CustomOntologySpace) {
+                meta.remove(new TripleImpl(c, new UriRef(MANAGES_IN_CUSTOM), u));
+                meta.remove(new TripleImpl(u, new UriRef(IS_MANAGED_BY_CUSTOM), c));
+            }
+        }
+    }
+
 }

Modified: incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/CustomOntologySpaceImpl.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/CustomOntologySpaceImpl.java?rev=1352018&r1=1352017&r2=1352018&view=diff
==============================================================================
--- incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/CustomOntologySpaceImpl.java (original)
+++ incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/CustomOntologySpaceImpl.java Wed Jun 20 09:42:24 2012
@@ -16,9 +16,7 @@
  */
 package org.apache.stanbol.ontologymanager.ontonet.impl.clerezza;
 
-import org.apache.stanbol.ontologymanager.ontonet.api.collector.UnmodifiableOntologyCollectorException;
 import org.apache.stanbol.ontologymanager.ontonet.api.ontology.OntologyProvider;
-import org.apache.stanbol.ontologymanager.ontonet.api.scope.CoreOntologySpace;
 import org.apache.stanbol.ontologymanager.ontonet.api.scope.CustomOntologySpace;
 import org.semanticweb.owlapi.model.IRI;
 
@@ -40,11 +38,6 @@ public class CustomOntologySpaceImpl ext
         super(buildId(scopeID), namespace, SpaceType.CUSTOM, ontologyProvider);
     }
 
-    @Override
-    public void attachCoreSpace(CoreOntologySpace coreSpace, boolean skipRoot) throws UnmodifiableOntologyCollectorException {
-        // TODO deprecated, remove asap.
-    }
-
     /**
      * Once it is set up, a custom space is write-locked.
      */

Added: incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/OntologyLookaheadMGraph.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/OntologyLookaheadMGraph.java?rev=1352018&view=auto
==============================================================================
--- incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/OntologyLookaheadMGraph.java (added)
+++ incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/OntologyLookaheadMGraph.java Wed Jun 20 09:42:24 2012
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.stanbol.ontologymanager.ontonet.impl.clerezza;
+
+import java.util.Iterator;
+
+import org.apache.clerezza.rdf.core.NonLiteral;
+import org.apache.clerezza.rdf.core.Triple;
+import org.apache.clerezza.rdf.core.UriRef;
+import org.apache.clerezza.rdf.core.impl.SimpleMGraph;
+import org.apache.clerezza.rdf.ontologies.OWL;
+import org.apache.clerezza.rdf.ontologies.RDF;
+
+public class OntologyLookaheadMGraph extends SimpleMGraph {
+
+    private UriRef ontologyIRI = null;
+
+    @Override
+    public boolean performAdd(Triple t) {
+        boolean b = false;
+
+        // filter the interesting Triple
+        if (RDF.type.equals(t.getPredicate()) && OWL.Ontology.equals(t.getObject())) b = super.performAdd(t);
+
+        // check the currently available triples for the Ontology ID
+        checkOntologyId();
+
+        if (ontologyIRI != null) throw new RuntimeException(); // stop importing
+        // TODO: add an limit to the triples you read
+
+        return b;
+    }
+
+    public UriRef getOntologyIRI() {
+        return ontologyIRI;
+    }
+
+    private void checkOntologyId() {
+        for (Iterator<Triple> it = this.filter(null, RDF.type, OWL.Ontology); it.hasNext();) {
+            NonLiteral s = it.next().getSubject();
+            if (s instanceof UriRef) {
+                ontologyIRI = (UriRef) s;
+                break;
+            }
+        }
+    }
+
+}

Modified: incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/OntologySpaceFactoryImpl.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/OntologySpaceFactoryImpl.java?rev=1352018&r1=1352017&r2=1352018&view=diff
==============================================================================
--- incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/OntologySpaceFactoryImpl.java (original)
+++ incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/OntologySpaceFactoryImpl.java Wed Jun 20 09:42:24 2012
@@ -25,6 +25,7 @@ import org.apache.felix.scr.annotations.
 import org.apache.felix.scr.annotations.Deactivate;
 import org.apache.felix.scr.annotations.Reference;
 import org.apache.felix.scr.annotations.Service;
+import org.apache.stanbol.ontologymanager.ontonet.api.collector.OntologyCollectorListener;
 import org.apache.stanbol.ontologymanager.ontonet.api.collector.UnmodifiableOntologyCollectorException;
 import org.apache.stanbol.ontologymanager.ontonet.api.io.OntologyInputSource;
 import org.apache.stanbol.ontologymanager.ontonet.api.ontology.OntologyProvider;
@@ -107,6 +108,11 @@ public class OntologySpaceFactoryImpl im
         //
         // if (parentScope != null && parentScope instanceof OntologyCollectorListener) s
         // .addListener((OntologyCollectorListener) parentScope);
+
+        // Make sure the ontology provider listens to ontology additions before core ontologies are added.
+        if (ontologyProvider instanceof OntologyCollectorListener) s
+                .addOntologyCollectorListener((OntologyCollectorListener) ontologyProvider);
+
         // Set the supplied ontology's parent as the root for this space.
         if (ontologySources != null) try {
             for (OntologyInputSource<?,?> src : ontologySources)

Modified: incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/ontology/OntologyScopeImpl.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/ontology/OntologyScopeImpl.java?rev=1352018&r1=1352017&r2=1352018&view=diff
==============================================================================
--- incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/ontology/OntologyScopeImpl.java (original)
+++ incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/ontology/OntologyScopeImpl.java Wed Jun 20 09:42:24 2012
@@ -34,6 +34,7 @@ import org.apache.clerezza.rdf.core.impl
 import org.apache.clerezza.rdf.core.impl.TripleImpl;
 import org.apache.clerezza.rdf.ontologies.OWL;
 import org.apache.clerezza.rdf.ontologies.RDF;
+import org.apache.stanbol.ontologymanager.ontonet.api.collector.OntologyCollector;
 import org.apache.stanbol.ontologymanager.ontonet.api.collector.OntologyCollectorListener;
 import org.apache.stanbol.ontologymanager.ontonet.api.collector.UnmodifiableOntologyCollectorException;
 import org.apache.stanbol.ontologymanager.ontonet.api.io.OntologyInputSource;
@@ -42,7 +43,6 @@ import org.apache.stanbol.ontologymanage
 import org.apache.stanbol.ontologymanager.ontonet.api.scope.OntologyScope;
 import org.apache.stanbol.ontologymanager.ontonet.api.scope.OntologySpace;
 import org.apache.stanbol.ontologymanager.ontonet.api.scope.OntologySpaceFactory;
-import org.apache.stanbol.ontologymanager.ontonet.api.scope.ScopeOntologyListener;
 import org.semanticweb.owlapi.apibinding.OWLManager;
 import org.semanticweb.owlapi.model.AddImport;
 import org.semanticweb.owlapi.model.IRI;
@@ -50,6 +50,7 @@ import org.semanticweb.owlapi.model.OWLD
 import org.semanticweb.owlapi.model.OWLOntology;
 import org.semanticweb.owlapi.model.OWLOntologyChange;
 import org.semanticweb.owlapi.model.OWLOntologyCreationException;
+import org.semanticweb.owlapi.model.OWLOntologyID;
 import org.semanticweb.owlapi.model.OWLOntologyManager;
 import org.semanticweb.owlapi.model.OWLOntologySetProvider;
 import org.semanticweb.owlapi.util.OWLOntologyMerger;
@@ -80,7 +81,7 @@ public class OntologyScopeImpl implement
      */
     protected String id = null;
 
-    private Set<ScopeOntologyListener> listeners = new HashSet<ScopeOntologyListener>();
+    private Set<OntologyCollectorListener> listeners = new HashSet<OntologyCollectorListener>();
 
     /**
      * An ontology scope knows whether it's write-locked or not. Initially it is not.
@@ -98,32 +99,33 @@ public class OntologyScopeImpl implement
         setID(id);
         setNamespace(namespace);
 
-        this.coreSpace = factory.createCoreOntologySpace(id, coreOntologies);
-        this.coreSpace.addListener(this);
+        this.coreSpace = factory.createCoreOntologySpace(id/* , coreOntologies */);
+        this.coreSpace.addOntologyCollectorListener(this); // Set listener before adding core ontologies
+        for (OntologyInputSource<?,?> src : coreOntologies)
+            this.coreSpace.addOntology(src);
         // let's just lock it. Once the core space is done it's done.
         this.coreSpace.setUp();
 
         try {
-            setCustomSpace(factory.createCustomOntologySpace(id/* , coreOntologies */));
+            setCustomSpace(factory.createCustomOntologySpace(id));
         } catch (UnmodifiableOntologyCollectorException e) {
-            // Cannot happen unless the factory or space implementations are
-            // really naughty.
+            // Cannot happen unless the factory or space implementations are really naughty.
             log.warn(
                 "Ontology scope "
                         + id
                         + " was denied creation of its own custom space upon initialization! This should not happen.",
                 e);
         }
-        this.customSpace.addListener(this);
+        this.customSpace.addOntologyCollectorListener(this);
     }
 
     @Override
-    public void addOntologyScopeListener(ScopeOntologyListener listener) {
+    public void addOntologyCollectorListener(OntologyCollectorListener listener) {
         listeners.add(listener);
     }
 
     @Override
-    public void clearOntologyScopeListeners() {
+    public void clearOntologyCollectorListeners() {
         listeners.clear();
     }
 
@@ -284,14 +286,14 @@ public class OntologyScopeImpl implement
         return ont;
     }
 
-    protected void fireOntologyAdded(IRI ontologyIri) {
-        for (ScopeOntologyListener listener : listeners)
-            listener.onOntologyAdded(this.getID(), ontologyIri);
+    protected void fireOntologyAdded(OntologySpace space, OWLOntologyID addedOntology) {
+        for (OntologyCollectorListener listener : listeners)
+            listener.onOntologyAdded(space, addedOntology);
     }
 
-    protected void fireOntologyRemoved(IRI ontologyIri) {
-        for (ScopeOntologyListener listener : listeners)
-            listener.onOntologyRemoved(this.getID(), ontologyIri);
+    protected void fireOntologyRemoved(OntologySpace space, OWLOntologyID removedOntology) {
+        for (OntologyCollectorListener listener : listeners)
+            listener.onOntologyRemoved(space, removedOntology);
     }
 
     @Override
@@ -320,7 +322,7 @@ public class OntologyScopeImpl implement
     }
 
     @Override
-    public Collection<ScopeOntologyListener> getOntologyScopeListeners() {
+    public Collection<OntologyCollectorListener> getOntologyCollectorListeners() {
         return listeners;
     }
 
@@ -330,19 +332,20 @@ public class OntologyScopeImpl implement
     }
 
     @Override
-    public void onOntologyAdded(String collectorId, IRI addedOntology) {
+    public void onOntologyAdded(OntologyCollector collector, OWLOntologyID addedOntology) {
         // Propagate events to scope listeners
-        fireOntologyAdded(addedOntology);
+        if (collector instanceof OntologySpace) fireOntologyAdded((OntologySpace) collector, addedOntology);
     }
 
     @Override
-    public void onOntologyRemoved(String collectorId, IRI removedOntology) {
+    public void onOntologyRemoved(OntologyCollector collector, OWLOntologyID removedOntology) {
         // Propagate events to scope listeners
-        fireOntologyRemoved(removedOntology);
+        if (collector instanceof OntologySpace) fireOntologyRemoved((OntologySpace) collector,
+            removedOntology);
     }
 
     @Override
-    public void removeOntologyScopeListener(ScopeOntologyListener listener) {
+    public void removeOntologyCollectorListener(OntologyCollectorListener listener) {
         listeners.remove(listener);
     }
 
@@ -354,7 +357,7 @@ public class OntologyScopeImpl implement
                 "supplied object is not a CustomOntologySpace instance.");
         else {
             this.customSpace = (CustomOntologySpace) customSpace;
-            this.customSpace.addListener(this);
+            this.customSpace.addOntologyCollectorListener(this);
         }
     }
 
@@ -397,10 +400,10 @@ public class OntologyScopeImpl implement
     @Override
     public synchronized void setUp() {
         if (locked || (customSpace != null && !customSpace.isLocked())) return;
-        this.coreSpace.addListener(this);
+        this.coreSpace.addOntologyCollectorListener(this);
         this.coreSpace.setUp();
         if (this.customSpace != null) {
-            this.customSpace.addListener(this);
+            this.customSpace.addOntologyCollectorListener(this);
             this.customSpace.setUp();
         }
         locked = true;

Modified: incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/ontology/ScopeRegistryImpl.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/ontology/ScopeRegistryImpl.java?rev=1352018&r1=1352017&r2=1352018&view=diff
==============================================================================
--- incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/ontology/ScopeRegistryImpl.java (original)
+++ incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/ontology/ScopeRegistryImpl.java Wed Jun 20 09:42:24 2012
@@ -34,28 +34,26 @@ import org.apache.stanbol.ontologymanage
  */
 public class ScopeRegistryImpl implements ScopeRegistry {
 
-    private Set<String> activeScopeIRIs;
+    protected Set<String> activeScopeIRIs;
 
-    private Set<ScopeEventListener> scopeListeners;
+    protected Set<ScopeEventListener> listeners;
 
-    private Map<String,OntologyScope> scopeMap;
+    protected Map<String,OntologyScope> scopeMap;
 
     public ScopeRegistryImpl() {
         scopeMap = new HashMap<String,OntologyScope>();
         activeScopeIRIs = new HashSet<String>();
-        scopeListeners = new HashSet<ScopeEventListener>();
+        listeners = new HashSet<ScopeEventListener>();
     }
 
     @Override
     public void addScopeRegistrationListener(ScopeEventListener listener) {
-        scopeListeners.add(listener);
-
+        listeners.add(listener);
     }
 
     @Override
     public void clearScopeRegistrationListeners() {
-        scopeListeners.clear();
-
+        listeners.clear();
     }
 
     @Override
@@ -77,9 +75,9 @@ public class ScopeRegistryImpl implement
 
     protected void fireScopeActivationChange(String scopeID, boolean activated) {
         OntologyScope scope = scopeMap.get(scopeID);
-        if (activated) for (ScopeEventListener l : scopeListeners)
+        if (activated) for (ScopeEventListener l : listeners)
             l.scopeActivated(scope);
-        else for (ScopeEventListener l : scopeListeners)
+        else for (ScopeEventListener l : listeners)
             l.scopeDeactivated(scope);
     }
 
@@ -90,7 +88,7 @@ public class ScopeRegistryImpl implement
      *            the scope that was removed.
      */
     protected void fireScopeDeregistered(OntologyScope scope) {
-        for (ScopeEventListener l : scopeListeners)
+        for (ScopeEventListener l : listeners)
             l.scopeDeregistered(scope);
     }
 
@@ -101,7 +99,7 @@ public class ScopeRegistryImpl implement
      *            the scope that was added.
      */
     protected void fireScopeRegistered(OntologyScope scope) {
-        for (ScopeEventListener l : scopeListeners)
+        for (ScopeEventListener l : listeners)
             l.scopeRegistered(scope);
     }
 
@@ -125,7 +123,7 @@ public class ScopeRegistryImpl implement
 
     @Override
     public Set<ScopeEventListener> getScopeRegistrationListeners() {
-        return scopeListeners;
+        return listeners;
     }
 
     @Override
@@ -148,7 +146,7 @@ public class ScopeRegistryImpl implement
 
     @Override
     public void removeScopeRegistrationListener(ScopeEventListener listener) {
-        scopeListeners.remove(listener);
+        listeners.remove(listener);
     }
 
     @Override

Modified: incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/owlapi/AbstractOntologySpaceImpl.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/owlapi/AbstractOntologySpaceImpl.java?rev=1352018&r1=1352017&r2=1352018&view=diff
==============================================================================
--- incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/owlapi/AbstractOntologySpaceImpl.java (original)
+++ incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/owlapi/AbstractOntologySpaceImpl.java Wed Jun 20 09:42:24 2012
@@ -44,6 +44,7 @@ import org.semanticweb.owlapi.model.OWLO
 import org.semanticweb.owlapi.model.OWLOntologyChange;
 import org.semanticweb.owlapi.model.OWLOntologyCreationException;
 import org.semanticweb.owlapi.model.OWLOntologyDocumentAlreadyExistsException;
+import org.semanticweb.owlapi.model.OWLOntologyID;
 import org.semanticweb.owlapi.model.OWLOntologyManager;
 import org.semanticweb.owlapi.model.OWLOntologyStorageException;
 import org.slf4j.Logger;
@@ -121,11 +122,6 @@ public abstract class AbstractOntologySp
     }
 
     @Override
-    public void addListener(OntologyCollectorListener listener) {
-        listeners.add(listener);
-    }
-
-    @Override
     public synchronized String addOntology(OntologyInputSource<?,?> ontologySource) throws UnmodifiableOntologyCollectorException {
         if (locked) throw new UnmodifiableOntologyCollectorException(this);
         log.debug("Trying to add ontology {} to space {}",
@@ -200,11 +196,6 @@ public abstract class AbstractOntologySp
         return root;
     }
 
-    @Override
-    public void clearListeners() {
-        listeners.clear();
-    }
-
     @SuppressWarnings("unchecked")
     @Override
     public <O> O export(Class<O> returnType, boolean merge) {
@@ -218,9 +209,9 @@ public abstract class AbstractOntologySp
      * @param ontologyIri
      *            the identifier of the ontology that was added to this space.
      */
-    protected void fireOntologyAdded(IRI ontologyIri) {
+    protected void fireOntologyAdded(OWLOntologyID added) {
         for (OntologyCollectorListener listener : listeners)
-            listener.onOntologyAdded(this.getID(), ontologyIri);
+            listener.onOntologyAdded(this, added);
     }
 
     /**
@@ -229,9 +220,9 @@ public abstract class AbstractOntologySp
      * @param ontologyIri
      *            the identifier of the ontology that was removed from this space.
      */
-    protected void fireOntologyRemoved(IRI ontologyIri) {
+    protected void fireOntologyRemoved(OWLOntologyID removed) {
         for (OntologyCollectorListener listener : listeners)
-            listener.onOntologyRemoved(this.getID(), ontologyIri);
+            listener.onOntologyRemoved(this, removed);
     }
 
     @Override
@@ -244,11 +235,6 @@ public abstract class AbstractOntologySp
         return _id;
     }
 
-    @Override
-    public Collection<OntologyCollectorListener> getListeners() {
-        return listeners;
-    }
-
     @SuppressWarnings("unchecked")
     @Override
     public <O> Set<O> getManagedOntologies(Class<O> returnType, boolean withClosure) {
@@ -305,7 +291,7 @@ public abstract class AbstractOntologySp
         // See to it that the ontology is copied to this manager.
         OWLOntology newOnt = reload((OWLOntology) ontology, ontologyManager, true, false);
         // if (newOnt!=null)
-        managedOntologies.put(OWLUtils.guessOntologyIdentifier(newOnt), newOnt);
+        managedOntologies.put(OWLUtils.guessOntologyIdentifier(newOnt).getOntologyIRI(), newOnt);
 
         fireOntologyAdded(OWLUtils.guessOntologyIdentifier(ontology));
 
@@ -366,7 +352,7 @@ public abstract class AbstractOntologySp
         OWLOntology root = null;
 
         IRI location = ontology.getOWLOntologyManager().getOntologyDocumentIRI(ontology);
-        IRI idd = OWLUtils.guessOntologyIdentifier(ontology);
+        IRI idd = OWLUtils.guessOntologyIdentifier(ontology).getOntologyIRI();
         if (mgr == null) mgr = ontologyManager;
         Set<OWLOntology> closure = withClosure ? ontology.getOWLOntologyManager().getImportsClosure(ontology)
                 : Collections.singleton(ontology);
@@ -383,7 +369,7 @@ public abstract class AbstractOntologySp
 
             for (OWLOntology o : closure) {
                 // System.out.println("In closure of " + ontology + " : " + o);
-                IRI id2 = OWLUtils.guessOntologyIdentifier(o);
+                IRI id2 = OWLUtils.guessOntologyIdentifier(o).getOntologyIRI();
                 // OWLOntologyID id = o.getOntologyID();
                 if (mgr.contains(id2)) {
                     // System.out.println("REMOVING " + id2);
@@ -437,11 +423,6 @@ public abstract class AbstractOntologySp
     }
 
     @Override
-    public void removeListener(OntologyCollectorListener listener) {
-        listeners.remove(listener);
-    }
-
-    @Override
     public synchronized void removeOntology(IRI ontologyId) throws OntologyCollectorModificationException {
         if (locked) throw new UnmodifiableOntologyCollectorException(this);
 
@@ -478,7 +459,7 @@ public abstract class AbstractOntologySp
 
             ontologyManager.removeOntology(ontologyManager.getOntology(ontologyId));
             managedOntologies.remove(ontologyId);
-            fireOntologyRemoved(ontologyId);
+            fireOntologyRemoved(new OWLOntologyID(ontologyId));
         } catch (RuntimeException ex) {
             throw new OntologyCollectorModificationException(this, ex);
         }
@@ -532,4 +513,24 @@ public abstract class AbstractOntologySp
         this.namespace = namespace;
     }
 
+    @Override
+    public void addOntologyCollectorListener(OntologyCollectorListener listener) {
+        listeners.add(listener);
+    }
+
+    @Override
+    public void clearOntologyCollectorListeners() {
+        listeners.clear();
+    }
+
+    @Override
+    public Collection<OntologyCollectorListener> getOntologyCollectorListeners() {
+        return listeners;
+    }
+
+    @Override
+    public void removeOntologyCollectorListener(OntologyCollectorListener listener) {
+        listeners.remove(listener);
+    }
+
 }

Modified: incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/owlapi/CustomOntologySpaceImpl.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/owlapi/CustomOntologySpaceImpl.java?rev=1352018&r1=1352017&r2=1352018&view=diff
==============================================================================
--- incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/owlapi/CustomOntologySpaceImpl.java (original)
+++ incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/owlapi/CustomOntologySpaceImpl.java Wed Jun 20 09:42:24 2012
@@ -16,8 +16,6 @@
  */
 package org.apache.stanbol.ontologymanager.ontonet.impl.owlapi;
 
-import org.apache.stanbol.ontologymanager.ontonet.api.collector.UnmodifiableOntologyCollectorException;
-import org.apache.stanbol.ontologymanager.ontonet.api.scope.CoreOntologySpace;
 import org.apache.stanbol.ontologymanager.ontonet.api.scope.CustomOntologySpace;
 import org.semanticweb.owlapi.model.IRI;
 import org.semanticweb.owlapi.model.OWLOntologyManager;
@@ -44,21 +42,6 @@ public class CustomOntologySpaceImpl ext
         super(buildId(scopeID), namespace, SpaceType.CUSTOM, ontologyManager);
     }
 
-    @Override
-    public void attachCoreSpace(CoreOntologySpace coreSpace, boolean skipRoot) throws UnmodifiableOntologyCollectorException {
-        // OWLOntology o = coreSpace.getTopOntology();
-        // // This does the append thingy
-        // log.debug("Attaching " + o + " TO " + getTopOntology() + " ...");
-        // try {
-        // // It is in fact the addition of the core space top ontology to the
-        // // custom space, with import statements and all.
-        // addOntology(new RootOntologySource(o, null));
-        // // log.debug("ok");
-        // } catch (Exception ex) {
-        // log.error("FAILED", ex);
-        // }
-    }
-
     /**
      * Once it is set up, a custom space is write-locked.
      */

Modified: incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/owlapi/OWLAPIOntologyProvider.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/owlapi/OWLAPIOntologyProvider.java?rev=1352018&r1=1352017&r2=1352018&view=diff
==============================================================================
--- incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/owlapi/OWLAPIOntologyProvider.java (original)
+++ incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/owlapi/OWLAPIOntologyProvider.java Wed Jun 20 09:42:24 2012
@@ -139,7 +139,7 @@ public class OWLAPIOntologyProvider impl
     }
 
     @Override
-    public String loadInStore(InputStream data, String formatIdentifier, String preferredKey, boolean force) {
+    public String loadInStore(InputStream data, String formatIdentifier, boolean force) {
         try {
             OWLOntology o = store.loadOntologyFromOntologyDocument(data);
             return OWLUtils.guessOntologyIdentifier(o).toString();
@@ -149,7 +149,7 @@ public class OWLAPIOntologyProvider impl
     }
 
     @Override
-    public String loadInStore(IRI location, String formatIdentifier, String preferredKey, boolean force) {
+    public String loadInStore(IRI location, String formatIdentifier, boolean force) {
         OWLOntology o = null;
         try {
             o = store.loadOntologyFromOntologyDocument(location);
@@ -164,7 +164,7 @@ public class OWLAPIOntologyProvider impl
     }
 
     @Override
-    public String loadInStore(Object ontology, String preferredKey, boolean force) {
+    public String loadInStore(Object ontology, boolean force) {
         throw new UnsupportedOperationException("Not implemented for OWL API version.");
     }
 
@@ -185,4 +185,21 @@ public class OWLAPIOntologyProvider impl
                 "The OWL API implementation does not use a graph for storing correspondencies");
     }
 
+    @Override
+    public String getKey(OWLOntologyID ontologyId) {
+        return ontologyId.getDefaultDocumentIRI().toString();
+    }
+
+    @Override
+    public Set<String> getOntologyVersionKeys(IRI ontologyIRI) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public void setLocatorMapping(IRI locator, String key) {
+        // TODO Auto-generated method stub
+        
+    }
+
 }

Modified: incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/owlapi/OntologySpaceFactoryImpl.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/owlapi/OntologySpaceFactoryImpl.java?rev=1352018&r1=1352017&r2=1352018&view=diff
==============================================================================
--- incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/owlapi/OntologySpaceFactoryImpl.java (original)
+++ incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/owlapi/OntologySpaceFactoryImpl.java Wed Jun 20 09:42:24 2012
@@ -67,7 +67,7 @@ public class OntologySpaceFactoryImpl im
         OntologyScope parentScope = registry.getScope(scopeID);
 
         if (parentScope != null && parentScope instanceof OntologyCollectorListener) s
-                .addListener((OntologyCollectorListener) parentScope);
+                .addOntologyCollectorListener((OntologyCollectorListener) parentScope);
         // Set the supplied ontology's parent as the root for this space.
         if (ontologySources != null) try {
             for (OntologyInputSource<?,?> src : ontologySources)

Modified: incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/renderers/ScopeSetRenderer.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/renderers/ScopeSetRenderer.java?rev=1352018&r1=1352017&r2=1352018&view=diff
==============================================================================
--- incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/renderers/ScopeSetRenderer.java (original)
+++ incubator/stanbol/trunk/ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/impl/renderers/ScopeSetRenderer.java Wed Jun 20 09:42:24 2012
@@ -1,25 +1,26 @@
 /*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-* contributor license agreements.  See the NOTICE file distributed with
-* this work for additional information regarding copyright ownership.
-* The ASF licenses this file to You under the Apache License, Version 2.0
-* (the "License"); you may not use this file except in compliance with
-* the License.  You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 package org.apache.stanbol.ontologymanager.ontonet.impl.renderers;
 
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Set;
 
+import org.apache.stanbol.ontologymanager.ontonet.api.Vocabulary;
 import org.apache.stanbol.ontologymanager.ontonet.api.scope.OntologyScope;
 import org.semanticweb.owlapi.apibinding.OWLManager;
 import org.semanticweb.owlapi.model.AddAxiom;
@@ -38,46 +39,44 @@ import org.slf4j.LoggerFactory;
 /**
  * Just an attempt. If we like it, make an API out of it.
  * 
+ * XXX deprecate it in favor of {@link Vocabulary} ?
+ * 
  * @author alexdma
  * 
  */
 public class ScopeSetRenderer {
 
-	private static OWLDataFactory __factory = OWLManager.getOWLDataFactory();
+    private static OWLDataFactory __factory = OWLManager.getOWLDataFactory();
 
-	private static IRI _scopeIri = IRI
-			.create("http://kres.iks-project.eu/ontology/onm/meta.owl#Scope");
+    private static IRI _scopeIri = IRI.create(Vocabulary.SCOPE);
 
-	private static OWLClass cScope = __factory.getOWLClass(_scopeIri);
+    private static OWLClass cScope = __factory.getOWLClass(_scopeIri);
 
-	public static OWLOntology getScopes(Set<OntologyScope> scopes) {
+    public static OWLOntology getScopes(Set<OntologyScope> 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 (OntologyScope scope : scopes) {
-			OWLNamedIndividual iScope = __factory.getOWLNamedIndividual(IRI.create(scope.getNamespace()+scope
-					.getID()));
-			OWLAxiom ax = __factory.getOWLClassAssertionAxiom(cScope, iScope);
-			additions.add(new AddAxiom(ont, ax));
-		}
-		mgr.applyChanges(additions);
+        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 (OntologyScope scope : scopes) {
+            OWLNamedIndividual iScope = __factory.getOWLNamedIndividual(IRI.create(scope.getNamespace()
+                                                                                   + scope.getID()));
+            OWLAxiom ax = __factory.getOWLClassAssertionAxiom(cScope, iScope);
+            additions.add(new AddAxiom(ont, ax));
+        }
+        mgr.applyChanges(additions);
 
-		return ont;
-	}
+        return ont;
+    }
 
 }

Modified: incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/MockOsgiContext.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/MockOsgiContext.java?rev=1352018&r1=1352017&r2=1352018&view=diff
==============================================================================
--- incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/MockOsgiContext.java (original)
+++ incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/MockOsgiContext.java Wed Jun 20 09:42:24 2012
@@ -31,52 +31,71 @@ import org.apache.clerezza.rdf.simple.st
 import org.apache.stanbol.ontologymanager.ontonet.api.ONManager;
 import org.apache.stanbol.ontologymanager.ontonet.api.OfflineConfiguration;
 import org.apache.stanbol.ontologymanager.ontonet.api.ontology.OntologyProvider;
+import org.apache.stanbol.ontologymanager.ontonet.api.scope.OntologySpaceFactory;
+import org.apache.stanbol.ontologymanager.ontonet.api.session.SessionManager;
 import org.apache.stanbol.ontologymanager.ontonet.impl.ONManagerImpl;
 import org.apache.stanbol.ontologymanager.ontonet.impl.OfflineConfigurationImpl;
 import org.apache.stanbol.ontologymanager.ontonet.impl.clerezza.ClerezzaOntologyProvider;
+import org.apache.stanbol.ontologymanager.ontonet.impl.clerezza.OntologySpaceFactoryImpl;
+import org.apache.stanbol.ontologymanager.ontonet.impl.session.SessionManagerImpl;
 
 /**
- * Utility class that provides some object that would be provided by SCR reference in an OSGi environment. Can
- * be used to simulate OSGi in unit tests.
+ * Utility class that provides some objects that would otherwise be provided by SCR reference in an OSGi
+ * environment. Can be used to simulate OSGi in unit tests.
  * 
  * @author alexdma
  * 
  */
 public class MockOsgiContext {
 
-    public static Parser parser;
+    private static Dictionary<String,Object> config;
 
-    public static TcManager tcManager;
+    private static OfflineConfiguration offline;
 
     public static ONManager onManager;
 
+    public static OntologyProvider<TcProvider> ontologyProvider;
+
+    public static Parser parser;
+
     public static Serializer serializer;
 
-    public static OntologyProvider<TcProvider> ontologyProvider;
+    public static SessionManager sessionManager;
 
-    private static OfflineConfiguration offline;
+    public static TcManager tcManager;
 
     static {
+        config = new Hashtable<String,Object>();
+        config.put(ONManager.ONTOLOGY_NETWORK_NS, "http://stanbol.apache.org/scope/");
+        config.put(SessionManager.SESSIONS_NS, "http://stanbol.apache.org/session/");
+        config.put(SessionManager.MAX_ACTIVE_SESSIONS, "-1");
         offline = new OfflineConfigurationImpl(new Hashtable<String,Object>());
         reset();
     }
 
+    /**
+     * Sets up a new mock OSGi context and cleans all resources and components.
+     */
     public static void reset() {
+        // reset Clerezza objects
         tcManager = new TcManager();
         tcManager.addWeightedTcProvider(new SimpleTcProvider());
-
-        parser = new Parser();
+        parser = new Parser(); // add Jena-supported formats + RDF/JSON
         parser.bindParsingProvider(new JenaParserProvider());
         parser.bindParsingProvider(new RdfJsonParsingProvider());
-
-        serializer = new Serializer();
+        serializer = new Serializer(); // add Jena-supported formats + RDF/JSON
         serializer.bindSerializingProvider(new JenaSerializerProvider());
         serializer.bindSerializingProvider(new RdfJsonSerializingProvider());
 
+        // reset Stanbol objects
         ontologyProvider = new ClerezzaOntologyProvider(tcManager, offline, parser);
-        Dictionary<String,Object> onmconf = new Hashtable<String,Object>();
-        onmconf.put(ONManager.ONTOLOGY_NETWORK_NS, "http://stanbol.apache.org/scope/");
-        onManager = new ONManagerImpl(ontologyProvider, offline, onmconf);
+        resetManagers();
+    }
+
+    public static void resetManagers() {
+        OntologySpaceFactory factory = new OntologySpaceFactoryImpl(ontologyProvider, config);
+        onManager = new ONManagerImpl(ontologyProvider, offline, factory, config);
+        sessionManager = new SessionManagerImpl(ontologyProvider, config);
     }
 
 }

Added: incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/TestUtilities.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/TestUtilities.java?rev=1352018&view=auto
==============================================================================
--- incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/TestUtilities.java (added)
+++ incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/TestUtilities.java Wed Jun 20 09:42:24 2012
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.stanbol.ontologymanager.ontonet;
+
+import static org.apache.stanbol.ontologymanager.ontonet.MockOsgiContext.parser;
+import static org.apache.stanbol.ontologymanager.ontonet.MockOsgiContext.reset;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.io.InputStream;
+
+import org.apache.clerezza.rdf.core.serializedform.SupportedFormat;
+import org.apache.stanbol.ontologymanager.ontonet.impl.clerezza.ClerezzaOWLUtils;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.semanticweb.owlapi.model.IRI;
+import org.semanticweb.owlapi.model.OWLOntologyID;
+
+public class TestUtilities {
+
+    private OWLOntologyID expectedOntologyID = new OWLOntologyID(
+            IRI.create("http://stanbol.apache.org/ontologies/test1.owl"));
+
+    @BeforeClass
+    public static void cleanup() throws Exception {
+        reset();
+    }
+
+    @Test
+    public void testLookahead() throws Exception {
+        InputStream content = getClass().getResourceAsStream("/ontologies/test1.owl");
+        OWLOntologyID id = ClerezzaOWLUtils.guessOntologyID(content, parser, SupportedFormat.RDF_XML);
+        assertNotNull(id);
+        assertEquals(expectedOntologyID, id);
+    }
+
+}

Added: incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/TestClerezzaProvider.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/TestClerezzaProvider.java?rev=1352018&view=auto
==============================================================================
--- incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/TestClerezzaProvider.java (added)
+++ incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/TestClerezzaProvider.java Wed Jun 20 09:42:24 2012
@@ -0,0 +1,117 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.stanbol.ontologymanager.ontonet.impl.clerezza;
+
+import static org.apache.clerezza.rdf.core.serializedform.SupportedFormat.RDF_XML;
+import static org.apache.stanbol.ontologymanager.ontonet.MockOsgiContext.parser;
+import static org.apache.stanbol.ontologymanager.ontonet.MockOsgiContext.reset;
+import static org.apache.stanbol.ontologymanager.ontonet.MockOsgiContext.tcManager;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Set;
+
+import org.apache.clerezza.rdf.core.access.TcProvider;
+import org.apache.stanbol.ontologymanager.ontonet.api.OfflineConfiguration;
+import org.apache.stanbol.ontologymanager.ontonet.api.ontology.OntologyProvider;
+import org.apache.stanbol.ontologymanager.ontonet.impl.OfflineConfigurationImpl;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.semanticweb.owlapi.model.IRI;
+import org.semanticweb.owlapi.model.OWLClassExpression;
+import org.semanticweb.owlapi.model.OWLNamedIndividual;
+import org.semanticweb.owlapi.model.OWLOntology;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tests the correct behaviour of the Clerezza-based implementation of {@link OntologyProvider}, regardless of
+ * virtual ontology network setups.
+ * 
+ * @author alexdma
+ * 
+ */
+public class TestClerezzaProvider {
+
+    private static Logger log = LoggerFactory.getLogger(TestClerezzaProvider.class);
+
+    @BeforeClass
+    public static void setup() throws Exception {
+        reset();
+    }
+
+    private String fn1 = "/ontologies/versiontest_v1.owl", fn2 = "/ontologies/versiontest_v2.owl";
+
+    private String oiri = "http://stanbol.apache.org/ontologies/versiontest";
+
+    private OntologyProvider<TcProvider> ontologyProvider;
+
+    private OfflineConfiguration offline = new OfflineConfigurationImpl(new Hashtable<String,Object>());
+
+    @After
+    public void cleanup() {
+        reset();
+    }
+
+    @Before
+    public void setupTest() throws Exception {
+        // Must be reset due to the internal key mapper.
+        ontologyProvider = new ClerezzaOntologyProvider(tcManager, offline, parser);
+    }
+
+    @Test
+    public void testVersionIRISplit() throws Exception {
+
+        // Check the first version
+        InputStream data = getClass().getResourceAsStream(fn1);
+        String key1 = ontologyProvider.loadInStore(data, RDF_XML, true);
+        assertNotNull(key1);
+        assertFalse(key1.isEmpty());
+
+        // Check the second version
+        data = getClass().getResourceAsStream(fn2);
+        String key2 = ontologyProvider.loadInStore(data, RDF_XML, true);
+        assertNotNull(key2);
+        assertFalse(key2.isEmpty());
+
+        // Must be 2 different graphs
+        assertFalse(key1.equals(key2));
+        assertEquals(2, ontologyProvider.getKeys().size());
+
+        // Ontologies must not be tainting each other
+        OWLOntology o1 = ontologyProvider.getStoredOntology(key1, OWLOntology.class, true);
+        OWLOntology o2 = ontologyProvider.getStoredOntology(key2, OWLOntology.class, true);
+        Set<OWLOntology> oAll = new HashSet<OWLOntology>(Arrays.asList(new OWLOntology[] {o1, o2}));
+        for (OWLNamedIndividual i : o1.getIndividualsInSignature()) {
+            Set<OWLClassExpression> tAll = i.getTypes(oAll), t1 = i.getTypes(o1), t2 = i.getTypes(o2);
+            assertTrue(tAll.containsAll(t1)); // Should be obvious from the OWL API
+            assertTrue(tAll.containsAll(t2)); // Should be obvious from the OWL API
+            assertFalse(t1.containsAll(t2));
+            assertFalse(t2.containsAll(t1));
+        }
+
+        log.info("{}", ontologyProvider.getKey(IRI.create(oiri)));
+    }
+}

Modified: incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/TestOntologyCollectors.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/TestOntologyCollectors.java?rev=1352018&r1=1352017&r2=1352018&view=diff
==============================================================================
--- incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/TestOntologyCollectors.java (original)
+++ incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/TestOntologyCollectors.java Wed Jun 20 09:42:24 2012
@@ -29,6 +29,7 @@ import org.apache.stanbol.ontologymanage
 import org.apache.stanbol.ontologymanager.ontonet.api.io.ParentPathInputSource;
 import org.apache.stanbol.ontologymanager.ontonet.api.scope.OntologySpace;
 import org.junit.After;
+import org.junit.Assert;
 import org.junit.Test;
 import org.semanticweb.owlapi.apibinding.OWLManager;
 import org.semanticweb.owlapi.model.IRI;
@@ -92,7 +93,7 @@ public class TestOntologyCollectors {
         // OntologyInputSource<OWLOntology> src = new OntologyContentInputSource(content,mgr);
 
         OWLOntology original = src.getRootOntology();
-
+        Assert.assertNotNull(original);
         OntologySpace spc = new CustomOntologySpaceImpl("Test", scopeNs, ontologyProvider);
         spc.addOntology(src);
 

Added: incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/TestOntologyNetworkPersistence.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/TestOntologyNetworkPersistence.java?rev=1352018&view=auto
==============================================================================
--- incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/TestOntologyNetworkPersistence.java (added)
+++ incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/impl/clerezza/TestOntologyNetworkPersistence.java Wed Jun 20 09:42:24 2012
@@ -0,0 +1,265 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.stanbol.ontologymanager.ontonet.impl.clerezza;
+
+import static org.apache.stanbol.ontologymanager.ontonet.MockOsgiContext.onManager;
+import static org.apache.stanbol.ontologymanager.ontonet.MockOsgiContext.parser;
+import static org.apache.stanbol.ontologymanager.ontonet.MockOsgiContext.resetManagers;
+import static org.apache.stanbol.ontologymanager.ontonet.MockOsgiContext.sessionManager;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.InputStream;
+import java.util.Dictionary;
+import java.util.Hashtable;
+
+import org.apache.clerezza.rdf.core.TripleCollection;
+import org.apache.clerezza.rdf.core.UriRef;
+import org.apache.clerezza.rdf.core.access.TcProvider;
+import org.apache.clerezza.rdf.core.impl.TripleImpl;
+import org.apache.clerezza.rdf.core.serializedform.SupportedFormat;
+import org.apache.clerezza.rdf.simple.storage.SimpleTcProvider;
+import org.apache.stanbol.ontologymanager.ontonet.api.ONManager;
+import org.apache.stanbol.ontologymanager.ontonet.api.Vocabulary;
+import org.apache.stanbol.ontologymanager.ontonet.api.io.GraphContentInputSource;
+import org.apache.stanbol.ontologymanager.ontonet.api.ontology.OntologyProvider;
+import org.apache.stanbol.ontologymanager.ontonet.api.scope.OntologyScope;
+import org.apache.stanbol.ontologymanager.ontonet.api.session.Session;
+import org.apache.stanbol.ontologymanager.ontonet.impl.ONManagerImpl;
+import org.apache.stanbol.ontologymanager.ontonet.impl.OfflineConfigurationImpl;
+import org.junit.Before;
+import org.junit.Test;
+import org.semanticweb.owlapi.model.IRI;
+import org.semanticweb.owlapi.model.OWLOntology;
+import org.semanticweb.owlapi.model.OWLOntologyID;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This suite is for testing that all the meta-level information stored by OntoNet can be retrieved and
+ * rebuilt if OntoNet or Stanbol goes down but the Clerezza store is not cleared.
+ * 
+ * @author alexdma
+ * 
+ */
+public class TestOntologyNetworkPersistence {
+
+    private Logger log = LoggerFactory.getLogger(getClass());
+
+    private OntologyProvider<TcProvider> ontologyProvider;
+
+    private ONManager onm;
+
+    @Test
+    public void updatesGraphOnSpaceModification() throws Exception {
+
+        // Ensure the metadata graph is there.
+        TripleCollection meta = ontologyProvider.getMetaGraph(TripleCollection.class);
+        assertNotNull(meta);
+
+        String scopeId = "updateTest";
+        OntologyScope scope = onm.createOntologyScope(scopeId, new GraphContentInputSource(getClass()
+                .getResourceAsStream("/ontologies/test1.owl")));
+
+        UriRef collector = new UriRef(scope.getNamespace() + scope.getCoreSpace().getID());
+        UriRef test1id = new UriRef("http://stanbol.apache.org/ontologies/test1.owl"); // Has no versionIRI
+
+        // Be strict: the whole property pair must be there.
+        UriRef predicate = new UriRef(Vocabulary.MANAGES_IN_CORE);
+        assertTrue(meta.contains(new TripleImpl(collector, predicate, test1id)));
+        predicate = new UriRef(Vocabulary.IS_MANAGED_BY_CORE);
+        assertTrue(meta.contains(new TripleImpl(test1id, predicate, collector)));
+
+        scope.tearDown(); // To modify the core space.
+
+        scope.getCoreSpace().addOntology(
+            new GraphContentInputSource(getClass().getResourceAsStream("/ontologies/minorcharacters.owl")));
+        UriRef minorId = new UriRef("http://stanbol.apache.org/ontologies/pcomics/minorcharacters.owl"); // Has no versionIRI
+        predicate = new UriRef(Vocabulary.MANAGES_IN_CORE);
+        assertTrue(meta.contains(new TripleImpl(collector, predicate, minorId)));
+        predicate = new UriRef(Vocabulary.IS_MANAGED_BY_CORE);
+        assertTrue(meta.contains(new TripleImpl(minorId, predicate, collector)));
+        
+        scope.getCustomSpace().addOntology(
+            new GraphContentInputSource(getClass().getResourceAsStream("/ontologies/test1.owl")));
+
+        scope.getCustomSpace().addOntology(
+            new GraphContentInputSource(getClass().getResourceAsStream("/ontologies/minorcharacters.owl")));
+    }
+
+    // @Test
+    public void preservesManagedOntologies() throws Exception {
+        String id = "preserve";
+        OntologyScope scope = onManager.createOntologyScope(id, new GraphContentInputSource(getClass()
+                .getResourceAsStream("/ontologies/mockfoaf.rdf")));
+        scope.getCustomSpace().addOntology(
+            new GraphContentInputSource(getClass().getResourceAsStream(
+                "/ontologies/nonexistentcharacters.owl")));
+
+        // Simulate Stanbol going down.
+        resetOntologyProvider(); // but keep the TcProvider
+        resetManagers();
+
+        OntologyScope sc = onManager.getScope(id);
+        assertNotNull(sc);
+        // assertEquals(scope, sc); XXX should scopes be equal on ID + content?
+
+        // for (IRI iri : sc.getCustomSpace().listManagedOntologies())
+        // System.out.println(iri);
+    }
+
+    @Test
+    public void scopesAndSessionsOutliveOntoNet() throws Exception {
+        String id1 = "scope1", id2 = "scope2";
+
+        // Setup a network
+
+        OntologyScope scope1 = onManager.createOntologyScope(id1);
+        assertNotNull(scope1);
+        // OntologyScope scope2 = onManager.createOntologyScope(id2);
+        // assertNotNull(scope2);
+
+        // onManager.deregisterScope(scope1);
+
+        Session ses1 = sessionManager.createSession();
+        assertNotNull(ses1);
+        assertNotNull(ses1.getID());
+        assertFalse(ses1.getID().isEmpty());
+        Session ses2 = sessionManager.createSession();
+        assertNotNull(ses2);
+        assertNotNull(ses2.getID());
+        assertFalse(ses2.getID().isEmpty());
+
+        resetOntologyProvider(); // but keep the TcProvider
+        resetManagers();
+
+        assertNotNull(onManager.getScope(id1));
+        // assertNotNull(onManager.getScope(id2));
+    }
+
+    /*
+     * Use a dedicated TC Provider that is setup once before the tests begin and never cleared.
+     */
+    private TcProvider tcp;
+
+    @Test
+    public void canRetrieveOntologyImported() throws Exception {
+        String pcomics = "http://stanbol.apache.org/ontologies/pcomics/";
+        OWLOntologyID foaf = new OWLOntologyID(IRI.create("http://xmlns.com/foaf/0.1/")), all = new OWLOntologyID(
+                IRI.create(pcomics + "characters_all.owl")), main = new OWLOntologyID(
+                IRI.create(pcomics + "maincharacters.owl")), minor = new OWLOntologyID(
+                IRI.create(pcomics + "minorcharacters.owl"));
+        OWLOntology oAll, oMain, oMinor, oFoaf;
+        final int total = 4;
+
+        // Load the Peanuts characters_all ontology (has 2 import levels)
+        InputStream data = getClass().getResourceAsStream("/ontologies/characters_all.owl");
+        String key = ontologyProvider.loadInStore(data, SupportedFormat.RDF_XML, false);
+        assertNotNull(key);
+        assertFalse(key.isEmpty());
+
+        /*
+         * characters_all, main, minor + mockfoaf (note: imports are available only because the xml:base is
+         * set to be the same as the import target)
+         */
+        assertEquals(total, ontologyProvider.getKeys().size());
+
+        // Check that each imported ontology is stored
+        oAll = ontologyProvider.getStoredOntology(ontologyProvider.getKey(all), OWLOntology.class, false);
+        OWLOntologyID id = oAll.getOntologyID();
+        assertNotNull(id);
+        assertEquals(all, id);
+        oMain = ontologyProvider.getStoredOntology(ontologyProvider.getKey(main), OWLOntology.class, false);
+        id = oMain.getOntologyID();
+        assertNotNull(id);
+        assertEquals(main, id);
+        oMinor = ontologyProvider.getStoredOntology(ontologyProvider.getKey(minor), OWLOntology.class, false);
+        id = oMinor.getOntologyID();
+        assertNotNull(id);
+        assertEquals(minor, id);
+        oFoaf = ontologyProvider.getStoredOntology(ontologyProvider.getKey(foaf), OWLOntology.class, false);
+        id = oFoaf.getOntologyID();
+        assertNotNull(id);
+        assertEquals(foaf, id);
+
+        resetOntologyProvider(); // but keep the TcProvider
+        assertEquals(total, ontologyProvider.getKeys().size());
+
+        // The OWL API implements OWLOntology#equals()
+        assertEquals(oAll,
+            ontologyProvider.getStoredOntology(ontologyProvider.getKey(all), OWLOntology.class, false));
+        assertEquals(oMain,
+            ontologyProvider.getStoredOntology(ontologyProvider.getKey(main), OWLOntology.class, false));
+        assertEquals(oMinor,
+            ontologyProvider.getStoredOntology(ontologyProvider.getKey(minor), OWLOntology.class, false));
+        assertEquals(oFoaf,
+            ontologyProvider.getStoredOntology(ontologyProvider.getKey(foaf), OWLOntology.class, false));
+    }
+
+   @Test
+    public void canRetrieveOntologySingleton() throws Exception {
+
+        OWLOntologyID foaf = new OWLOntologyID(IRI.create("http://xmlns.com/foaf/0.1/"));
+        OWLOntology o1;
+
+        // Get the fake FOAF
+        InputStream data = getClass().getResourceAsStream("/ontologies/mockfoaf.rdf");
+        String key = ontologyProvider.loadInStore(data, SupportedFormat.RDF_XML, false);
+        assertNotNull(key);
+        assertFalse(key.isEmpty());
+
+        // Retrieve the stored ontology
+        assertEquals(1, ontologyProvider.getKeys().size());
+        o1 = ontologyProvider.getStoredOntology(key, OWLOntology.class, false);
+        OWLOntologyID id = o1.getOntologyID();
+        assertNotNull(id);
+        assertEquals(foaf, id);
+
+        // Check there is a storage key for the FOAF ID
+        key = ontologyProvider.getKey(foaf);
+        assertNotNull(key);
+        assertFalse(key.isEmpty());
+
+        resetOntologyProvider(); // but keep the TcProvider
+        assertEquals(1, ontologyProvider.getKeys().size());
+
+        // Check again
+        key = ontologyProvider.getKey(foaf);
+        assertNotNull(key);
+        assertFalse(key.isEmpty());
+
+        // The OWL API implements OWLOntology#equals()
+        assertEquals(o1, ontologyProvider.getStoredOntology(key, OWLOntology.class, false));
+    }
+
+    @Before
+    public void cleanup() throws Exception {
+        tcp = new SimpleTcProvider();
+        resetOntologyProvider();
+        Dictionary<String,Object> empty = new Hashtable<String,Object>();
+        onm = new ONManagerImpl(ontologyProvider, new OfflineConfigurationImpl(empty),
+                new OntologySpaceFactoryImpl(ontologyProvider, empty), empty);
+    }
+
+    private void resetOntologyProvider() {
+        ontologyProvider = new ClerezzaOntologyProvider(tcp, new OfflineConfigurationImpl(
+                new Hashtable<String,Object>()), parser);
+    }
+
+}

Modified: incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/io/TestStorage.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/io/TestStorage.java?rev=1352018&r1=1352017&r2=1352018&view=diff
==============================================================================
--- incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/io/TestStorage.java (original)
+++ incubator/stanbol/trunk/ontologymanager/ontonet/src/test/java/org/apache/stanbol/ontologymanager/ontonet/io/TestStorage.java Wed Jun 20 09:42:24 2012
@@ -24,6 +24,7 @@ import static org.junit.Assert.assertFal
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 
+import java.io.File;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.Set;
@@ -34,6 +35,7 @@ import org.apache.clerezza.rdf.core.UriR
 import org.apache.clerezza.rdf.utils.GraphNode;
 import org.apache.stanbol.ontologymanager.ontonet.Constants;
 import org.apache.stanbol.ontologymanager.ontonet.api.io.OntologyInputSource;
+import org.apache.stanbol.ontologymanager.ontonet.api.io.ParentPathInputSource;
 import org.apache.stanbol.ontologymanager.ontonet.api.io.RootOntologyIRISource;
 import org.apache.stanbol.ontologymanager.ontonet.api.scope.OntologyScope;
 import org.junit.After;
@@ -64,8 +66,9 @@ public class TestStorage {
     public void storageOnScopeCreation() throws Exception {
 
         assertEquals(1, ontologyProvider.getStore().listTripleCollections().size());
-        OntologyInputSource ois = new RootOntologyIRISource(IRI.create(getClass().getResource(
-            "/ontologies/minorcharacters.owl")));
+        // This one has an import that we want to hijack locally, so we use the ParentPathInputSource.
+        OntologyInputSource<?,?> ois = new ParentPathInputSource(new File(getClass().getResource(
+            "/ontologies/minorcharacters.owl").toURI()));
 
         OntologyScope sc = onManager.createOntologyScope(scopeId, ois);