An Introduction to RDF and the Jena RDF API
2007-06-07 14:44
591 查看
AnIntroductiontoRDFandtheJenaRDFAPI
Preface
ThisisatutorialintroductiontobothW3C'sResourceDescriptionFramework(RDF)andJena,aJavaAPIforRDF.ItiswrittenfortheprogrammerwhoisunfamiliarwithRDFandwholearnsbestbyprototyping,or,forotherreasons,wishestomovequicklytoimplementation.SomefamiliaritywithbothXMLandJavaisassumed.Implementingtooquickly,withoutfirstunderstandingtheRDFdatamodel,leadstofrustrationanddisappointment.Yetstudyingthedatamodelaloneisdrystuffandoftenleadstotortuousmetaphysicalconundrums.Itisbettertoapproachunderstandingboththedatamodelandhowtouseitinparallel.Learnabitofthedatamodelandtryitout.Thenlearnabitmoreandtrythatout.Thenthetheoryinformsthepracticeandthepracticethetheory.Thedatamodelisquitesimple,sothisapproachdoesnottakelong.
RDFhasanXMLsyntaxandmanywhoarefamiliarwithXMLwillthinkofRDFintermsofthatsyntax.Thisismistake.RDFshouldbeunderstoodintermsofitsdatamodel.RDFdatacanberepresentedinXML,butunderstandingthesyntaxissecondarytounderstandingthedatamodel.
AnimplementationoftheJenaAPI,includingtheworkingsourcecodeforalltheexamplesusedinthistutorialcanbedownloadedfrom
TableofContents
Introduction
TheResourceDescriptionFramework(RDF)isastandard(technicallyaW3CRecommendation)fordescribingresources.Whatisaresource?Thatisratheradeepquestionandtheprecisedefinitionisstillthesubjectofdebate.Forourpurposeswecanthinkofitasanythingwecanidentify.Youarearesource,asisyourhomepage,thistutorial,thenumberoneandthegreatwhitewhaleinMobyDick.Ourexamplesinthistutorialwillbeaboutpeople.Theyusean
The
Resourceshave
Eachpropertyhasavalue.Inthiscasethevalueisa
JenaisaJavaAPIwhichcanbeusedtocreateandmanipulateRDFgraphslikethisone.Jenahasobjectclassestorepresentgraphs,resources,propertiesandliterals.Theinterfacesrepresentingresources,propertiesandliteralsarecalledResource,PropertyandLiteralrespectively.InJena,agraphiscalledamodelandisrepresentedbytheModelinterface.
Thecodetocreatethisgraph,ormodel,issimple:
//somedefinitions staticStringpersonURI="http://somewhere/JohnSmith"; staticStringfullName="JohnSmith"; //createanemptyModel Modelmodel=ModelFactory.createDefaultModel(); //createtheresource ResourcejohnSmith=model.createResource(personURI); //addtheproperty johnSmith.addProperty(VCARD.FN,fullName);
ItbeginswithsomeconstantdefinitionsandthencreatesanemptyModelormodel,usingthe
ModelFactorymethod
createDefaultModel()tocreateamemory-basedmodel.JenacontainsotherimplementationsoftheModelinterface,e.gonewhichusesarelationaldatabase:thesetypesofModelarealsoavailablefromModelFactory.
TheJohnSmithresourceisthencreatedandapropertyaddedtoit.Thepropertyisprovidedbya"constant"classVCARDwhichholdsobjectsrepresentingallthedefinitionsintheVCARDschema.Jenaprovidesconstantclassesforotherwellknownschemas,suchasRDFandRDFschemathemselves,DublinCoreandDAML.
Thecodetocreatetheresourceandaddtheproperty,canbemorecompactlywritteninacascadingstyle:
ResourcejohnSmith= model.createResource(personURI) .addProperty(VCARD.FN,fullName);
Theworkingcodeforthisexamplecanbefoundinthe/src-examplesdirectoryoftheJenadistributionas
Nowlet'saddsomemoredetailtothevcard,exploringsomemorefeaturesofRDFandJena.
Inthefirstexample,thepropertyvaluewasaliteral.RDFpropertiescanalsotakeotherresourcesastheirvalue.UsingacommonRDFtechnique,thisexampleshowshowtorepresentthedifferentpartsofJohnSmith'sname:
Herewehaveaddedanewproperty,vcard:N,torepresentthestructureofJohnSmith'sname.ThereareseveralthingsofinterestaboutthisModel.Notethatthevcard:Npropertytakesaresourceasitsvalue.NotealsothattheellipserepresentingthecompoundnamehasnoURI.Itisknownasan
TheJenacodetoconstructthisexample,isagainverysimple.Firstsomedeclarationsandthecreationoftheemptymodel.
//somedefinitions StringpersonURI="http://somewhere/JohnSmith"; StringgivenName="John"; StringfamilyName="Smith"; StringfullName=givenName+""+familyName; //createanemptyModel Modelmodel=ModelFactory.createDefaultModel(); //createtheresource //andaddthepropertiescascadingstyle ResourcejohnSmith =model.createResource(personURI) .addProperty(VCARD.FN,fullName) .addProperty(VCARD.N, model.createResource() .addProperty(VCARD.Given,givenName) .addProperty(VCARD.Family,familyName));
Theworkingcodeforthisexamplecanbefoundas
Statements
EacharcinanRDFModeliscalledathe
the
the
Astatementissometimescalleda
AnRDFModelisrepresentedasasetofstatements.Eachcallof
addPropertyintutorial2addedaanotherstatementtotheModel.(BecauseaModelissetofstatements,addingaduplicateofastatementhasnoeffect.)TheJenamodelinterfacedefinesa
listStatements()methodwhichreturnsan
StmtIterator,asubtypeofJava's
IteratoroverallallthestatementsinaModel.
StmtIteratorhasamethod
nextStatement()whichreturnsthenextstatementfromtheiterator(thesameonethat
next()woulddeliver,alreadycastto
Statement).The
Statementinterfaceprovidesaccessormethodstothesubject,predicateandobjectofastatement.
Nowwewillusethatinterfacetoextendtutorial2tolistallthestatementscreatedandprintthemout.Thecompletecodeforthiscanbefoundin
//listthestatementsintheModel StmtIteratoriter=model.listStatements(); //printoutthepredicate,subjectandobjectofeachstatement while(iter.hasNext()){ Statementstmt=iter.nextStatement();//getnextstatement Resourcesubject=stmt.getSubject();//getthesubject Propertypredicate=stmt.getPredicate();//getthepredicate RDFNodeobject=stmt.getObject();//gettheobject System.out.print(subject.toString()); System.out.print(""+predicate.toString()+""); if(objectinstanceofResource){ System.out.print(object.toString()); }else{ //objectisaliteral System.out.print("\""+object.toString()+"\""); } System.out.println("."); }
Sincetheobjectofastatementcanbeeitheraresourceoraliteral,the
getObject()methodreturnsanobjecttypedas
RDFNode,whichisacommonsuperclassofboth
Resourceand
Literal.Theunderlyingobjectisoftheappropriatetype,sothecodeuses
instanceoftodeterminewhichandprocessesitaccordingly.
Whenrun,thisprogramshouldproduceoutputresembling:
http://somewhere/JohnSmithhttp://www.w3.org/2001/vcard-rdf/3.0#Nanon:14df86:ecc3dee17b:-7fff. anon:14df86:ecc3dee17b:-7fff http://www.w3.org/2001/vcard-rdf/3.0#Family"Smith". anon:14df86:ecc3dee17b:-7fff http://www.w3.org/2001/vcard-rdf/3.0#Given"John". http://somewhere/JohnSmithhttp://www.w3.org/2001/vcard-rdf/3.0#FN"JohnSmith".
NowyouknowwhyitisclearertodrawModels.Ifyoulookcarefully,youwillseethateachlineconsistsofthreefieldsrepresentingthesubject,predicateandobjectofeachstatement.TherearefourarcsintheModel,sotherearefourstatements.The"anon:14df86:ecc3dee17b:-7fff"isaninternalidentifiergeneratedbyJena.ItisnotaURIandshouldnotbeconfusedwithone.ItissimplyaninternallabelusedbytheJenaimplementation.
TheW3C
WritingRDF
JenahasmethodsforreadingandwritingRDFasXML.ThesecanbeusedtosaveanRDFmodeltoafileandlaterreaditbackinagain.Tutorial3createdamodelandwroteitoutintripleform.
model.writecantakean
OutputStreamargument.
//nowwritethemodelinXMLformtoafile model.write(System.out);
Theoutputshouldlooksomethinglikethis:
<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' xmlns:vcard='http://www.w3.org/2001/vcard-rdf/3.0#' > <rdf:Descriptionrdf:about='http://somewhere/JohnSmith'> <vcard:FN>JohnSmith</vcard:FN> <vcard:Nrdf:nodeID="A0"/> </rdf:Description> <rdf:Descriptionrdf:nodeID="A0"> <vcard:Given>John</vcard:Given> <vcard:Family>Smith</vcard:Family> </rdf:Description> </rdf:RDF>