use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.
the class JenaToOwlConvert method EntityOwlToJenaResource.
// //////////////////////////////////////////////////////////////////////////////
/**
* This function converts any thingths relatives to an OWL entity in an iterator over Jena statement
*
* @param entity
* {It could be a class, an object property or a data property}
* @param owlmodel
* {OWLOntology model where to retrieve information about the entity}
* @param format
* {RDF/XML or TURTLE}
* @return {An iterator over jena statement}
*/
public synchronized StmtIterator EntityOwlToJenaResource(OWLEntity entity, OWLOntology owlmodel, String format) {
while (available == false) {
try {
wait();
} catch (InterruptedException e) {
System.err.println("EntityOwlToJenaResource::: " + e);
}
}
available = false;
try {
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology = manager.createOntology(IRI.create("http://www.semanticweb.org/owlapi/ontologies/ontology"));
// If the entity is a class
if (entity.isOWLClass()) {
OWLClass owldata = entity.asOWLClass();
Iterator<OWLClassAxiom> entityaxiom = owlmodel.getAxioms(owldata).iterator();
while (entityaxiom.hasNext()) manager.addAxiom(ontology, entityaxiom.next());
Iterator<OWLAnnotationAssertionAxiom> annotations = entity.getAnnotationAssertionAxioms(owlmodel).iterator();
while (annotations.hasNext()) manager.addAxiom(ontology, annotations.next());
}
// If the entity is a data property
if (entity.isOWLDataProperty()) {
OWLDataProperty owldata = entity.asOWLDataProperty();
Iterator<OWLDataPropertyAxiom> entityaxiom = owlmodel.getAxioms(owldata).iterator();
while (entityaxiom.hasNext()) manager.addAxiom(ontology, entityaxiom.next());
Iterator<OWLAnnotationAssertionAxiom> annotations = entity.getAnnotationAssertionAxioms(owlmodel).iterator();
while (annotations.hasNext()) manager.addAxiom(ontology, annotations.next());
}
// If the entity is an object property
if (entity.isOWLObjectProperty()) {
OWLObjectProperty owldata = entity.asOWLObjectProperty();
Iterator<OWLObjectPropertyAxiom> entityaxiom = owlmodel.getAxioms(owldata).iterator();
while (entityaxiom.hasNext()) manager.addAxiom(ontology, entityaxiom.next());
Iterator<OWLAnnotationAssertionAxiom> annotations = entity.getAnnotationAssertionAxioms(owlmodel).iterator();
while (annotations.hasNext()) manager.addAxiom(ontology, annotations.next());
}
// If the entity is a data type
if (entity.isOWLDatatype()) {
OWLDatatype owldata = entity.asOWLDatatype();
Iterator<OWLDatatypeDefinitionAxiom> entityaxiom = owlmodel.getAxioms(owldata).iterator();
while (entityaxiom.hasNext()) manager.addAxiom(ontology, entityaxiom.next());
Iterator<OWLAnnotationAssertionAxiom> annotations = entity.getAnnotationAssertionAxioms(owlmodel).iterator();
while (annotations.hasNext()) manager.addAxiom(ontology, annotations.next());
}
// If the entity is an individual
if (entity.isOWLNamedIndividual()) {
OWLNamedIndividual owldata = entity.asOWLNamedIndividual();
Iterator<OWLIndividualAxiom> entityaxiom = owlmodel.getAxioms(owldata).iterator();
while (entityaxiom.hasNext()) manager.addAxiom(ontology, entityaxiom.next());
Iterator<OWLAnnotationAssertionAxiom> annotations = entity.getAnnotationAssertionAxioms(owlmodel).iterator();
while (annotations.hasNext()) manager.addAxiom(ontology, annotations.next());
}
// If the entity is an annotations property
if (entity.isOWLAnnotationProperty()) {
OWLAnnotationProperty owldata = entity.asOWLAnnotationProperty();
Iterator<OWLAnnotationAxiom> entityaxiom = owlmodel.getAxioms(owldata).iterator();
while (entityaxiom.hasNext()) manager.addAxiom(ontology, entityaxiom.next());
Iterator<OWLAnnotationAssertionAxiom> annotations = entity.getAnnotationAssertionAxioms(owlmodel).iterator();
while (annotations.hasNext()) manager.addAxiom(ontology, annotations.next());
}
OntModel ontmodel = ModelOwlToJenaConvert(ontology, format);
StmtIterator statement = ontmodel.listStatements();
available = true;
notifyAll();
return statement;
} catch (OWLOntologyCreationException eoc) {
System.err.print("EntityOwlToJenaResource::: ");
eoc.printStackTrace();
return null;
}
}
use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.
the class ScopeSetRenderer method getScopes.
public static OWLOntology getScopes(Set<Scope> 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 (Scope scope : scopes) {
OWLNamedIndividual iScope = __factory.getOWLNamedIndividual(IRI.create(scope.getDefaultNamespace() + scope.getID()));
OWLAxiom ax = __factory.getOWLClassAssertionAxiom(cScope, iScope);
additions.add(new AddAxiom(ont, ax));
}
mgr.applyChanges(additions);
return ont;
}
use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.
the class CustomSpaceImpl method getOntologyAsOWLOntology.
@Override
protected OWLOntology getOntologyAsOWLOntology(OWLOntologyID ontologyId, boolean merge, org.semanticweb.owlapi.model.IRI universalPrefix) {
OWLOntology o = super.getOntologyAsOWLOntology(ontologyId, merge, universalPrefix);
switch(getConnectivityPolicy()) {
case LOOSE:
break;
case TIGHT:
String s = getID();
// strip "custom"
s = s.substring(0, s.indexOf(SUFFIX));
// concatenate "core"
s += SpaceType.CORE.getIRISuffix();
org.semanticweb.owlapi.model.IRI target = org.semanticweb.owlapi.model.IRI.create(universalPrefix + s);
o.getOWLOntologyManager().applyChange(new AddImport(o, OWLManager.getOWLDataFactory().getOWLImportsDeclaration(target)));
break;
default:
break;
}
return o;
}
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;
}
Aggregations