Author: alexdma
Date: Thu Nov 15 12:17:27 2012
New Revision: 1409749

URL: http://svn.apache.org/viewvc?rev=1409749&view=rev
Log:
Changes that close STANBOL-305:
* Changed behaviour of guessOntologyID in OWLUtils. Now it returns null only if 
it is unable to parse the ontology, while it returns an anonymous OWLOntologyID 
when it is able to parse it but cannot detect an ID.
* Rewrote loadInStore() methods in ClerezzaOntologyProvider so that they scan 
the origin array for overrides *once* and decide immediately on setting primary 
key and aliases. This way, timestamped public keys are generated *only* in the 
extreme event of the ontology being anonymous and no overrides or physical IRIs 
being provided.
* Ontology GET service now sets its request URI as version IRI also for 
Clerezza-supported MIME-types.
* New unit tests of ontology reconciliation when overrides are provided for 
anonymous ontologies.

Modified:
    
stanbol/trunk/commons/owl/src/main/java/org/apache/stanbol/commons/owl/util/OWLUtils.java
    
stanbol/trunk/commons/owl/src/test/java/org/apache/stanbol/commons/owl/util/TestOWLUtils.java
    
stanbol/trunk/ontologymanager/multiplexer/clerezza/src/main/java/org/apache/stanbol/ontologymanager/multiplexer/clerezza/ontology/ClerezzaOntologyProvider.java
    
stanbol/trunk/ontologymanager/multiplexer/clerezza/src/test/java/org/apache/stanbol/ontologymanager/multiplexer/clerezza/ontology/TestOntologyReconciliation.java
    
stanbol/trunk/ontologymanager/web/src/main/java/org/apache/stanbol/ontologymanager/web/resources/OntoNetRootResource.java

Modified: 
stanbol/trunk/commons/owl/src/main/java/org/apache/stanbol/commons/owl/util/OWLUtils.java
URL: 
http://svn.apache.org/viewvc/stanbol/trunk/commons/owl/src/main/java/org/apache/stanbol/commons/owl/util/OWLUtils.java?rev=1409749&r1=1409748&r2=1409749&view=diff
==============================================================================
--- 
stanbol/trunk/commons/owl/src/main/java/org/apache/stanbol/commons/owl/util/OWLUtils.java
 (original)
+++ 
stanbol/trunk/commons/owl/src/main/java/org/apache/stanbol/commons/owl/util/OWLUtils.java
 Thu Nov 15 12:17:27 2012
