use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.
the class TestOntologyReconciliation method namedFromURL.
/*
* Named ontologies loaded from an URL must reconcile with both their logical ID and their resource URL
* (through aliasing).
*/
@Test
public void namedFromURL() throws Exception {
String location = "/ontologies/naming/named-1.owl";
OWLOntologyID expectedId = new OWLOntologyID(IRI.create("http://stanbol.apache.org/ontologies/test/naming/named-1"));
URL url = getClass().getResource(location);
OWLOntologyManager onMgr = OWLManager.createOWLOntologyManager();
OWLOntology o1 = onMgr.loadOntologyFromOntologyDocument(IRI.create(url));
assertFalse(o1.isAnonymous());
assertEquals(expectedId, o1.getOntologyID());
// in = getClass().getResourceAsStream(location); // use if stream cannot be reset
OWLOntologyID key = ontologyProvider.loadInStore(IRI.create(url), RDF_XML, false);
assertNotNull(key);
assertFalse(key.isAnonymous());
log.info("Named ontology loaded with public key {}", key);
assertEquals(expectedId, key);
log.info(" -- (matches actual ontology ID).");
OWLOntology o1_1 = ontologyProvider.getStoredOntology(key, OWLOntology.class, false);
assertFalse(o1_1.isAnonymous());
// Cannot equal OWLOntology objects
assertEquals(expectedId, o1_1.getOntologyID());
// Check that axioms match
log.warn("Plain OWL API seems to be failing to preserve owl:versionInfo. Will test non-annotation axioms only.");
assertEquals(o1.getTBoxAxioms(false), o1_1.getTBoxAxioms(false));
log.info(" -- TBox axiom check successful.");
assertEquals(o1.getABoxAxioms(false), o1_1.getABoxAxioms(false));
log.info(" -- ABox axiom check successful.");
// Now check the alias from the physical URL
OWLOntologyID aliasId = new OWLOntologyID(IRI.create(url));
Set<OWLOntologyID> aliases = ontologyProvider.listAliases(expectedId);
assertSame(1, aliases.size());
assertTrue(aliases.contains(aliasId));
// Check that it actually *is* an alias
OWLOntology alias = ontologyProvider.getStoredOntology(aliasId, OWLOntology.class);
assertNotNull(alias);
assertEquals(expectedId, alias.getOntologyID());
// Both ontologies come from the ontology provider and should have preserved ontology annotations.
// Therefore ass axioms should match safely.
assertEquals(o1_1.getAxioms(), alias.getAxioms());
}
use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.
the class RuleListWriter method writeTo.
@Override
public void writeTo(RuleList ruleList, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType mediaType, MultivaluedMap<String, Object> arg5, OutputStream out) throws IOException, WebApplicationException {
Logger log = LoggerFactory.getLogger(getClass());
log.debug("Rendering the list of recipes.");
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLDataFactory factory = OWLManager.getOWLDataFactory();
OWLOntology ontology;
try {
ontology = manager.createOntology();
String recipeClassURI = Symbols.Recipe.toString().replace("<", "").replace(">", "");
IRI recipeClassIRI = IRI.create(recipeClassURI);
OWLClass owlRecipeClass = factory.getOWLClass(recipeClassIRI);
String ruleClassURI = Symbols.Rule.toString().replace("<", "").replace(">", "");
IRI ruleClassIRI = IRI.create(ruleClassURI);
OWLClass owlRuleClass = factory.getOWLClass(ruleClassIRI);
String descriptionURI = Symbols.description.toString().replace("<", "").replace(">", "");
IRI descriptionIRI = IRI.create(descriptionURI);
OWLDataProperty descriptionProperty = factory.getOWLDataProperty(descriptionIRI);
String hasRuleURI = Symbols.hasRule.toString().replace("<", "").replace(">", "");
IRI hasRuleIRI = IRI.create(hasRuleURI);
OWLObjectProperty hasRule = factory.getOWLObjectProperty(hasRuleIRI);
String ruleBodyURI = Symbols.ruleBody.toString().replace("<", "").replace(">", "");
IRI ruleBodyIRI = IRI.create(ruleBodyURI);
OWLDataProperty ruleBody = factory.getOWLDataProperty(ruleBodyIRI);
String ruleHeadURI = Symbols.ruleHead.toString().replace("<", "").replace(">", "");
IRI ruleHeadIRI = IRI.create(ruleHeadURI);
OWLDataProperty ruleHead = factory.getOWLDataProperty(ruleHeadIRI);
if (ruleList != null) {
for (Rule rule : ruleList) {
String recipeId = rule.getRecipe().getRecipeID().toString().replace("<", "").replace(">", "");
IRI reicpeIRI = IRI.create(recipeId);
OWLIndividual owlRecipe = factory.getOWLNamedIndividual(reicpeIRI);
String ruleId = rule.getRuleID().toString().replace("<", "").replace(">", "");
IRI ruleIRI = IRI.create(ruleId);
OWLIndividual owlRule = factory.getOWLNamedIndividual(ruleIRI);
OWLAxiom axiom = factory.getOWLClassAssertionAxiom(owlRecipeClass, owlRecipe);
manager.addAxiom(ontology, axiom);
axiom = factory.getOWLClassAssertionAxiom(owlRuleClass, owlRule);
manager.addAxiom(ontology, axiom);
axiom = factory.getOWLObjectPropertyAssertionAxiom(hasRule, owlRecipe, owlRule);
manager.addAxiom(ontology, axiom);
String recipeDescription = rule.getRecipe().getRecipeDescription();
String ruleDescription = rule.getDescription();
if (recipeDescription != null) {
axiom = factory.getOWLDataPropertyAssertionAxiom(descriptionProperty, owlRecipe, recipeDescription);
manager.addAxiom(ontology, axiom);
}
if (ruleDescription != null) {
axiom = factory.getOWLDataPropertyAssertionAxiom(descriptionProperty, owlRule, ruleDescription);
manager.addAxiom(ontology, axiom);
}
String ruleContent = rule.toString();
String[] parts = ruleContent.split("\\->");
axiom = factory.getOWLDataPropertyAssertionAxiom(ruleBody, owlRule, parts[0]);
manager.addAxiom(ontology, axiom);
axiom = factory.getOWLDataPropertyAssertionAxiom(ruleHead, owlRule, parts[1]);
manager.addAxiom(ontology, axiom);
}
}
if (mediaType.toString().equals(KRFormat.RDF_XML)) {
try {
manager.saveOntology(ontology, new RDFXMLOntologyFormat(), out);
} catch (OWLOntologyStorageException e) {
log.error("Failed to store ontology for rendering.", e);
}
} else if (mediaType.toString().equals(KRFormat.OWL_XML)) {
try {
manager.saveOntology(ontology, new OWLXMLOntologyFormat(), out);
} catch (OWLOntologyStorageException e) {
log.error("Failed to store ontology for rendering.", e);
}
} else if (mediaType.toString().equals(KRFormat.MANCHESTER_OWL)) {
try {
manager.saveOntology(ontology, new ManchesterOWLSyntaxOntologyFormat(), out);
} catch (OWLOntologyStorageException e) {
log.error("Failed to store ontology for rendering.", e);
}
} else if (mediaType.toString().equals(KRFormat.FUNCTIONAL_OWL)) {
try {
manager.saveOntology(ontology, new OWLFunctionalSyntaxOntologyFormat(), out);
} catch (OWLOntologyStorageException e) {
log.error("Failed to store ontology for rendering.", e);
}
} else if (mediaType.toString().equals(KRFormat.TURTLE)) {
try {
manager.saveOntology(ontology, new TurtleOntologyFormat(), out);
} catch (OWLOntologyStorageException e) {
log.error("Failed to store ontology for rendering.", e);
}
} else if (mediaType.toString().equals(KRFormat.RDF_JSON)) {
Graph mGraph = OWLAPIToClerezzaConverter.owlOntologyToClerezzaGraph(ontology);
RdfJsonSerializingProvider provider = new RdfJsonSerializingProvider();
provider.serialize(out, mGraph, SupportedFormat.RDF_JSON);
}
} catch (OWLOntologyCreationException e1) {
log.error("An error occurred.", e1);
}
out.flush();
}
use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.
the class RefactorResource method applyRefactoring.
// public RefactorResource(@Context ServletContext servletContext) {
// refactorer = (Refactorer) ContextHelper.getServiceFromContext(Refactorer.class, servletContext);
// if (refactorer == null) throw new IllegalStateException("Refactorer missing in ServletContext");
// ruleStore = (RuleStore) ContextHelper.getServiceFromContext(RuleStore.class, servletContext);
// if (ruleStore == null) throw new IllegalStateException("RuleStore missing in ServletContext");
// }
/**
* The apply mode allows the client to compose a recipe, by mean of string containg the rules, and apply
* it "on the fly" to the graph in input.
*
* @param recipe
* String
* @param input
* InputStream
* @return a Response containing the transformed graph
*/
@POST
@Path("/apply")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(value = { TURTLE, RDF_XML, MANCHESTER_OWL, FUNCTIONAL_OWL, OWL_XML, RDF_JSON, X_TURTLE })
public Response applyRefactoring(MultiPartBody data, @Context HttpHeaders headers) {
String recipe = null;
InputStream input = null;
if (data.getTextParameterValues(recipe) != null) {
recipe = data.getTextParameterValues(recipe)[0];
}
if (data.getFormFileParameterValues("input") != null) {
input = new ByteArrayInputStream(data.getFormFileParameterValues("input")[0].getContent());
}
if (recipe == null || input == null) {
throw new WebApplicationException(BAD_REQUEST);
}
ResponseBuilder rb;
OWLOntology output = null;
try {
output = doRefactoring(input, RuleParserImpl.parse("http://incubator.apache.com/stanbol/rules/refactor/", recipe));
} catch (OWLOntologyCreationException e1) {
throw new WebApplicationException(e1, INTERNAL_SERVER_ERROR);
} catch (RefactoringException e1) {
throw new WebApplicationException(e1, BAD_REQUEST);
}
if (output != null) {
rb = Response.ok(output);
MediaType mediaType = MediaTypeUtil.getAcceptableMediaType(headers, null);
if (mediaType != null)
rb.header(HttpHeaders.CONTENT_TYPE, mediaType);
} else
rb = Response.status(NOT_FOUND);
// addCORSOrigin(servletContext, rb, headers);
return rb.build();
}
use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.
the class RefactorEnhancementEngine method computeEnhancements.
@Override
public void computeEnhancements(ContentItem ci) throws EngineException {
// Prepare the OntoNet environment. First we create the OntoNet session in which run the whole
final Session session;
try {
session = sessionManager.createSession();
} catch (SessionLimitException e1) {
throw new EngineException("OntoNet session quota reached. The Refactor Engine requires its own new session to execute.");
}
if (session == null)
throw new EngineException("Failed to create OntoNet session. The Refactor Engine requires its own new session to execute.");
log.debug("Refactor enhancement job will run in session '{}'.", session.getID());
// Retrieve and filter the metadata graph for entities recognized by the engines.
final Graph metadataGraph = ci.getMetadata(), signaturesGraph = new IndexedGraph();
// FIXME the Stanbol Enhancer vocabulary should be retrieved from somewhere in the enhancer API.
final IRI ENHANCER_ENTITY_REFERENCE = new IRI("http://fise.iks-project.eu/ontology/entity-reference");
Iterator<Triple> tripleIt = metadataGraph.filter(null, ENHANCER_ENTITY_REFERENCE, null);
while (tripleIt.hasNext()) {
// Get the entity URI
RDFTerm obj = tripleIt.next().getObject();
if (!(obj instanceof IRI)) {
log.warn("Invalid IRI for entity reference {}. Skipping.", obj);
continue;
}
final String entityReference = ((IRI) obj).getUnicodeString();
log.debug("Trying to resolve entity {}", entityReference);
// Populate the entity signatures graph, by querying either the Entity Hub or the dereferencer.
if (engineConfiguration.isEntityHubUsed()) {
Graph result = populateWithEntity(entityReference, signaturesGraph);
if (result != signaturesGraph && result != null) {
log.warn("Entity Hub query added triples to a new graph instead of populating the supplied one!" + " New signatures will be discarded.");
}
} else
try {
OntologyInputSource<Graph> source = new GraphContentSourceWithPhysicalIRI(dereferencer.resolve(entityReference), org.semanticweb.owlapi.model.IRI.create(entityReference));
signaturesGraph.addAll(source.getRootOntology());
} catch (FileNotFoundException e) {
log.error("Failed to dereference entity " + entityReference + ". Skipping.", e);
continue;
}
}
try {
/*
* The dedicated session for this job will store the following: (1) all the (merged) signatures
* for all detected entities; (2) the original content metadata graph returned earlier in the
* chain.
*
* There is no chance that (2) could be null, as it was previously controlled by the JobManager
* through the canEnhance() method and the computeEnhancement is always called iff the former
* returns true.
*/
session.addOntology(new GraphSource(signaturesGraph));
session.addOntology(new GraphSource(metadataGraph));
} catch (UnmodifiableOntologyCollectorException e1) {
throw new EngineException("Cannot add enhancement graph to OntoNet session for refactoring", e1);
}
try {
/*
* Export the entire session (incl. entities and enhancement graph) as a single merged ontology.
*
* TODO the refactorer should have methods to accommodate an OntologyCollector directly instead.
*/
OWLOntology ontology = session.export(OWLOntology.class, true);
log.debug("Refactoring recipe IRI is : " + engineConfiguration.getRecipeId());
/*
* We pass the ontology and the recipe IRI to the Refactor that returns the refactored graph
* expressed by using the given vocabulary.
*
* To perform the refactoring of the ontology to a given vocabulary we use the Stanbol Refactor.
*/
Recipe recipe = ruleStore.getRecipe(new IRI(engineConfiguration.getRecipeId()));
log.debug("Recipe {} contains {} rules.", recipe, recipe.getRuleList().size());
log.debug("The ontology to be refactor is {}", ontology);
Graph tc = refactorer.graphRefactoring(OWLAPIToClerezzaConverter.owlOntologyToClerezzaGraph(ontology), recipe);
/*
* The newly generated ontology is converted to Clarezza format and then added os substitued to
* the old mGraph.
*/
if (engineConfiguration.isInGraphAppendMode()) {
log.debug("Metadata of the content will replace old ones.", this);
} else {
metadataGraph.clear();
log.debug("Content metadata will be appended to the existing ones.", this);
}
metadataGraph.addAll(tc);
} catch (RefactoringException e) {
String msg = "Refactor engine execution failed on content item " + ci + ".";
log.error(msg, e);
throw new EngineException(msg, e);
} catch (NoSuchRecipeException e) {
String msg = "Refactor engine could not find recipe " + engineConfiguration.getRecipeId() + " to refactor content item " + ci + ".";
log.error(msg, e);
throw new EngineException(msg, e);
} catch (Exception e) {
throw new EngineException("Refactor Engine has failed.", e);
} finally {
/*
* The session needs to be destroyed anyhow.
*
* Clear contents before destroying (FIXME only do this until this is implemented in the
* destroySession() method).
*/
for (OWLOntologyID id : session.listManagedOntologies()) {
try {
String key = ontologyProvider.getKey(id.getOntologyIRI());
ontologyProvider.getStore().deleteGraph(new IRI(key));
} catch (Exception ex) {
log.error("Failed to delete triple collection " + id, ex);
continue;
}
}
sessionManager.destroySession(session.getID());
}
}
use of org.semanticweb.owlapi.model.OWLOntology in project stanbol by apache.
the class UrlInputProvider method getInput.
@Override
public <T> Iterator<T> getInput(Class<T> type) throws IOException {
if (type.isAssignableFrom(OWLAxiom.class)) {
// We add additional axioms
OWLOntology fromUrl;
try {
fromUrl = createOWLOntologyManager().loadOntologyFromOntologyDocument(IRI.create(url));
} catch (OWLOntologyCreationException e) {
throw new IOException(e);
}
Set<OWLOntology> all = fromUrl.getImportsClosure();
List<OWLAxiom> axiomList = new ArrayList<OWLAxiom>();
for (OWLOntology o : all) {
axiomList.addAll(o.getAxioms());
}
final Iterator<OWLAxiom> iterator = axiomList.iterator();
return new Iterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@SuppressWarnings("unchecked")
@Override
public T next() {
return (T) iterator.next();
}
@Override
public void remove() {
// This iterator is read-only
throw new UnsupportedOperationException("Cannot remove statements from the iterator");
}
};
} else if (type.isAssignableFrom(Statement.class)) {
final OntModel input = ModelFactory.createOntologyModel();
synchronized (url) {
// FIXME: use instead:
// FileManager.get().loadModel
input.read(url);
}
final StmtIterator iterator = input.listStatements();
return new Iterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@SuppressWarnings("unchecked")
@Override
public T next() {
return (T) iterator.next();
}
@Override
public void remove() {
// This iterator is read-only
throw new UnsupportedOperationException("Cannot remove statements from the iterator");
}
};
} else {
throw new UnsupportedOperationException("This provider does not adapt to the given type");
}
}
Aggregations