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