Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming with Jena Sources for examples can be

Similar presentations

Presentation on theme: "Programming with Jena Sources for examples can be"— Presentation transcript:

1 Programming with Jena Sources for examples can be found @ Taylor Cowan Travelocity 8982

2 2 [] a foaf:Person; foaf:name Taylor Cowan; foaf:weblog ; foaf:workplaceHomepage ; foaf:holdsAccount ; foaf:currentProject ;

3 3 Model m = ModelFactory.createDefaultModel(); Thing todaysTopic = new Thing("", m); new Thing(m).isa(Foaf.Person.class).name("Taylor Cowan").weblog(URI.create("")).holdsAccount(URI.create("")).currentProject(todaysTopic).currentProject(URI.create("")); @see in package example.fluentwriter

4 4 AGENDA >Semantic Web Introduction >RDF basics >Coding Towards Jena’s Semantic Web Framework API >Java to Model Binding with JenaBean >Java to Model Binding with Fluent Interfaces

5 Why Not Microformats? 5

6 RDF != XML “The site at, also known as Travelocity, is an online travel agency competing with” 6

7 Concepts as a Directed Graph 7 AKA Travelocity Is a Online travel agency Has competitor

8 8 Concepts Serialized as N3 :OnlineTravelAgency a owl:Class. :hasCompetitor a rdf:Property. a :OnlineTravelAgency ; rdfs:label "Travelocity"@en ; :hasCompetitor.

9 9 Concepts Serialized as RDF/XML Travelocity

10 As N-Triples (Most Canonical or Normalized). "Travelocity"@en. 10 Subject, Verb, Object = a triple

11 As Java Code, using the Jena API OntModel m = ModelFactory.createOntologyModel(); OntClass ota = m.createClass("OnlineTravelAgency"); Individual tvly = ota.createIndividual(""); tvly.setLabel("Travelocity", "en"); OntProperty p = m.createOntProperty("hasCompetitor"); tvly.setPropertyValue(p, m.createResource("")); 11

12 Creating a Model 1: Model m = ModelFactory.createDefaultModel(); 2: m.setNsPrefix("foaf", FOAF.NS); 3: Resource jazoon = m.createResource(""); 4: Resource java = m.createResource( 5:""); 6: jazoon.addProperty(FOAF.primaryTopic, java); 7: m.write(System.out, "N3"); 12 foaf:primaryTopic.

13 Assertion 13 java foaf:primaryTopic

14 Creating an Inferencing Model OntModel infModel = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM_MICRO_RULE_INF, m);""); infModel.writeAll(System.out, "N3",null); 14 foaf:isPrimaryTopicOf In addition to known data, a new triple is inferred…

15 Knowledge after Inference 15 java foaf:primaryTopic foaf:isPrimaryTopicOf foaf:Document Is a

16 16 The Semantic Web is Property focused >Properties have Classes, not vice versa >Don’t read “the domain of foaf:knows is a foaf:Person”, but instead “anything with foaf:knows relationship is a foaf:Person” >Properties can extend other properties >Properties can be declared as inverse, symmetric, and transitive, all resulting in new inferences.

17 List All Classes from an Ontology OntModel model = ModelFactory.createOntologyModel();""); ExtendedIterator it = model.listClasses(); while(it.hasNext()) { OntClass cls =; if (cls.getNameSpace().equals(FOAF.NS)) System.out.println(cls.getURI()); } 17

18 Models Can be Populated from URL, Either Public or Local OntModel model = ModelFactory.createOntologyModel(); // read from URL"");"file:mydata.n3","N3"); 18

19 Models can be Populated from Other Models Model modelA = ModelFactory.createDefaultModel(); Model modelB = ModelFactory.createDefaultModel(); … //Add all statements from modelB to modelA modelA.add(modelB); 19

20 20 Some example foaf: a dc:Article ; dc:creator "Philip McCarthy"^^xsd:string ; dc:subject "jena, rdf, java, semantic web"^^xsd:string ; dc:title "Introduction to Jena"^^xsd:string.

