Remove ontology annotation using OWLAPI - java

I am trying to remove some literal Annotations from an ontology using OWLAPI version 4.0.2 (from Maven)
In this purpose I am using the RemoveOntologyAnnotation class and the manager applyChange() method.
Here is the (simplified) code I use:
OWLOntologyManager m = OWLManager.createOWLOntologyManager();
OWLOntology ontology = null;
File ontologyFile = new File(ontologyFileName);
try {
ontology = m.loadOntologyFromOntologyDocument(ontologyFile);
} catch (OWLOntologyCreationException e) {
e.printStackTrace();
}
for (OWLClass cls : ontology.getClassesInSignature()) {
for (OWLAnnotation annotation : EntitySearcher.getAnnotations(cls.getIRI(), ontology)) {
if (annotation.getValue() instanceof OWLLiteral) {
RemoveOntologyAnnotation rm = new RemoveOntologyAnnotation(ontology, annotation);
System.out.println(m.applyChange(rm));
}
}
}
The applyChange() method is always returning "UNSUCCESSFULLY"
And I could not find any documentation about why the annotation removing don't work.
N.B.: found some indications here http://sourceforge.net/p/owlapi/mailman/message/28203984/
Where it seems to work

As also noted in the mailing list thread linked in your question, annotations on ontologies and annotations on ontology elements are two different things.
RemoveOntologyAnnotation only removes annotations on the ontology itself.
Annotations on elements are represented using axioms, specifically OWLAnnotationAssertionAxioms: Consequently, they have to be removed using OWLOntologyManager.removeAxiom() or similar means:
for (OWLClass cls : ontology.getClassesInSignature()) {
for (OWLAnnotationAssertionAxiom annAx : EntitySearcher.getAnnotationAssertionAxioms(cls.getIRI(), ontology)) {
if (annAx.getValue().getValue() instanceof OWLLiteral) {
m.removeAxiom(annAx);
}
}
}

Related

Unable to read OWL axioms

I am reading the attached university-bench ontology file (which I generated from UBA1.7 lubm) in java using owlapi. But it is not reading any axiom like subclass etc. And it is also not giving me any error. Can anyone tell me what I am doing wrong. The below code I used to retrieve the subclass axioms from this ontology but it return me nothing/ blank output. I wanted to output subclass, disjoint class, sub property, disjoint property, anonymous superclass axioms. but currently I am unable to get anything out from the ontology.
When I use the ontology which is created by me using protege. The below code works fine. But when i try to execute the ontology generated from UBA1.7 it gives me nothing.
public static void axioms(File ontology) throws OWLOntologyCreationException {
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology = manager.loadOntologyFromOntologyDocument(ontology);
OWLDataFactory df = manager.getOWLDataFactory();
for (final OWLSubClassOfAxiom subClasse : ontology.getAxioms(AxiomType.SUBCLASS_OF))
{
if (subClasse.getSuperClass() instanceof OWLClass && subClasse.getSubClass() instanceof OWLClass)
{
System.out.println(subClasse.getSubClass() + " extends " + subClasse.getSuperClass());
}
}
}

Printing Superclasses of Pizza ontology using OWL-API and Hermit

I try to print the Superclasses of standard Pizza ontology downloaded from here . I am using OWL API 3.4.3 and Hermit 1.3.8.1 (reasoner).
The following code snippet is used to print the required Superclasses of class "Food".
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
IRI ontologyIRI =IRI.create("file:/D:/pizza.owl.xml");
//IRI ontologyIRI =IRI.create("http://www.co-ode.org/ontologies/pizza/pizza.owl");
OWLOntology ontology = manager.loadOntology(ontologyIRI);
OWLReasoner reasoner = new Reasoner.ReasonerFactory().createReasoner(ontology);
OWLDataFactory df = manager.getOWLDataFactory();
try{
reasoner.precomputeInferences(InferenceType.CLASS_ASSERTIONS);
//following Lines are to see super classes of Container
OWLClass clsA = df.getOWLClass(IRI.create(ontologyIRI + "#Food"));
Set<OWLClassExpression> superClasses = clsA.getSuperClasses(ontology);
System.out.println("in TRY 1");
//System.out.println("Hello World\n"+superClasses.iterator().toString());
for (OWLClassExpression g : superClasses) {
System.out.println("The superclasses are:"+g);
}
}
catch (Exception e) {
e.printStackTrace();
}
I do not get any compilation error. The result is in TRY 1. The content inside for loop has not been printed.
In protege 5.0, I have seen two Superclasses of Food class; namely DomainConcept and owl:Thing. Why these two names has not been printed by the program?
Where am I doing wrong?
Thanks for any kind of help.
Your ontology IRI is a local file name. When you use it to obtain a class IRI, you're getting a different IRI from the one actually used in the ontology. Check what IRI the class actually has and that should fix your issue.

OWL API, extracting a string from a URI

