Apache Jackrabbit 官网代码示例First Hops.docx

上传人:b****3 文档编号:26556121 上传时间:2023-06-20 格式:DOCX 页数:19 大小:22.45KB
下载 相关 举报
Apache Jackrabbit 官网代码示例First Hops.docx_第1页
第1页 / 共19页
Apache Jackrabbit 官网代码示例First Hops.docx_第2页
第2页 / 共19页
Apache Jackrabbit 官网代码示例First Hops.docx_第3页
第3页 / 共19页
Apache Jackrabbit 官网代码示例First Hops.docx_第4页
第4页 / 共19页
Apache Jackrabbit 官网代码示例First Hops.docx_第5页
第5页 / 共19页
点击查看更多>>
下载资源
资源描述

Apache Jackrabbit 官网代码示例First Hops.docx

《Apache Jackrabbit 官网代码示例First Hops.docx》由会员分享,可在线阅读,更多相关《Apache Jackrabbit 官网代码示例First Hops.docx(19页珍藏版)》请在冰豆网上搜索。

Apache Jackrabbit 官网代码示例First Hops.docx

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.

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 工作范文 > 演讲主持

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1