Apache Jackrabbit 官网代码示例First Hops.docx
《Apache Jackrabbit 官网代码示例First Hops.docx》由会员分享,可在线阅读,更多相关《Apache Jackrabbit 官网代码示例First Hops.docx(19页珍藏版)》请在冰豆网上搜索。
ApacheJackrabbit官网代码示例FirstHops
FirstHops
WelcometoyourfirsthopsintotheworldofJackrabbit!
Thisintroductiongivesyouahands-onexperiencewithJackrabbitandtheJCRAPI.Onceyouhavefinishedhoppingthroughthisdocument,youshouldbeallsettocontinueonyourownwiththeofficialJCRspecificationandthedocumentationonthissite.
Hop0:
Gettingstarted
TheeasiestwaytogetstartedwithJackrabbitistodownloadtherunnableStandaloneServerjar.Inadditiontorunningit,youcanalsoputitinyourclasspathtoquicklyaccessalltheclassesandinterfacesyouneedbelow.Alternatively,ifyouusetheApacheMavenbuildsystem(whichwerecommend),youcansetupyourfirsthopsprojectwiththefollowingdependencies.
--TheJCRAPI-->
javax.jcr
jcr
2.0
--Jackrabbitcontentrepository-->
org.apache.jackrabbit
jackrabbit-core
2.2.4
--UseLog4Jforlogging-->
org.slf4j
slf4j-log4j12
1.5.11
YouprobablyhaveanerrorinyourclasspathsettingsifyougetaClassNotFoundExceptionmessagewhentryingtocompileorruntheexamplesbelow.
Hop1:
LoggingintoJackrabbit
Solet’sgetstarted.Asawarm-upwe’llcreateaJackrabbitcontentrepositoryandstartaloginsessionforaccessingit.Thefullexampleapplicationthatdoesthisisshownbelow,withline-by-lineexplanationsfollowingshortlyafter.
importjavax.jcr.Repository;
importjavax.jcr.Session;
importorg.apache.jackrabbit.core.TransientRepository;
/**
*Firsthopexample.Logsintoacontentrepositoryandprintsa
*statusmessage.
*/
publicclassFirstHop{
/**
*Themainentrypointoftheexampleapplication.
*
*@paramargscommandlinearguments(ignored)
*@throwsExceptionifanerroroccurs
*/
publicstaticvoidmain(String[]args)throwsException{
Repositoryrepository=newTransientRepository();
Sessionsession=repository.login();
try{
Stringuser=session.getUserID();
Stringname=repository.getDescriptor(Repository.REP_NAME_DESC);
System.out.println(
"Loggedinas"+user+"toa"+name+"repository.");
}finally{
session.logout();
}
}
}
YoucanalsodownloadthesourcefileasFirstHop.java.Ifyouhaveyourclasspathsetup,youcancompiletheapplicationwithjavacFirstHop.javaandrunitwithjavaFirstHoptogetthefollowingoutput.
LoggedinasanonymoustoaJackrabbitrepository.
Inadditiontoproducingtheabovestatuslinetheapplicationcopiesadefaultrepositoryconfigurationfiletorepository.xmlandcreatesaninitialJackrabbitcontentrepositoryintherepositorysubdirectory.Youcanusethesystempropertiesorg.apache.jackrabbit.repository.confandorg.apache.jackrabbit.repository.hometosetalternativeconfigurationfileandrepositorydirectorylocations.
ReadonforadetailedbreakdownoftheFirstHopapplication:
importjavax.jcr.Repository;
importjavax.jcr.Session;
TheJCRAPIinterfacesarelocatedinthejavax.jcrpackagefoundinthejcr-1.0.jarlibrary.ThepromiseoftheJCRAPIisthatifyouonlyusetheseinterfacesinyourcontentapplication,itshouldremainmostlyindependentoftheunderlyingcontentrepositoryimplementation.
TheRepositoryinterfacerepresentsagivencontentrepositoryinstanceandtheSessioninterfacerepresentsasingleloginsessionforaccessingtherepository.Asessionisneededtoaccessanycontentwithinarepository.
NotethataSessioninstanceisnotguaranteedtobethread-safesoyoushouldstartmultiplesessionsifyouneedtoaccessrepositorycontentsimultaneouslyfromdifferentthreads.Thisisespeciallyimportantforthingslikewebapplications.
importorg.apache.jackrabbit.core.TransientRepository;
ThebestpracticefordeployingJackrabbitistouseJNDIorsomeotherconfigurationmechanisminacontainerenvironmenttokeeptheapplicationcodefreeofdirectJackrabbitdependencies,butsincewearecreatingasimplestandaloneapplicationwecantakeashortcutbyusingtheTransientRepositoryclassfromJackrabbitcore.
publicclassFirstHop
publicstaticvoidmain(String[]args)throwsException
TheFirstHopexampleisasimplestandaloneapplicationthatfitsnicelyinthemain()methodandletstheJVMtakecareofthepossibleexceptions.MoresubstantialcontentapplicationscouldalsobewrittenaswebapplicationorEJBcomponentswithdifferentsetupanderrorhandlingpatterns.
Repositoryrepository=newTransientRepository();
TheTransientRepositoryclassimplementstheJCRRepositoryinterface,soyoucansimplyassignaTransientRepositoryinstancetoaRepositoryvariable.Thedefaultconstructorcontainsautilityfeaturethatwilltakecareoftheinitialconfigurationandrepositoryconstructionwhenthefirstsessionisstarted.Thusthereisnoneedformanualconfigurationfornowunlessyouwantdirectcontrolovertherepositorysetup.
TheTransientRepositoryimplementationwillautomaticallyinitializethecontentrepositorywhenthefirstsessionisstartedandshutitdownwhenthelastsessionisclosed.Thusthereisnoneedforexplicitrepositoryshutdownaslongasallsessionsareproperlyclosed.NotethataJackrabbitrepositorydirectorycontainsalockfilethatpreventsitfrombeingaccessedsimultaneouslybymultipleprocesses.Youwillseerepositorystartupexceptionscausedbythelockfileifyoufailtoproperlycloseallsessionsorotherwiseshutdowntherepositorybeforeleavingtheprocessthataccessesarepository.Normallyyoucanjustmanuallyremovethelockfileinsuchcasesbutsuchcasesalwayspresentachanceofrepositorycorruptionespeciallyifyouuseanon-transactionalpersistencemanager.
Sessionsession=repository.login();
ThedefaultRepository.login()methodstartsarepositorysessionusingthedefaultworkspaceandnousercredentials.JackrabbittriestousetheJavaAuthenticationandAuthorizationService(JAAS)configurationinsuchcases,butdefaultstotheanonymoususerifaJAASSubjectisnotfound.
SinceweusetheTransientRepositoryclassastheRepositoryimplementation,thisstepwillalsocausetherepositorytobeinitialized.
try{...}finally{session.logout();}
Itisagoodpracticetoproperlyreleaseallacquiredresources,andtheJCRsessionsarenoexception.Thetry-finallyidiomisagoodwaytoensurethataresourcereallygetsreleased,asthereleasemethodgetscalledeveniftheinterveningcodethrowsanexceptionorotherwisejumpsoutsidethescope(forexampleusingareturn,break,orcontinuestatement).
TheSession.logout()methodinthefinallybranchclosesthesessionandsincethisistheonlysessionwehavestarted,theTransientRepositoryisautomaticallyshutdown.
Stringuser=session.getUserID();
TheusernameoridentifieroftheuserassociatedwithasessionisavailableusingtheSession.getUserID()method.Jackrabbitreturns"anonymous"bydefault.
Stringname=repository.getDescriptor(Repository.REP_NAME_DESC);
Eachcontentrepositoryimplementationpublishesanumberofstringdescriptorsthatdescribethevariousimplementationproperties,liketheimplementationlevelandthesupportedoptionalJCRfeatures.SeetheRepositoryinterfaceforalistofthestandardrepositorydescriptors.TheREP_NAME_DESCdescriptorcontainsthenameoftherepositoryimplementation,inthiscase"Jackrabbit".
Hop2:
Workingwithcontent
Themainfunctionofacontentrepositoryisallowapplicationstostoreandretrievecontent.ThecontentinaJCRcontentrepositoryconsistsofstructuredorunstructureddatamodeledasahierarchyofnodeswithpropertiesthatcontaintheactualdata.
Thefollowingexampleapplicationfirststoressomecontenttotheinitiallyemptycontentrepository,thenretrievesthestoredcontentandoutputsit,andfinallyremovesthestoredcontent.
importjavax.jcr.Repository;
importjavax.jcr.Session;
importjavax.jcr.SimpleCredentials;
importjavax.jcr.Node;
importorg.apache.jackrabbit.core.TransientRepository;
/**
*Secondhopexample.Stores,retrieves,andremovesexamplecontent.
*/
publicclassSecondHop{
/**
*Themainentrypointoftheexampleapplication.
*
*@paramargscommandlinearguments(ignored)
*@throwsExceptionifanerroroccurs
*/
publicstaticvoidmain(String[]args)throwsException{
Repositoryrepository=newTransientRepository();
Sessionsession=repository.login(
newSimpleCredentials("username","password".toCharArray()));
try{
Noderoot=session.getRootNode();
//Storecontent
Nodehello=root.addNode("hello");
Nodeworld=hello.addNode("world");
world.setProperty("message","Hello,World!
");
session.save();
//Retrievecontent
Nodenode=root.getNode("hello/world");
System.out.println(node.getPath());
System.out.println(node.getProperty("message").getString());
//Removecontent
root.getNode("hello").remove();
session.save();
}finally{
session.logout();
}
}
}
Likeinthefirsthop,thisexamplesourceisalsoavailableasSecondHop.java.Youcanalsocompileandrunthisclassjustlikeyoudidinthefirsthopexample.Runningthisexampleshouldproducethefollowingoutput:
/hello/world
Hello,World!
ThebasicstructureofthisexampleapplicationisthesameasintheFirstHopexample,solet’sjustwalkthroughthedifferences:
importjavax.jcr.SimpleCredentials;
importjavax.jcr.