21 21 Equivalent Raw Jena API Client Code String NS = ""; OntModel m = ModelFactory.createOntologyModel(); OntClass articleCls = m.createClass(NS +"Article"); Individual i = articleCls.createIndividual( ""); Property title = m.getProperty(NS + "title"); Literal l = m.createTypedLiteral("Introduction to Jena"); i.setPropertyValue(title,l); Property creator = m.getProperty(NS + "creator"); l = m.createTypedLiteral("Philip McCarthy"); i.setPropertyValue(creator,l); Property subject = m.getProperty(NS + "subject"); l = m.createTypedLiteral("jena, rdf, java, semantic web"); i.setPropertyValue(subject,l); m.write(System.out, "N3");

22 22 Pain Points of Raw Jena API Programming >You need to create unique URI’s for every entity. >You must specify the type of each primitive value. >Properties must be created for each bean property. >The impedance mismatch is similar to what we had with RDBMS

23 23 Creating The Same Assertions with JenaBean Model m = ModelFactory.createDefaultModel(); Bean2RDF writer = new Bean2RDF(m); Article article = new Article( ""); article.setCreator("Philip McCarthy"); article.setTitle("Introduction to Jena"); article.setSubject("jena, rdf, java, semantic web");; m.write(System.out, "N3");

24 24 The JenaBean Project >Hosted at Google code >Bean binding, not code generation >Doesn’t use byte code interweaving >Doesn’t require implementing an interface >

25 25 Programming with JenaBean is Simple >Bean2RDF writes objects >RDF2Bean reads objects >3 Annotations –@Id specifies unique field –@Namespace provides a domain –@RdfProperty maps java properties to RDF properties

26 The Simplest Possible Example package examples.model; import thewebsemantic.Id; public class Person { @Id private String email; public String getEmail() { return email;} public void setEmail(String email) { = email;} } 26 a ; "examples.model.Person". a ; ""^^xsd:string.

27 Saving an Instance of Person Model m = ModelFactory.createOntologyModel(); Bean2RDF writer = new Bean2RDF(m); Person p = new Person(); p.setEmail("");; m.write(System.out, "N3"); … a owl:Class ; "example.Person". a ; ""^^xsd:string. 27

28 Overriding the Default Namespace package examples.model; import thewebsemantic.Id; import thewebsemantic.Namespace; @Namespace("http://mydomain#") public class Person { … } 28 a ; "examples.model.Person". a ; ""^^xsd:string.

29 Overriding the Default Property Bindings @Namespace(“http://mydomain#”) public class Person { private String email; @RdfProperty(FOAF.NS + "name") private String name; 29 a ; "examples.model.Person". a ; "Taylor Cowan"^^xsd:string.

30 Extending Person to Support Friendship public Collection friends = new LinkedList (); @RdfProperty("") public Collection getFriends() { return friends;} 30

31 Loading Beans from a Model RDF2Bean reader = new RDF2Bean(m); Person p = reader.load(Person.class,""); Collection allPeople = reader.load(Person.class); 31

32 JenaBean Support for OWL Entailments 32 public class Location { @Id public String id; public String name; @RdfProperty(transitive=true) public Collection within; @RdfProperty(inverseOf="within") public Collection contains; … a rdf:Property, owl:TransitiveProperty. a rdf:Property ; owl:inverseOf.

33 Reading Existing RDF/OWL 33 >Up till this point we were generating the triples >JenaBean + annotations controlled the URI’s >The model knew the provenance of all data (the originating java class)

34 Example Geonames “feature” entry 34 London Borough of Islington Islington 185500 51.5333333 -0.1333333 Jenabean will bind to existing URI’s

35 Crafting beans for existing RDF requires care 35 @Namespace("") public class Feature { @Id private URI uri; @RdfProperty("") public double lat; 1 2 3 4 1.Namespace must accurately match 2.Your java’s classname must match the Ontology class 3.Your @Id must be of type 4.All property URI’s must match the Ontology property

36 JenaBean can auto discover JenaBeans, provided it knows the package(s) 36 1: Model m = ModelFactory.createDefaultModel(); 2:""); 3: RDF2Bean reader = new RDF2Bean(m); 4: reader.bindAll("", ""); // type safe binding by class reader.bind(Feature.class); // or package reader.bind(Feature.class.getPackage());

37 JenaBean tip: handling lang encoded strings If your data has something like this: Londres Then use JenaBean‘s special type “LocalizedString“ 37 public Collection alternateName; example.geonames

38 Query Support 38 // load using a Jena Resource reader.load(Human.class, jenaResource); // load any node using it’s URI reader.load(Human.class, "http://any.uri"); >Most most practical purposes there’s no need to utilize anything other than Jena’s ARQ api to query. JenaBean’s reader (RDF2Bean) can transform a node given it’s URI or it’s representation as a jena Resource…

39 thewebsemantic.Sparql Util 39 String query = "prefix ntn: \n" + "SELECT ?s WHERE { ?s a ntn:Woman }"; Model m = ModelFactory.createOntologyModel();"file:NTNames.owl");"file:NTN-individuals.owl"); RDF2Bean reader = new RDF2Bean(m); reader.bindAll("example.query"); Collection women = Sparql.exec(m, Woman.class, query); for (Human human : women) System.out.println(human.label + ":" + human.comment); example.query