Given an arbitrary IRI, such as the main ontology or one of the ontologies it imports, I would like to extract the title but the code yields no annotations.
Here's an example of what I'm talking about, from the SKOS ontology:
<owl:Ontology rdf:about="http://www.w3.org/2004/02/skos/core">
<dct:title xml:lang="en">SKOS Vocabulary</dct:title>
How exactly would I extract, "SKOS Vocabulary".
Here is some code I am currently using from an OWL-API tutorial.
public void testingOWL() throws OWLOntologyCreationException, OWLOntologyStorageException
{
// Get hold of an ontology manager
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
// Load an ontology from the Web. We load the ontology from a document IRI
IRI docIRI = IRI.create("http://www.w3.org/2009/08/skos-reference/skos.rdf");
OWLOntology skos = manager.loadOntologyFromOntologyDocument(docIRI);
System.out.println("Loaded ontology: " + skos);
System.out.println();
// Save a local copy of the ontology. (Specify a path appropriate to your setup)
File file = new File("e:/downloadAndSaveOWLFile.owl");
manager.saveOntology(skos, IRI.create(file.toURI()));
// Ontologies are saved in the format from which they were loaded.
// We can get information about the format of an ontology from its manager
OWLOntologyFormat format = manager.getOntologyFormat(skos);
System.out.println(" format: " + format);
System.out.println();
// Save the ontology in owl/xml format
OWLXMLOntologyFormat owlxmlFormat = new OWLXMLOntologyFormat();
// Some ontology formats support prefix names and prefix IRIs.
// In our case we loaded the pizza ontology from an rdf/xml format, which supports prefixes.
// When we save the ontology in the new format we will copy the prefixes over
// so that we have nicely abbreviated IRIs in the new ontology document
if(format.isPrefixOWLOntologyFormat())
{
owlxmlFormat.copyPrefixesFrom(format.asPrefixOWLOntologyFormat());
}
manager.saveOntology(skos, owlxmlFormat, IRI.create(file.toURI()));
// Dump an ontology to System.out by specifying a different OWLOntologyOutputTarget
// Note that we can write an ontology to a stream in a similar way
// using the StreamOutputTarget class
OWLOntologyDocumentTarget documentTarget = new SystemOutDocumentTarget();
// Try another format - The Manchester OWL Syntax
ManchesterOWLSyntaxOntologyFormat manSyntaxFormat = new ManchesterOWLSyntaxOntologyFormat();
if(format.isPrefixOWLOntologyFormat())
{
manSyntaxFormat.copyPrefixesFrom(format.asPrefixOWLOntologyFormat());
}
manager.saveOntology(skos, manSyntaxFormat, documentTarget);
}
EDIT: Update the code based on the suggestion below but only returns 1 object for rdfs:seeAlso.
public void getData() throws OWLOntologyCreationException
{
// Get hold of an ontology manager
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
// Load an ontology from the Web. We load the ontology from a document IRI
IRI docIRI = IRI.create("http://www.w3.org/2009/08/skos-reference/skos.rdf");
OWLOntology skos = manager.loadOntologyFromOntologyDocument(docIRI);
for (OWLAnnotation ann: skos.getAnnotations())
{
System.out.println("ann: " + ann.getProperty());
System.out.println();
}
}
The annotation you're looking for is an ontology annotation, meaning the IRI that is its subject is the ontology IRI itself. This is accessed differently from standard annotations.
OWLOntology o= ... // init the ontology as usual
for (OWLAnnotation ann: o.getAnnotations()){
if(ann.getProperty().equals(dataFactory.getRDFSLabel()){
// here you have found a rdfs:label annotation, so you can use the value for your purposes
}
}
Edit: Example of use
public static void main(String[] args) throws OWLOntologyCreationException {
OWLOntologyManager m = OWLManager.createOWLOntologyManager();
OWLOntology o = m.loadOntology(IRI
.create("http://www.w3.org/2009/08/skos-reference/skos.rdf"));
for (OWLAnnotation a : o.getAnnotations()) {
System.out.println("TestSkos.main() " + a);
}
}
Output:
TestSkos.main() Annotation(rdfs:seeAlso <http://www.w3.org/TR/skos-reference/>)
TestSkos.main() Annotation(<http://purl.org/dc/terms/creator> "Alistair Miles")
TestSkos.main() Annotation(<http://purl.org/dc/terms/description> "An RDF vocabulary for describing the basic structure and content of concept schemes such as thesauri, classification schemes, subject heading lists, taxonomies, 'folksonomies', other types of controlled vocabulary, and also concept schemes embedded in glossaries and terminologies."#en)
TestSkos.main() Annotation(<http://purl.org/dc/terms/contributor> "Participants in W3C's Semantic Web Deployment Working Group.")
TestSkos.main() Annotation(<http://purl.org/dc/terms/creator> "Sean Bechhofer")
TestSkos.main() Annotation(<http://purl.org/dc/terms/contributor> "Nikki Rogers")
TestSkos.main() Annotation(<http://purl.org/dc/terms/title> "SKOS Vocabulary"#en)
TestSkos.main() Annotation(<http://purl.org/dc/terms/contributor> "Dave Beckett")

xStream crashes when there are more fields in the XML

xStream
When I have the following XML code:
<xml>
<version>1.1</version>
<url>http://www.google.nl</url>
</xml>
And I read this with my Java code everything works fine, but when the XML changes, for example to:
<xml>
<test>test</test>
<version>1.1</version>
<url>http://www.google.nl</url>
</xml>
I get an error, but I want that the program doesn't stop, and don't use the field test. Is there a way to handle this exception without that the program stops?
Exception in thread "main" com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$UnknownFieldExce ption: No such field Version.iets
---- Debugging information ----
field : iets
class : Version
required-type : Version
converter-type : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
path : /Version/iets
line number : 1
version : null
-------------------------------
XStream 1.4.5 makes you simple to deal with unknown tags. Use ignoreUnknownElements for tags which are not implemented yet or has been removed and you are dealing with old xml.
http://x-stream.github.io/javadoc/com/thoughtworks/xstream/XStream.html#ignoreUnknownElements%28%29
You can also specify which particular tag you would like to ignore.
Thanks to Brian Agnew I found the answer, this is the solution:
XStream xstream = new XStream(new DomDriver()) {
protected MapperWrapper wrapMapper(MapperWrapper next) {
return new MapperWrapper(next) {
public boolean shouldSerializeMember(Class definedIn, String fieldName) {
try {
return definedIn != Object.class || realClass(fieldName) != null;
} catch(CannotResolveClassException cnrce) {
return false;
}
}
};
}
};

How do I set up jsr223 scripting with scala as scripting language

So far I have tried the sling implementation for jsr223 scripting for scala, but was not able to get it set up correctly.
when I do this:
public static void main(String[] args) {
try {
new ScriptEngineManager().getEngineByName("scala").
eval("object HelloWorld {def main(args: Array[String]) {
println(\"Hello, world!\") }}");
} catch (ScriptException e) {
e.printStackTrace();
}
}
I got nothing but:
javax.script.ScriptException: ERROR
org.apache.sling.scripting.scala.Script line 13 : not found: type
Script at org.apache.sling.scripting.scala.ScalaScriptEngine.eval(ScalaScriptEngine.scala:117)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:247)
similar Problems are discussed here:
http://scala-programming-language.1934581.n4.nabble.com/How-to-compile-Scala-code-from-java-using-the-current-ClassLoader-instead-of-a-string-based-classpat-td1955873.html#a1955873
and
http://dev.day.com/discussion-groups/content/lists/sling-dev/2009-12/2009-12-01_Scala_scripting_support_was_Re_And_another_one____Michael_D_rig.html
maybe there is another Implementation that I'm not aware of.
Any help appreciated
Have a look at the test cases in the scala/script module of Apache Sling for a working example. The script and its entry point (that is the object) need to follow certain conventions. I'll provide more information on these if required later.
For a general overview of the scripting engine see my session slides from Scala Days 2010.
Update: Scripts must be of the following form:
package my.cool.script {
class foo(args: fooArgs) {
import args._ // import the bindings
println("bar:" + bar)
}
}
The type of args is generated by the script engine and is named after the simple class name of the script appended with 'Args'. Further the example assumes, that the Bindings passed for script evaluation contains a value for the name 'bar'. For further details see the class comment on ScalaScriptEngine.
You need to pass the name of your script class to the script engine. You do this by putting the fully qualified script name (i.e. my.cool.script.foo) into the ScriptContext by the name 'scala.script.class'.
With the conclusion of https://issues.scala-lang.org/browse/SI-874 in version 2.11, it should be as easy as what is shown in the ticket:
import javax.script.*;
ScriptEngine e = new ScriptEngineManager().getEngineByName("scala");
e.getContext().setAttribute("label", new Integer(4), ScriptContext.ENGINE_SCOPE);
try {
engine.eval("println(2+label)");
} catch (ScriptException ex) {
ex.printStackTrace();
}
Unfortunately my comment was unreadable without linebreaks - so...
To be able to run the Codesnippet mentioned I needed to make the following changes.
I used Scala 2.11.0-M4
public static void main(String args[]){
ScriptEngine engine = new ScriptEngineManager().getEngineByName("scala");
// Set up Scriptenvironment to use the Java classpath
List nil = Nil$.MODULE$;
$colon$colon vals = $colon$colon$.MODULE$.apply((String) "true", nil);
((IMain)engine).settings().usejavacp().tryToSet(vals);ScriptContext.ENGINE_SCOPE);
engine.getContext().setAttribute("labelO", new Integer(4), ScriptContext.ENGINE_SCOPE);
try {
engine.eval("val label = labelO.asInstanceOf[Integer]\n"+
"println(\"ergebnis: \" + (2 + label ))");
} catch (ScriptException ex) {
ex.printStackTrace();
}
}

Categories

Resources