@@ -134,12 +134,14 @@ public class OWLUtils {
         OntologyLookaheadMGraph graph = new OntologyLookaheadMGraph(limit, 
versionIriOffset);
         try {
             parser.parse(graph, bIn, format);
-        } catch (RuntimeException e) {}
+        } catch (RuntimeException e) {
+            log.error("Parsing failed for format {}. Returning null.", format);
+        }
         OWLOntologyID result;
 
         if (graph.getOntologyIRI() == null) { // No Ontology ID found
             log.warn(" *** No ontology ID found, ontology has a chance of 
being anonymous.");
-            result = null;
+            result = new OWLOntologyID();
         } else {
             // bIn.reset(); // reset set the stream to the start
             IRI oiri = IRI.create(graph.getOntologyIRI().getUnicodeString());

Modified: 
stanbol/trunk/commons/owl/src/test/java/org/apache/stanbol/commons/owl/util/TestOWLUtils.java
URL: 
http://svn.apache.org/viewvc/stanbol/trunk/commons/owl/src/test/java/org/apache/stanbol/commons/owl/util/TestOWLUtils.java?rev=1409749&r1=1409748&r2=1409749&view=diff
==============================================================================
--- 
stanbol/trunk/commons/owl/src/test/java/org/apache/stanbol/commons/owl/util/TestOWLUtils.java
 (original)
+++ 
stanbol/trunk/commons/owl/src/test/java/org/apache/stanbol/commons/owl/util/TestOWLUtils.java
 Thu Nov 15 12:17:27 2012
@@ -19,8 +19,10 @@ package org.apache.stanbol.commons.owl.u
 import static 
org.apache.clerezza.rdf.core.serializedform.SupportedFormat.RDF_XML;
 import static 
org.apache.clerezza.rdf.core.serializedform.SupportedFormat.TURTLE;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
 
 import java.io.InputStream;
 
@@ -75,12 +77,13 @@ public class TestOWLUtils {
         // Try a low triple limit (the ontology IRI triple is much further).
         InputStream content = getClass().getResourceAsStream(location);
         OWLOntologyID id = OWLUtils.guessOntologyID(content, parser, RDF_XML, 
10);
-        assertNull(id);
+        assertTrue(id.isAnonymous());
 
         // Try again with no limit
         content = getClass().getResourceAsStream(location);
         id = OWLUtils.guessOntologyID(content, parser, RDF_XML);
         assertNotNull(id);
+        assertFalse(id.isAnonymous());
         assertEquals(new OWLOntologyID(ontologyIri), id);
     }
 
@@ -115,24 +118,27 @@ public class TestOWLUtils {
         // Low triple limit: guessing should fail.
         InputStream content = getClass().getResourceAsStream(location);
         OWLOntologyID id = OWLUtils.guessOntologyID(content, parser, RDF_XML, 
10);
-        assertNull(id);
+        assertTrue(id.isAnonymous());
 
         // Reasonable triple limit with low offset: guessing should return the 
unversioned ID.
         content = getClass().getResourceAsStream(location);
         id = OWLUtils.guessOntologyID(content, parser, RDF_XML, 256, 1);
         assertNotNull(id);
+        assertFalse(id.isAnonymous());
         assertEquals(new OWLOntologyID(ontologyIri), id);
 
         // Reasonable triple limit with auto offset: guessing should succeed.
         content = getClass().getResourceAsStream(location);
         id = OWLUtils.guessOntologyID(content, parser, RDF_XML, 256);
         assertNotNull(id);
+        assertFalse(id.isAnonymous());
         assertEquals(expectedOntId, id);
 
         // No triple limit: guessing should succeed.
         content = getClass().getResourceAsStream(location);
         id = OWLUtils.guessOntologyID(content, parser, RDF_XML);
         assertNotNull(id);
+        assertFalse(id.isAnonymous());
         assertEquals(expectedOntId, id);
     }
 
@@ -177,12 +183,13 @@ public class TestOWLUtils {
         // No triple limit but offset < 102 : guessing should fail.
         InputStream content = getClass().getResourceAsStream(location);
         OWLOntologyID id = OWLUtils.guessOntologyID(content, parser, TURTLE, 
-1, 99);
-        assertNull(id);
+        assertTrue(id.isAnonymous());
 
         // Try again, setting limit = 1024 (offset = 102) should work.
         content = getClass().getResourceAsStream(location);
         id = OWLUtils.guessOntologyID(content, parser, TURTLE, 1024);
         assertNotNull(id);
+        assertFalse(id.isAnonymous());
         assertEquals(expectedOntId, id);
     }
 

Modified: 
stanbol/trunk/ontologymanager/multiplexer/clerezza/src/main/java/org/apache/stanbol/ontologymanager/multiplexer/clerezza/ontology/ClerezzaOntologyProvider.java
URL: 
http://svn.apache.org/viewvc/stanbol/trunk/ontologymanager/multiplexer/clerezza/src/main/java/org/apache/stanbol/ontologymanager/multiplexer/clerezza/ontology/ClerezzaOntologyProvider.java?rev=1409749&r1=1409748&r2=1409749&view=diff
==============================================================================
--- 
stanbol/trunk/ontologymanager/multiplexer/clerezza/src/main/java/org/apache/stanbol/ontologymanager/multiplexer/clerezza/ontology/ClerezzaOntologyProvider.java
 (original)
+++ 
stanbol/trunk/ontologymanager/multiplexer/clerezza/src/main/java/org/apache/stanbol/ontologymanager/multiplexer/clerezza/ontology/ClerezzaOntologyProvider.java
 Thu Nov 15 12:17:27 2012
@@ -38,6 +38,7 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.net.URLConnection;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Dictionary;
@@ -536,9 +537,8 @@ public class ClerezzaOntologyProvider im
         log.info(" ... Alias : {}", alias);
         // Check that they do not map to two different ontologies.
         OWLOntologyID already = checkAlias(primaryKey, alias);
-        /*if (already != null) throw new 
IllegalArgumentException*/log.warn(alias
-                                                                + " is already 
an alias for primary key "
-                                                                + already);
+        /* if (already != null) throw new IllegalArgumentException */log
+                .warn(alias + " is already an alias for primary key " + 
already);
         // XXX a SPARQL query could come in handy.
         // Nothing to do but defer to the meta graph,
         new MetaGraphManager(tcManager, 
keymap.graph).updateAddAlias(primaryKey, alias);
@@ -1094,10 +1094,9 @@ public class ClerezzaOntologyProvider im
     public OWLOntologyID loadInStore(final IRI ontologyIri,
                                      String formatIdentifier,
                                      boolean force,
-                                     Origin<?>... references) throws 
IOException {
+                                     Origin<?>... origins) throws IOException {
         log.debug("Loading {}", ontologyIri);
         if (ontologyIri == null) throw new IllegalArgumentException("Ontology 
IRI cannot be null.");
-        checkReplaceability(references);
 
         IRI location = null;
         if (force) location = null;
@@ -1114,6 +1113,11 @@ public class ClerezzaOntologyProvider im
 
         log.info("found {} in {}", ontologyIri, location);
 
+        // Add the physical IRI to the origins.
+        origins = Arrays.copyOf(origins, origins.length + 1);
+        origins[origins.length - 1] = Origin.create(ontologyIri);
+        checkReplaceability(origins);
+
         // Get ordered list of preferred/supported formats, or use the 
specified one.
         List<String> supported = 
OntologyUtils.getPreferredSupportedFormats(parser.getSupportedFormats());
         List<String> formats;
@@ -1137,7 +1141,7 @@ public class ClerezzaOntologyProvider im
                      * formats again. Also, we provide the ontologyIRI as the 
preferred key, since we already
                      * know it.
                      */
-                    OWLOntologyID key = loadInStore(is, currentFormat, force, 
Origin.create(ontologyIri));
+                    OWLOntologyID key = loadInStore(is, currentFormat, force, 
origins);
                     // If parsing failed, an exception will be thrown before 
getting here, so no risk.
                     // if (key != null && !key.isEmpty()) 
setLocatorMapping(ontologyIri, key);
                     return key;
@@ -1163,12 +1167,14 @@ public class ClerezzaOntologyProvider im
         checkReplaceability(origins);
         long before = System.currentTimeMillis();
 
-        TripleCollection graph; // The final graph
+        TripleCollection targetGraph; // The final graph
         TripleCollection rdfData; // The supplied ontology converted to 
TripleCollection
 
         if (ontology instanceof OWLOntology) {
+            // This will be in memory!
             rdfData = 
OWLAPIToClerezzaConverter.owlOntologyToClerezzaMGraph((OWLOntology) ontology);
         } else if (ontology instanceof TripleCollection) {
+            // This might be in memory or in persistent storage.
             rdfData = (TripleCollection) ontology;
         } else throw new UnsupportedOperationException(
                 "This ontology provider can only accept objects assignable to 
" + TripleCollection.class
@@ -1176,86 +1182,107 @@ public class ClerezzaOntologyProvider im
 
         // XXX Force is ignored for the content, but the imports?
 
-        // TODO Profile this method. Are we getting rid of rdfData after 
adding its triples?
-        OWLOntologyID extractedId = OWLUtils.extractOntologyID(rdfData);
-
-        OWLOntologyID publicKey = null;
+        // Now we proceed to assign the primary key to the ontology.
+        OWLOntologyID primaryKey = null;
 
-        for (int i = 0; i < origins.length && publicKey == null; i++) {
-            if (origins[i] != null) {
-                Object ref = origins[i].getReference();
-                if (ref instanceof OWLOntologyID) publicKey = (OWLOntologyID) 
ref;
+        /*
+         * Compute aliases
+         */
+        UriRef graphName = null;
+        List<OWLOntologyID> overrides = new ArrayList<OWLOntologyID>(); // 
Priority aliases.
+        List<IRI> sources = new ArrayList<IRI>(); // Second-choice aliases.
+
+        // Scan origins ONCE.
+        for (int i = 0; i < origins.length; i++) {
+            Origin<?> origin = origins[i];
+            log.debug("Found origin at index {}", i);
+            if (origin == null) {
+                log.warn("Null origin at index {}. Skipping.", i);
+                continue;
+            }
+            Object ref = origin.getReference();
+            if (ref == null) {
+                log.warn("Null reference at index {}. Skipping.", i);
+                continue;
+            }
+            log.debug(" ... Reference is a {}", 
ref.getClass().getCanonicalName());
+            log.debug(" ... Value : {}", ref);
+            if (ref instanceof OWLOntologyID) {
+                OWLOntologyID key = (OWLOntologyID) ref;
+                if (primaryKey == null) {
+                    primaryKey = key;
+                    log.debug(" ... assigned as primary key.");
+                } else if (primaryKey.equals(key)) {
+                    log.debug(" ... matches primary key. Skipping.");
+                } else {
+                    overrides.add(key);
+                    log.debug(" ... assigned as a priority alias for {}", 
primaryKey);
+                }
+            } else if (ref instanceof IRI) {
+                sources.add((IRI) ref);
+                log.debug(" ... assigned as a secondary alias (source) for 
{}", primaryKey);
+            } else if (ref instanceof UriRef) {
+                if (graphName != null) log.warn("Graph name already assigned 
as {}. Skipping.", graphName);
+                else {
+                    graphName = (UriRef) ref;
+                    log.debug(" ... assigned as a graph name for {}", 
primaryKey);
+                }
+            } else {
+                log.warn("Unhandled type for origin at index {} : {}. 
Skipping.", i, ref.getClass());
             }
         }
 
-        if (publicKey == null) publicKey = extractedId;
+        // The actual logical ID will be dereferenceable no matter what.
+        OWLOntologyID extractedId = OWLUtils.extractOntologyID(rdfData);
+        if (primaryKey == null) primaryKey = extractedId; // Not overridden: 
set as primary key.
+        else overrides.add(extractedId); // Overridden: must be an alias 
anyway.
 
-        if (publicKey == null) {
+        if (primaryKey == null) // No overrides, no extracted ID.
+        {
             IRI z;
-            if (origins.length > 0 && origins[0] != null) {
-                Object reff = origins[0].getReference();
-                if (reff instanceof IRI) z = (IRI) reff; // No version IRI here
-                else if (reff instanceof UriRef) z = IRI.create(((UriRef) 
reff).getUnicodeString());
-                else z = IRI.create(getClass().getCanonicalName() + "-time:" + 
System.currentTimeMillis());
-            } else z = IRI.create(getClass().getCanonicalName() + "-time:" + 
System.currentTimeMillis());
-            publicKey = new OWLOntologyID(z);
+            // The first IRI found becomes the primary key.
+            if (!sources.isEmpty()) z = sources.iterator().next();
+            else // Try the graph name
+            if (graphName != null) z = 
IRI.create(graphName.getUnicodeString());
+            else // Extrema ratio : compute a timestamped primary key.
+            z = IRI.create(getClass().getCanonicalName() + "-time:" + 
System.currentTimeMillis());
+            primaryKey = new OWLOntologyID(z);
         }
 
         // Check if it is possible to avoid reloading the ontology content 
from its source.
         boolean mustLoad = true;
-        if (!force) {
-            Set<UriRef> stored = store.listTripleCollections();
-            if (origins.length > 0 && origins[0] != null && 
origins[0].getReference() instanceof UriRef) {
-                UriRef ref = (UriRef) origins[0].getReference();
-
-                if (stored.contains(ref)) {
-                    boolean condition = true; // Any failed check will make it 
false
-
-                    /*
-                     * Check if the stored Ontology ID (versionIRI included) 
matches matches that of the
-                     * ontology source. XXX note that anonymous ontologies 
should be considered a match... or
-                     * should they not?
-                     */
-                    OWLOntologyID idFromSrc = 
OWLUtils.extractOntologyID(rdfData);
-                    OWLOntologyID idFromStore = 
OWLUtils.extractOntologyID(store.getTriples(ref));
-                    condition &= (idFromSrc == null && idFromStore == null) || 
idFromSrc.equals(idFromStore);
-
-                    // Finally, a size check
-                    if (condition && rdfData instanceof TripleCollection) 
condition &= store.getTriples(ref)
-                            .size() == rdfData.size();
-
-                    mustLoad &= !condition;
-                }
-            }
-        }
-
-        // The policy here is to avoid copying the triples from a graph 
already in the store.
-        // FIXME not a good policy for graphs that change
-        String iri = null;
-        if (publicKey.getOntologyIRI() != null) iri = 
publicKey.getOntologyIRI().toString();
-        if (publicKey.getVersionIRI() != null) iri += ":::" + 
publicKey.getVersionIRI().toString();
-        // s will become the graph name
-        String s = (iri.startsWith(prefix + "::")) ? "" : (prefix + "::");
-        s += iri;
-        UriRef uriref;
-        if (mustLoad) {
-            uriref = new UriRef(URIUtils.sanitize(s));
-            log.debug("Storing ontology with graph ID {}", uriref);
-            try {
-                graph = store.createMGraph(uriref);
-            } catch (EntityAlreadyExistsException e) {
-                if (uriref.equals(e.getEntityName())) graph = 
store.getMGraph(uriref);
-                else graph = store.createMGraph(uriref);
-            }
-            graph.addAll(rdfData);
+        if (!force && graphName != null && 
store.listTripleCollections().contains(graphName)) {
+            boolean condition = true; // Any failed check will abort the scan.
+            // Check if the extracted ontology ID matches that of the supplied 
graph.
+            // XXX note that anonymous ontologies should be considered a 
match... or should they not?
+            TripleCollection tc = store.getTriples(graphName);
+            OWLOntologyID idFromStore = OWLUtils.extractOntologyID(tc);
+            condition &= (extractedId == null && idFromStore == null) || 
extractedId.equals(idFromStore);
+            // Finally, a size check
+            // FIXME not a good policy for graphs that change without altering 
the size.
+            if (condition && rdfData instanceof TripleCollection) condition &= 
tc.size() == rdfData.size();
+            mustLoad &= !condition;
+        }
+
+        if (!mustLoad && graphName != null) {
+            log.debug("Graph with ID {} already in store. Default action is to 
skip storage.", graphName);
+            targetGraph = store.getTriples(graphName);
         } else {
+            String iri = null;
+            if (primaryKey.getOntologyIRI() != null) iri = 
primaryKey.getOntologyIRI().toString();
+            if (primaryKey.getVersionIRI() != null) iri += ":::" + 
primaryKey.getVersionIRI().toString();
+            // s will become the graph name
+            String s = (iri.startsWith(prefix + "::")) ? "" : (prefix + "::");
+            s += iri;
+            graphName = new UriRef(URIUtils.sanitize(s));
+            log.debug("Storing ontology with graph ID {}", graphName);
             try {
-                uriref = (UriRef) origins[0].getReference();
-            } catch (ClassCastException cex) {
-                uriref = new UriRef(s);
+                targetGraph = store.createMGraph(graphName);
+            } catch (EntityAlreadyExistsException e) {
+                if (graphName.equals(e.getEntityName())) targetGraph = 
store.getMGraph(graphName);
+                else targetGraph = store.createMGraph(graphName);
             }
-            log.debug("Graph with ID {} already in store. Default action is to 
skip storage.", origins[0]);
-            graph = store.getTriples(uriref);
+            targetGraph.addAll(rdfData);
         }
 
         // All is already sanitized by the time we get here.
@@ -1263,48 +1290,32 @@ public class ClerezzaOntologyProvider im
         // Now do the mappings
         String mappedIds = "";
         // Discard unconventional ontology IDs with only the version IRI
-        if (publicKey != null && publicKey.getOntologyIRI() != null) {
+        if (primaryKey != null && primaryKey.getOntologyIRI() != null) {
             // Versioned or not, the real ID mapping is always added
-            keymap.setMapping(publicKey, uriref);
-            mappedIds += publicKey;
+            keymap.setMapping(primaryKey, graphName);
+            mappedIds += primaryKey;
             // TODO map unversioned ID as well?
-            Triple t = new TripleImpl(keymap.buildResource(publicKey), 
SIZE_IN_TRIPLES_URIREF, LiteralFactory
-                    
.getInstance().createTypedLiteral(Integer.valueOf(rdfData.size())));
+            Triple t = new TripleImpl(keymap.buildResource(primaryKey), 
SIZE_IN_TRIPLES_URIREF,
+                    
LiteralFactory.getInstance().createTypedLiteral(Integer.valueOf(rdfData.size())));
             getMetaGraph(MGraph.class).add(t);
         }
-        /*
-         * Make an ontology ID out of the originally supplied IRI (which might 
be the physical one and differ
-         * from the logical one!)
-         * 
-         * If we find out that it differs from the "real ID", we map this one 
too.
-         * 
-         * TODO how safe is this if there was a mapping earlier?
-         */
 
-        for (Origin<?> origin : origins)
-            if (origin != null) {
-                Object reff = origin.getReference();
-                OWLOntologyID alias = null;
-                if (reff instanceof IRI) alias = new OWLOntologyID((IRI) reff);
-                else if (reff instanceof OWLOntologyID) alias = 
(OWLOntologyID) reff;
-                if (!alias.equals(publicKey)) {
-                    // keymap.setMapping(physical, uriref);
-                    addAlias(publicKey, alias);
-                    mappedIds += " , " + alias;
-                }
+        // Add aliases.
+        for (IRI source : sources)
+            if (source != null) overrides.add(new OWLOntologyID(source));
+        for (OWLOntologyID alias : overrides)
+            if (alias != null && !alias.equals(primaryKey)) {
+                addAlias(primaryKey, alias);
+                mappedIds += " , " + alias;
             }
-        if (extractedId != null && !extractedId.equals(publicKey)) {
-            addAlias(publicKey, extractedId);
-            mappedIds += " , " + extractedId;
-        }
 
         // Do this AFTER registering the ontology, otherwise import cycles 
will cause infinite loops.
         if (resolveImports) {
             // Scan resources of type owl:Ontology, but only get the first.
-            Iterator<Triple> it = graph.filter(null, RDF.type, OWL.Ontology);
+            Iterator<Triple> it = targetGraph.filter(null, RDF.type, 
OWL.Ontology);
             if (it.hasNext()) {
                 // Scan import statements for the one owl:Ontology considered.
-                Iterator<Triple> it2 = graph.filter(it.next().getSubject(), 
OWL.imports, null);
+                Iterator<Triple> it2 = 
targetGraph.filter(it.next().getSubject(), OWL.imports, null);
                 while (it2.hasNext()) {
                     Resource obj = it2.next().getObject();
                     log.info("Resolving import target {}", obj);
@@ -1325,7 +1336,7 @@ public class ClerezzaOntologyProvider im
                         } else {
                             log.info("Requested import already stored. Setting 
dependency only.");
                         }
-                        descriptor.setDependency(publicKey, id);
+                        descriptor.setDependency(primaryKey, id);
                     } catch (UnsupportedFormatException e) {
                         log.warn("Failed to parse format for resource " + obj, 
e);
                         // / XXX configure to continue?
@@ -1338,12 +1349,12 @@ public class ClerezzaOntologyProvider im
         }
 
         log.debug(" Ontology {}", mappedIds);
-        if (graph != null) log.debug(" ... ({} triples)", graph.size());
-        log.debug(" ... primary public key : {}", publicKey);
+        if (targetGraph != null) log.debug(" ... ({} triples)", 
targetGraph.size());
+        log.debug(" ... primary public key : {}", primaryKey);
         // log.debug("--- {}", URIUtils.sanitize(s));
         log.debug("Time: {} ms", (System.currentTimeMillis() - before));
         // return URIUtils.sanitize(s);
-        return publicKey;
+        return primaryKey;
     }
 
     @Override

Modified: 
stanbol/trunk/ontologymanager/multiplexer/clerezza/src/test/java/org/apache/stanbol/ontologymanager/multiplexer/clerezza/ontology/TestOntologyReconciliation.java
URL: 
http://svn.apache.org/viewvc/stanbol/trunk/ontologymanager/multiplexer/clerezza/src/test/java/org/apache/stanbol/ontologymanager/multiplexer/clerezza/ontology/TestOntologyReconciliation.java?rev=1409749&r1=1409748&r2=1409749&view=diff
==============================================================================
--- 
stanbol/trunk/ontologymanager/multiplexer/clerezza/src/test/java/org/apache/stanbol/ontologymanager/multiplexer/clerezza/ontology/TestOntologyReconciliation.java
 (original)
+++ 
stanbol/trunk/ontologymanager/multiplexer/clerezza/src/test/java/org/apache/stanbol/ontologymanager/multiplexer/clerezza/ontology/TestOntologyReconciliation.java
 Thu Nov 15 12:17:27 2012
@@ -31,6 +31,8 @@ import java.io.InputStream;
 import java.net.URL;
 import java.util.Set;
 
+import org.apache.stanbol.ontologymanager.servicesapi.io.Origin;
+import 
org.apache.stanbol.ontologymanager.servicesapi.ontology.OntologyProvider.Status;
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -61,6 +63,8 @@ public class TestOntologyReconciliation 
         reset();
     }
 
+    private String location_nameless = "/ontologies/nameless_ontology.owl";
+
     private Logger log = LoggerFactory.getLogger(getClass());
 
     /*
@@ -69,8 +73,7 @@ public class TestOntologyReconciliation 
      */
     @Test
     public void anonymousFromStream() throws Exception {
-        String location = "/ontologies/nameless_ontology.owl";
-        InputStream in = getClass().getResourceAsStream(location);
+        InputStream in = getClass().getResourceAsStream(location_nameless);
         in.mark(Integer.MAX_VALUE);
         OWLOntologyManager onMgr = OWLManager.createOWLOntologyManager();
         OWLOntology o1 = onMgr.loadOntologyFromOntologyDocument(in);
@@ -88,13 +91,48 @@ public class TestOntologyReconciliation 
     }
 
     /*
+     * If an anonymous ontology is loaded from a stream and at least one 
override is provided, the first
+     * override should be the primary key, while every other override should 
be an alias for that key.
+     */
+    @Test
+    public void anonymousFromStreamWithCustomKeys() throws Exception {
+        OWLOntologyID myKey = new OWLOntologyID(IRI.create("nameless"), 
IRI.create(getClass()
+                .getCanonicalName() + "#anonymousFromStreamWithCustomKeys()"));
+        OWLOntologyID alias = new OWLOntologyID(IRI.create("nameless"), 
IRI.create(getClass()
+                .getCanonicalName() + 
"#anonymousFromStreamWithCustomKeys().alias"));
+        InputStream in = getClass().getResourceAsStream(location_nameless);
+        in.mark(Integer.MAX_VALUE);
+        OWLOntologyManager onMgr = OWLManager.createOWLOntologyManager();
+        OWLOntology o1 = onMgr.loadOntologyFromOntologyDocument(in);
+        assertTrue(o1.isAnonymous());
+        in.reset();
+        // in = getClass().getResourceAsStream(location); // use if stream 
cannot be reset
+        OWLOntologyID key = ontologyProvider.loadInStore(in, RDF_XML, false, 
Origin.create(myKey),
+            Origin.create(alias));
+        assertNotNull(key);
+        assertFalse(key.isAnonymous());
+        assertEquals(myKey, key);
+        log.info("Anonymous ontology loaded with non-anonymous public key {} 
(submitted)", key);
+
+        assertEquals(1, ontologyProvider.listAliases(key).size());
+        for (OWLOntologyID al : ontologyProvider.listAliases(key)) {
+            assertFalse(al.isAnonymous());
+            log.info("Named alias detected {}", al);
+        }
+
+        // Now retrieve using the alias
+        OWLOntology o2 = ontologyProvider.getStoredOntology(alias, 
OWLOntology.class, false);
+        assertTrue(o2.isAnonymous());
+        assertEquals(o1.getAxioms(), o2.getAxioms()); // Cannot equal 
OWLOntology objects
+    }
+
+    /*
      * Anonymous ontologies loaded from a URL must reconcile with a public key 
that matches the resource URL
      * in its ontology IRI.
      */
     @Test
     public void anonymousFromURL() throws Exception {
-        String location = "/ontologies/nameless_ontology.owl";
-        URL in = getClass().getResource(location);
+        URL in = getClass().getResource(location_nameless);
         OWLOntologyManager onMgr = OWLManager.createOWLOntologyManager();
         OWLOntology o1 = 
onMgr.loadOntologyFromOntologyDocument(IRI.create(in));
         assertTrue(o1.isAnonymous());
@@ -109,6 +147,46 @@ public class TestOntologyReconciliation 
     }
 
     /*
+     * If an anonymous ontology is loaded from a URL and at least one override 
is provided, the first override
+     * should be the primary key, while everything else, including the URL, 
should be an alias for that key.
+     */
+    @Test
+    public void anonymousFromURLWithCustomKeys() throws Exception {
+        OWLOntologyID myKey = new OWLOntologyID(IRI.create("nameless"), 
IRI.create(getClass()
+                .getCanonicalName() + "#anonymousFromURLWithCustomKeys()"));
+        OWLOntologyID alias = new OWLOntologyID(IRI.create("nameless"), 
IRI.create(getClass()
+                .getCanonicalName() + 
"#anonymousFromURLWithCustomKeys().alias"));
+        URL url = getClass().getResource(location_nameless);
+        OWLOntologyManager onMgr = OWLManager.createOWLOntologyManager();
+        OWLOntology o1 = 
onMgr.loadOntologyFromOntologyDocument(IRI.create(url));
+        assertTrue(o1.isAnonymous());
+
+        OWLOntologyID key = ontologyProvider.loadInStore(IRI.create(url), 
RDF_XML, false,
+            Origin.create(myKey), Origin.create(alias));
+        assertNotNull(key);
+        assertFalse(key.isAnonymous());
+        assertEquals(myKey, key);
+        log.info("Anonymous ontology loaded with non-anonymous public key {} 
(submitted)", key);
+
+        // should have 2 aliases: the physical location and the submitted 
alias.
+        assertEquals(2, ontologyProvider.listAliases(key).size());
+        for (OWLOntologyID al : ontologyProvider.listAliases(key)) {
+            assertFalse(al.isAnonymous());
+            log.info("Named alias detected {}", al);
+        }
+
+        // Now retrieve using the alias...
+        OWLOntology o2 = ontologyProvider.getStoredOntology(alias, 
OWLOntology.class, false);
+        assertTrue(o2.isAnonymous());
+        assertEquals(o1.getAxioms(), o2.getAxioms()); // Cannot equal 
OWLOntology objects
+
+        // ... and using the physical IRI
+        o2 = ontologyProvider.getStoredOntology(new 
OWLOntologyID(IRI.create(url)), OWLOntology.class, false);
+        assertTrue(o2.isAnonymous());
+        assertEquals(o1.getAxioms(), o2.getAxioms()); // Cannot equal 
OWLOntology objects
+    }
+
+    /*
      * Named ontologies loaded from a data stream should have no aliases and 
directly reconcile with the
      * ontology IRI.
      */
@@ -220,7 +298,7 @@ public class TestOntologyReconciliation 
 
         // The unversioned ID should return no match...
         OWLOntologyID unversioned = new OWLOntologyID(key.getOntologyIRI());
-        assertFalse(ontologyProvider.hasOntology(unversioned));
+        assertSame(Status.NO_MATCH, ontologyProvider.getStatus(unversioned));
 
         // ...but a query on the available versions should return only the 
public key.
         Set<OWLOntologyID> versions = 
ontologyProvider.listVersions(key.getOntologyIRI());
@@ -246,7 +324,7 @@ public class TestOntologyReconciliation 
         log.info(" -- (matches actual ontology ID).");
 
         // The unversioned ID should still return no match...
-        assertFalse(ontologyProvider.hasOntology(unversioned));
+        assertSame(Status.NO_MATCH, ontologyProvider.getStatus(unversioned));
 
         // ...but a query on the available versions should return both public 
keys now.
         versions = ontologyProvider.listVersions(key.getOntologyIRI());

Modified: 
stanbol/trunk/ontologymanager/web/src/main/java/org/apache/stanbol/ontologymanager/web/resources/OntoNetRootResource.java
URL: 
http://svn.apache.org/viewvc/stanbol/trunk/ontologymanager/web/src/main/java/org/apache/stanbol/ontologymanager/web/resources/OntoNetRootResource.java?rev=1409749&r1=1409748&r2=1409749&view=diff
==============================================================================
--- 
stanbol/trunk/ontologymanager/web/src/main/java/org/apache/stanbol/ontologymanager/web/resources/OntoNetRootResource.java
 (original)
+++ 
stanbol/trunk/ontologymanager/web/src/main/java/org/apache/stanbol/ontologymanager/web/resources/OntoNetRootResource.java
 Thu Nov 15 12:17:27 2012
@@ -91,6 +91,7 @@ import org.apache.clerezza.rdf.core.impl
 import org.apache.clerezza.rdf.core.serializedform.Parser;
 import org.apache.clerezza.rdf.core.serializedform.UnsupportedFormatException;
 import org.apache.clerezza.rdf.ontologies.OWL;
+import org.apache.stanbol.commons.owl.util.OWL2Constants;
 import org.apache.stanbol.commons.owl.util.OWLUtils;
 import org.apache.stanbol.commons.owl.util.URIUtils;
 import org.apache.stanbol.commons.web.base.ContextHelper;
@@ -306,6 +307,16 @@ public class OntoNetRootResource extends
             // remove old statement
             o.remove(t);
         }
+
+        // Versioning.
+        OWLOntologyID id = OWLUtils.extractOntologyID(o);
+        if (id != null && !id.isAnonymous() && id.getVersionIRI() == null) {
+            UriRef viri = new UriRef(requestUri.toString());
+            log.debug("Setting version IRI for export : {}", viri);
+            o.add(new TripleImpl(new UriRef(id.getOntologyIRI().toString()), 
new UriRef(
+                    OWL2Constants.OWL_VERSION_IRI), viri));
+        }
+
         log.debug("Exported as Clerezza Graph in {} ms. Handing over to 
writer.", System.currentTimeMillis()
                                                                                
   - before);
         return o;
@@ -566,7 +577,8 @@ public class OntoNetRootResource extends
                     InputStream content = new FileInputStream(file);
                     // ClerezzaOWLUtils.guessOntologyID(new 
FileInputStream(file), Parser.getInstance(), f);
                     OWLOntologyID guessed = OWLUtils.guessOntologyID(content, 
Parser.getInstance(), f);
-                    if (guessed != null && 
ontologyProvider.hasOntology(guessed)) {
+
+                    if (guessed != null && !guessed.isAnonymous() && 
ontologyProvider.hasOntology(guessed)) {
                         rb = Response.status(Status.CONFLICT);
                         this.submitted = guessed;
                         if 
(headers.getAcceptableMediaTypes().contains(MediaType.TEXT_HTML_TYPE)) {
@@ -591,7 +603,7 @@ public class OntoNetRootResource extends
                     log.debug(">>> FAILURE format {} (parse error)", f);
                     failed++;
                 }
-            } while ((key == null || key.isAnonymous()) && itf.hasNext());
+            } while ((key == null/* || key.isAnonymous() */) && itf.hasNext());
             if (key == null || key.isAnonymous() && rb == null) {
                 if (failed > 0) throw new WebApplicationException(BAD_REQUEST);
                 else if (unsupported > 0) throw new 
WebApplicationException(UNSUPPORTED_MEDIA_TYPE);
@@ -604,24 +616,26 @@ public class OntoNetRootResource extends
                 throw new WebApplicationException(e, BAD_REQUEST);
             }
         } else if (!aliases.isEmpty()) // No content but there are aliases.
-        for (Origin<?> origin : keys)
-            if (origin.getReference() instanceof OWLOntologyID) {
-                OWLOntologyID primary = ((OWLOntologyID) 
origin.getReference());
-                if (ontologyProvider.getStatus(primary) != 
org.apache.stanbol.ontologymanager.servicesapi.ontology.OntologyProvider.Status.NO_MATCH)
 for (OWLOntologyID alias : aliases)
-                    try {
-                        if (ontologyProvider.addAlias(primary, alias) && key 
== null) key = alias;
-                    } catch (IllegalArgumentException ex) {
-                        log.warn("Cannot add alias");
-                        log.warn(" ... ontology key: {}", primary);
-                        log.warn(" ... alias: {}", alias);
-                        log.warn(" ... reason: ", ex);
-                        continue;
-                    }
-            } else {
-                log.error("Bad request");
-                log.error(" file is: {}", file);
-                throw new WebApplicationException(BAD_REQUEST);
-            }
+        {
+            for (Origin<?> origin : keys)
+                if (origin.getReference() instanceof OWLOntologyID) {
+                    OWLOntologyID primary = ((OWLOntologyID) 
origin.getReference());
+                    if (ontologyProvider.getStatus(primary) != 
org.apache.stanbol.ontologymanager.servicesapi.ontology.OntologyProvider.Status.NO_MATCH)
 for (OWLOntologyID alias : aliases)
+                        try {
+                            if (ontologyProvider.addAlias(primary, alias) && 
key == null) key = alias;
+                        } catch (IllegalArgumentException ex) {
+                            log.warn("Cannot add alias");
+                            log.warn(" ... ontology key: {}", primary);
+                            log.warn(" ... alias: {}", alias);
+                            log.warn(" ... reason: ", ex);
+                            continue;
+                        }
+                }
+        } else {
+            log.error("Bad request");
+            log.error(" file is: {}", file);
+            throw new WebApplicationException(BAD_REQUEST);
+        }
 
         if (key != null && !key.isAnonymous()) {
             String uri = OntologyUtils.encode(key);


Reply via email to