use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.
the class SessionImpl method exportToOWLOntology.
/**
* TODO support merging for attached scopes as well?
*/
@Override
protected OWLOntology exportToOWLOntology(boolean merge, org.semanticweb.owlapi.model.IRI universalPrefix) {
OWLOntology o = super.exportToOWLOntology(merge, universalPrefix);
org.semanticweb.owlapi.model.IRI iri = o.getOntologyID().getOntologyIRI();
if (merge) {
// Re-merge
// FIXME try to avoid this.
ScopeManager onm = ScopeManagerImpl.get();
final Set<OWLOntology> set = new HashSet<OWLOntology>();
set.add(o);
for (String scopeID : attachedScopes) {
log.debug(" ... Merging with attached scope {}.", scopeID);
Scope sc = onm.getScope(scopeID);
if (sc != null)
set.add(sc.export(OWLOntology.class, merge));
for (OWLOntologyID ontologyId : managedOntologies) {
set.add(getOntology(ontologyId, OWLOntology.class, true));
}
OWLOntologySetProvider provider = new OWLOntologySetProvider() {
@Override
public Set<OWLOntology> getOntologies() {
return set;
}
};
OWLOntologyMerger merger = new OWLOntologyMerger(provider);
try {
o = merger.createMergedOntology(OWLManager.createOWLOntologyManager(), iri);
} catch (OWLOntologyCreationException e) {
log.error("Failed to merge imports for ontology " + iri, e);
o = null;
}
}
} else
attachScopeImportsOwlApi(o, universalPrefix);
return o;
}
use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.
the class ClerezzaOntologyProvider method loadInStore.
@Override
public OWLOntologyID loadInStore(Object ontology, final boolean force, Origin<?>... origins) {
if (ontology == null)
throw new IllegalArgumentException("No ontology supplied.");
checkReplaceability(origins);
long before = System.currentTimeMillis();
// The final graph
Graph targetGraph;
// The supplied ontology converted to Graph
Graph rdfData;
if (ontology instanceof OWLOntology) {
// This will be in memory!
rdfData = OWLAPIToClerezzaConverter.owlOntologyToClerezzaGraph((OWLOntology) ontology);
} else if (ontology instanceof Graph) {
// This might be in memory or in persistent storage.
rdfData = (Graph) ontology;
} else
throw new UnsupportedOperationException("This ontology provider can only accept objects assignable to " + Graph.class + " or " + OWLOntology.class);
// XXX Force is ignored for the content, but the imports?
// Now we proceed to assign the primary key to the ontology.
OWLOntologyID primaryKey = null;
/*
* Compute aliases
*/
IRI graphName = null;
// Priority aliases.
List<OWLOntologyID> overrides = new ArrayList<OWLOntologyID>();
// Second-choice aliases.
List<org.semanticweb.owlapi.model.IRI> sources = new ArrayList<org.semanticweb.owlapi.model.IRI>();
// Scan origins ONCE.
for (int i = 0; i < origins.length; i++) {
Origin<?> origin = origins[i];
log.debug("Found origin at index {}", i);
if (origin == null) {
log.warn("Null origin at index {}. Skipping.", i);
continue;
}
Object ref = origin.getReference();
if (ref == null) {
log.warn("Null reference at index {}. Skipping.", i);
continue;
}
log.debug(" ... Reference is a {}", ref.getClass().getCanonicalName());
log.debug(" ... Value : {}", ref);
if (ref instanceof OWLOntologyID) {
OWLOntologyID key = (OWLOntologyID) ref;
if (primaryKey == null) {
primaryKey = key;
log.debug(" ... assigned as primary key.");
} else if (primaryKey.equals(key)) {
log.debug(" ... matches primary key. Skipping.");
} else {
overrides.add(key);
log.debug(" ... assigned as a priority alias for {}", primaryKey);
}
} else if (ref instanceof org.semanticweb.owlapi.model.IRI) {
sources.add((org.semanticweb.owlapi.model.IRI) ref);
log.debug(" ... assigned as a secondary alias (source) for {}", primaryKey);
} else if (ref instanceof IRI) {
if (graphName != null)
log.warn("ImmutableGraph name already assigned as {}. Skipping.", graphName);
else {
graphName = (IRI) ref;
log.debug(" ... assigned as a graph name for {}", primaryKey);
}
} else {
log.warn("Unhandled type for origin at index {} : {}. Skipping.", i, ref.getClass());
}
}
// The actual logical ID will be dereferenceable no matter what.
OWLOntologyID extractedId = OWLUtils.extractOntologyID(rdfData);
if (// Not overridden: set as primary key.
primaryKey == null)
// Not overridden: set as primary key.
primaryKey = extractedId;
else
// Overridden: must be an alias anyway.
overrides.add(extractedId);
if (// No overrides, no extracted ID.
primaryKey == null) {
org.semanticweb.owlapi.model.IRI z;
// The first IRI found becomes the primary key.
if (!sources.isEmpty())
z = sources.iterator().next();
else // Try the graph name
if (graphName != null)
z = org.semanticweb.owlapi.model.IRI.create(graphName.getUnicodeString());
else
// Extrema ratio : compute a timestamped primary key.
z = org.semanticweb.owlapi.model.IRI.create(getClass().getCanonicalName() + "-time:" + System.currentTimeMillis());
primaryKey = new OWLOntologyID(z);
}
// Check if it is possible to avoid reloading the ontology content from its source.
boolean mustLoad = true;
if (!force && graphName != null && store.listGraphs().contains(graphName)) {
// Any failed check will abort the scan.
boolean condition = true;
// Check if the extracted ontology ID matches that of the supplied graph.
// XXX note that anonymous ontologies should be considered a match... or should they not?
Graph tc = store.getGraph(graphName);
OWLOntologyID idFromStore = OWLUtils.extractOntologyID(tc);
condition &= (extractedId == null && idFromStore == null) || extractedId.equals(idFromStore);
// FIXME not a good policy for graphs that change without altering the size.
if (condition && rdfData instanceof Graph)
condition &= tc.size() == rdfData.size();
mustLoad &= !condition;
}
if (!mustLoad && graphName != null) {
log.debug("ImmutableGraph with ID {} already in store. Default action is to skip storage.", graphName);
targetGraph = store.getGraph(graphName);
} else {
String iri = null;
if (primaryKey.getOntologyIRI() != null)
iri = primaryKey.getOntologyIRI().toString();
if (primaryKey.getVersionIRI() != null)
iri += ":::" + primaryKey.getVersionIRI().toString();
// s will become the graph name
String s = (iri.startsWith(prefix + "::")) ? "" : (prefix + "::");
s += iri;
graphName = new IRI(URIUtils.sanitize(s));
log.debug("Storing ontology with graph ID {}", graphName);
try {
targetGraph = store.createGraph(graphName);
} catch (EntityAlreadyExistsException e) {
if (graphName.equals(e.getEntityName()))
targetGraph = store.getGraph(graphName);
else
targetGraph = store.createGraph(graphName);
}
targetGraph.addAll(rdfData);
}
// All is already sanitized by the time we get here.
// Now do the mappings
String mappedIds = "";
// Discard unconventional ontology IDs with only the version IRI
if (primaryKey != null && primaryKey.getOntologyIRI() != null) {
// Versioned or not, the real ID mapping is always added
keymap.setMapping(primaryKey, graphName);
mappedIds += primaryKey;
// TODO map unversioned ID as well?
Triple t = new TripleImpl(keymap.buildResource(primaryKey), SIZE_IN_TRIPLES_URIREF, LiteralFactory.getInstance().createTypedLiteral(Integer.valueOf(rdfData.size())));
getMetaGraph(Graph.class).add(t);
}
// Add aliases.
for (org.semanticweb.owlapi.model.IRI source : sources) if (source != null)
overrides.add(new OWLOntologyID(source));
for (OWLOntologyID alias : overrides) if (alias != null && !alias.equals(primaryKey)) {
addAlias(primaryKey, alias);
mappedIds += " , " + alias;
}
// Do this AFTER registering the ontology, otherwise import cycles will cause infinite loops.
if (resolveImports) {
// Scan resources of type owl:Ontology, but only get the first.
Iterator<Triple> it = targetGraph.filter(null, RDF.type, OWL.Ontology);
if (it.hasNext()) {
// Scan import statements for the one owl:Ontology considered.
Iterator<Triple> it2 = targetGraph.filter(it.next().getSubject(), OWL.imports, null);
while (it2.hasNext()) {
RDFTerm obj = it2.next().getObject();
log.info("Resolving import target {}", obj);
if (obj instanceof IRI)
try {
// TODO try locals first
IRI target = (IRI) obj;
OWLOntologyID id = new OWLOntologyID(org.semanticweb.owlapi.model.IRI.create(target.getUnicodeString()));
if (keymap.getMapping(id) == null) {
// Check if it's not there already.
if (isOfflineMode())
throw new RuntimeException("Cannot load imported ontology " + obj + " while Stanbol is in offline mode.");
// TODO manage origins for imported ontologies too?
OWLOntologyID id2 = loadInStore(org.semanticweb.owlapi.model.IRI.create(((IRI) obj).getUnicodeString()), null, false);
if (id2 != null)
id = id2;
log.info("Import {} resolved.", obj);
log.debug("");
} else {
log.info("Requested import already stored. Setting dependency only.");
}
descriptor.setDependency(primaryKey, id);
} catch (UnsupportedFormatException e) {
log.warn("Failed to parse format for resource " + obj, e);
// / XXX configure to continue?
} catch (IOException e) {
log.warn("Failed to load ontology from resource " + obj, e);
// / XXX configure to continue?
}
}
}
}
log.debug(" Ontology {}", mappedIds);
if (targetGraph != null)
log.debug(" ... ({} triples)", targetGraph.size());
log.debug(" ... primary public key : {}", primaryKey);
// log.debug("--- {}", URIUtils.sanitize(s));
log.debug("Time: {} ms", (System.currentTimeMillis() - before));
// return URIUtils.sanitize(s);
return primaryKey;
}
use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.
the class RegistryManagerImpl method activate.
protected void activate(Dictionary<String, Object> configuration) {
// Parse configuration.
try {
lazyLoading = (Boolean) (configuration.get(RegistryManager.LAZY_LOADING));
} catch (Exception ex) {
lazyLoading = _LAZY_LOADING_DEFAULT;
}
try {
retainIncomplete = (Boolean) (configuration.get(RegistryManager.RETAIN_INCOMPLETE));
} catch (Exception ex) {
retainIncomplete = _RETAIN_INCOMPLETE_DEFAULT;
}
Object obj = configuration.get(RegistryManager.REGISTRY_LOCATIONS);
if (obj instanceof String[])
locations = (String[]) obj;
else if (obj instanceof String)
locations = new String[] { (String) obj };
if (locations == null)
locations = new String[] { "stanbol_network.owl" };
Object cachingPolicy = configuration.get(RegistryManager.CACHING_POLICY);
if (cachingPolicy == null) {
this.cachingPolicyString = _CACHING_POLICY_DEFAULT.name();
} else {
this.cachingPolicyString = cachingPolicy.toString();
}
final IRI[] offlineResources;
if (this.offline != null) {
List<IRI> paths = offline.getOntologySourceLocations();
if (paths != null)
offlineResources = paths.toArray(new IRI[0]);
else
// There are no offline paths.
offlineResources = new IRI[0];
} else
// There's no offline configuration at all.
offlineResources = new IRI[0];
// Used only for creating the registry model, do not use for caching.
OWLOntologyManager mgr = OWLOntologyManagerFactory.createOWLOntologyManager(offlineResources);
OWLOntologyLoaderConfiguration conf = new OWLOntologyLoaderConfiguration();
// If we are retaining incomplete registries, do not throw exceptions if imports fail.
conf.setSilentMissingImportsHandling(retainIncomplete);
// Load registries
Set<OWLOntology> regOnts = new HashSet<OWLOntology>();
for (String loc : locations) {
try {
IRI iri = IRI.create(loc);
OWLOntologyDocumentSource src = null;
OWLOntology o = null;
if (iri.isAbsolute())
src = new IRIDocumentSource(iri);
else {
// Relative IRI : use data file provider
log.debug("Found relative IRI {} . Will try to retrieve from data file providers.", iri);
Map<String, String> info = new HashMap<String, String>();
if (dataFileProvider != null && dataFileProvider.isAvailable(null, loc, info))
src = new StreamDocumentSource(dataFileProvider.getInputStream(null, loc, info));
}
if (src != null)
o = mgr.loadOntologyFromOntologyDocument(src, conf);
if (o != null)
regOnts.add(o);
else
log.warn("Failed to obtain OWL ontology from resource {}", loc);
} catch (OWLOntologyAlreadyExistsException e) {
log.info("Skipping cached ontology {}.", e.getOntologyID());
continue;
} catch (OWLOntologyCreationException e) {
log.warn("Failed to load ontology " + loc + " - Skipping...", e);
continue;
} catch (Exception e) {
log.warn("Invalid registry configuration " + loc + " - Skipping...", e);
continue;
}
}
// Create and set the cache.
if (cachingPolicyString.equals(CachingPolicy.CENTRALISED.name())) {
// this.cache = OWLOntologyManagerFactory.createOWLOntologyManager(offlineResources);
if (cache == null) {
log.warn("Caching policy is set as Centralised, but no ontology provider is supplied. Will use new in-memory tcProvider.");
cache = new ClerezzaOntologyProvider(TcManager.getInstance(), offline, Parser.getInstance());
}
// else sta bene cosi'
} else if (cachingPolicyString.equals(CachingPolicy.DISTRIBUTED.name())) {
this.cache = null;
}
riFactory = new RegistryItemFactoryImpl(cache);
// Build the model.
createModel(regOnts);
// Set the cache on libraries.
Set<RegistryItem> visited = new HashSet<RegistryItem>();
for (Registry reg : getRegistries()) for (RegistryItem child : reg.getChildren()) if (!visited.contains(child)) {
if (child instanceof Library) {
if (this.cache != null)
((Library) child).setCache(this.cache);
else
((Library) child).setCache(new ClerezzaOntologyProvider(TcManager.getInstance(), offline, Parser.getInstance()));
}
visited.add(child);
}
if (isLazyLoading()) {
// Nothing to do about it at the moment.
} else {
loadEager();
}
}
use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.
the class RegistryManagerImpl method populateLibrary.
protected Library populateLibrary(OWLNamedObject ind, Set<OWLOntology> registries) throws RegistryContentException {
IRI libId = ind.getIRI();
RegistryItem lib = null;
if (population.containsKey(libId)) {
// We are not allowing multityping either.
lib = population.get(libId);
if (!(lib instanceof Library))
throw new RegistryContentException("Inconsistent multityping: for item " + libId + " : {" + Library.class + ", " + lib.getClass() + "}");
} else {
lib = riFactory.createLibrary(ind);
try {
population.put(lib.getIRI(), lib);
} catch (Exception e) {
log.error("Invalid identifier for library item " + lib, e);
return null;
}
}
// EXIT nodes.
Set<OWLNamedObject> ironts = new HashSet<OWLNamedObject>();
OWLDataFactory df = OWLManager.getOWLDataFactory();
for (OWLOntology o : registries) {
if (ind instanceof OWLIndividual) {
// Get usages of hasOntology as an object property
for (OWLIndividual value : ((OWLIndividual) ind).getObjectPropertyValues(hasOntology, o)) if (value.isNamed())
ironts.add(value.asOWLNamedIndividual());
// Get usages of hasOntology as an annotation property
for (OWLAnnotationAssertionAxiom ann : o.getAnnotationAssertionAxioms(ind.getIRI())) if (hasOntologyAnn.equals(ann.getProperty())) {
OWLAnnotationValue value = ann.getValue();
if (value instanceof OWLNamedObject)
ironts.add((OWLNamedObject) value);
else if (value instanceof IRI)
ironts.add(df.getOWLNamedIndividual((IRI) value));
}
}
}
for (OWLNamedObject iront : ironts) {
IRI childId = iront.getIRI();
// If some populate*() method has created it, it will be there.
RegistryItem ront = population.get(childId);
// Otherwise populating it will also put it in population.
if (ront == null)
ront = populateOntology(iront, registries);
lib.addChild(ront);
if (ontologyIndex.get(childId) == null)
ontologyIndex.put(childId, new HashSet<IRI>());
ontologyIndex.get(childId).add(libId);
}
return (Library) lib;
}
use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.
the class RegistryManagerImpl method populateRegistry.
protected Registry populateRegistry(OWLOntology registry) throws RegistryContentException {
log.debug("Populating registry content from ontology {}", registry);
Registry reg = riFactory.createRegistry(registry);
Set<OWLOntology> closure = registry.getOWLOntologyManager().getImportsClosure(registry);
// Just scan all individuals. Recurse in case the registry imports more registries.
for (OWLIndividual ind : registry.getIndividualsInSignature(true)) {
// We do not allow anonymous registry items.
if (ind.isAnonymous())
continue;
RegistryItem item = null;
// IRI id = ind.asOWLNamedIndividual().getIRI();
Type t = RegistryUtils.getType(ind, closure);
if (t == null) {
log.warn("Undetermined type for registry ontology individual {}", ind);
continue;
}
switch(t) {
case LIBRARY:
log.debug("Found library for individual {}", ind);
// Create the library and attach to parent and children
item = populateLibrary(ind.asOWLNamedIndividual(), closure);
reg.addChild(item);
item.addRegistryContentListener(this);
break;
case ONTOLOGY:
log.debug("Found ontology for individual {}", ind);
// Create the ontology and attach to parent
item = populateOntology(ind.asOWLNamedIndividual(), closure);
item.addRegistryContentListener(this);
// We don't know where to attach it within this method.
break;
default:
break;
}
}
try {
reg.addRegistryContentListener(this);
log.info("Registry {} added.", reg.getIRI());
population.put(reg.getIRI(), reg);
} catch (Exception e) {
log.error("Invalid identifier for library item " + reg, e);
return null;
}
return reg;
}
Aggregations