40 Summary @Namespace(“”) Applies to class declaration @Id Applies to field or getter method Should be a String or primitive type, or wrapper type type is special @RdfProperty(“”) Applies to field or getter method Remember: by definition, JavaBeans must have a default constructor. 40

41 Summary writer.saveDeep(mybean) Save this and all related objects reader.load(Class.class, key); reader.loadDeep(…); take care, could place entire graph into memory. reader.bindAll(package, package, …); Makes jenabean aware of your beans 41

42 JenaBean Fluent Programming API 42 >AKA method chaining, foo.this().that().bar(); >A “Fluent Interface” aims to provide more readable code >A significant departure from JavaBeans >Is always connected to the jena graph >Entirely interface (not class) driven >Allows Individuals to morph into their various classes >Allows use of vocabulary terms against any Individual regardless of classification.

43 Example: wgs84 geo vocabulary 43 import thewebsemantic.As; import thewebsemantic.Functional; import thewebsemantic.Namespace; @Namespace("") public interface Geo extends As { interface Point extends Geo{} @Functional Geo lat(float l); Float lat(); @Functional Geo long_(float l); Float long_(); }

44 A fluent api + good IDE makes things fun 44

45 Create a new anonymous iCal event. 45 Ical t = new Thing(m).isa(Ical.Vevent.class); Create a new iCal event with URI Ical t = new Thing(“http://uri”, m). isa(Ical.Vevent.class);

46 Full Example: Creating an iCal event for the meetup 46 1: Ical.Vevent t = new Thing(m).isa(Ical.Vevent.class); 2: t.uid(""). 3: dtstart("20100124T200000Z"). 4: dtend("20100124T220000Z"). 5: summary("Jena Semantic Web…"). 6: location("Parisoma - …") 8: lat(37.77f). 9: long_(-122.41f); [] a ical:Vevent ; ical:dtend "20100124T220000Z" ; ical:dtstart "20100124T200000Z" ; ical:location "Parisoma - " ; ical:summary "Jena Semantic Web…" ; ical:uid "" ; geo:lat "37.77"^^xsd:float ; geo:long "-122.41"^^xsd:float.

47 JenaBean comes with a few common vocabulary interfaces 47 >thewebsemantic.vocabulary.Foaf >Geo >Ical >DCTerms >Sioc >Skos >Rdfs >ReviewVocab >You may want to copy and modify in some cases.

48 Fluent API summary: 48 >Your interface should extend thewebsemantic.As >Provides polymorphic “as(Class)” to other vocabs. >Provides easy type declaration with “isa(Class)” >Use the @Namespace annotation to bind to the vocabulary >Name setters according to vocab, taking either an Object (literal) or anther Thing (relationship to other Individuals) >Name getters according to vocab, returning the same vocabulary type and taking no arguments. >If the vocabulary term collides with reserved term (as with long), append a dash. >Plural properties should return a Collection.

49 49 Project Ideas >Create your own foaf document using the fluent interface. >Integrate Jena/JenaBean with restlets – >Use your favorite framework (struts, stripes, spring mvc) and create a user registration screen. >Write JenaBeans that bind to jamendo or other music ontology at >Write a foaf crawler beginning with Berners-Lee that traverses his social graph. cc nickjohnson

50 50 Open Source Tools For Java Devs >Java Triple Stores –Jena (HP Labs) –Sesame OpenRDF (Aduna) –Mulgara >Java Binding tools –JenaBean (Jena) –Jastor (Jena) –Owl2Java (Jena) –Elmo (Sesame) –Empire cc nickjohnson

51 Taylor Cowan Travelocity

Download ppt "Programming with Jena Sources for examples can be"

Similar presentations

Ads by Google