xfire.docx
《xfire.docx》由会员分享,可在线阅读,更多相关《xfire.docx(14页珍藏版)》请在冰豆网上搜索。
xfire
XFire:
TheeasyandsimplewaytodevelopWebservices
Webservicesenableustobuilddistributedsystemswhereapplicationcomponentsonanetworkcanbeaccessedinaplatform-neutral,language-agnostic,andimplementation-independentway.Itdoesn'tmatterhowanapplicationisdeveloped,whatlanguageituses,orwhatOSplatformitrunson.IfitisavailableasaWebserviceanddesignedaddressinginteroperabilityissues,yourapplication,developedinanylanguageorplatform,willbeabletoutilizeitsservices.That'sthemainconceptofWebservices.
Toachievetheplatform-neutralandimplementation-independentaccessibilityofWebservices,thesoftwareindustryhasagreedonafewtechnologiesasstandards.Someofthemare:
∙XML:
ThedefaultdataformatusedacrossalllayersofWebservicesenvironment.
∙SOAP:
Thedefaultprotocolforpackagingandexchangingmessages.Whenfirstintroduced,itwasanacronymforSimpleObjectAccessProtocol.ButnowSOAPisconsideredapropernoun,anameinitself,asmostpeoplenowrealizeitisamisnomer:
SOAPisnotreallyforaccessingobjects.Plus,itisnotsimpleanymore.
∙WSDL(WebServicesDescriptionLanguage):
ThelanguagethatdescribesWebservices.AlthoughbasedonXMLandunderstandablebyhumans,WSDLismainlyformachineconsumption,tobereadandunderstoodbyclientprograms.
Thefollowinghigh-leveldiagram,basedonthedocument"WebServicesArchitecture"publishedbytheWorldWideWebConsortium,showshowallthesetechnologiesareengagedinaworkingenvironment:
TheprocessshowinghowcoretechnologiesengageinWebservices.Clickonthumbnailtoviewfull-sizeimage.
Here,Provideristheapplicationcomponentthatwouldprovidetheservice,andRequesteristheclientprogramthatwouldconsumeit.Manyothertechnologiesmayparticipateintheinteractions,butthisfigureshowsthecorecomponentsthatmustbeinaWebservicesenvironment.
XFireisafreeandopensourceSOAPframeworkthatnotonlyenablesyoutoimplementsuchanenvironmentwithgreateaseandsimplicity,butalsoprovidesyoumanyadvancedfeaturesidentifiedinWebservicesspecifications,butnotyetavailableinmostcommercialoropensourcetools.Youreadthewordscorrectly:
greateaseandsimplicity.Inthisarticle,you'llseehowsimpleitistobuildaWebservicewithXFire.
IfyourWebapplicationhasaJavaclassandyouwantitsmethodstobeexposedasWebservices,youmaynothavetowriteasinglelineofadditionalJavacodewhenyouuseXFire.Justworkonthedeploymentdescriptorsandyou'llgetaWebservice.Yes,it'sthateasy.Let'slookatanexample.
AsimpleJavaclass
OurexampleisabankingapplicationhostedinApacheTomcat5.5.7andrunningunderJ2SE1.4.2_07.IassumeyoualreadyknowhowtowriteWebapplicationsinJavaanddeployontoApacheTomcatservers.OurWebapplicationissimple;itdoesjustonething—transferfundsfromoneaccounttoanother.Aplain-oldJavaclassBankingServicecontainingamethodnamedtransferFunds()doesthejobforus.Itneedsfourinputparameters:
Page2of6
1.StringfromAccount
2.StringtoAccount
3.doubleamount
4.Stringcurrency
Hereisthecode:
packagecom.mybank.xfire.example;
importjava.text.NumberFormat;
importjava.text.DecimalFormat;
/**XFireWebServicessampleimplementationclass.
*/
publicclassBankingServiceimplementsIBankingService{
//Defaultconstructor.
publicBankingService(){
}
/**Transfersfundfromoneaccounttoanother.
*/
publicStringtransferFunds(
StringfromAccount,StringtoAccount,doubleamount,Stringcurrency){
StringstatusMessage="";
//Callbusinessobjectsandothercomponentstogetthejobdone.
//Thencreateastatusmessageandreturn.
try{
NumberFormatformatter=newDecimalFormat("###,###,###,###.00");
statusMessage="COMPLETED:
"+currency+""+formatter.format(amount)+
"wassuccessfullytransferredfromA/C#"+fromAccount+"toA/C#"+toAccount;
}catch(Exceptione){
statusMessage="BankingService.transferFunds():
EXCEPTION:
"+e.toString();
}
returnstatusMessage;
}
}
Doyouseeanythingexceptionalhere?
Probablynot,exceptthedefaultconstructor,whichispublic.Itisrequired.Otherwise,XFirewouldnotbeabletoinstantiatetheclass.
Sincedesigningwithinterfacesisgoodpractice,ourJavaclassalsoimplementsaninterfacenamedIBankingService.Thecodeissimple:
packagecom.mybank.xfire.example;
publicinterfaceIBankingService{
publicStringtransferFunds(
StringfromAccount,StringtoAccount,doubleamount,Stringcurrency);
}
Inactualimplementation,suchamethodmayincludeallkindsofcomplexcalls,queries,andprocessingoperations.Butourexamplecodeisbareminimumsothatwecanfocusonourmainobjective:
exposingthemethodasaWebservice.
YoucanseethatBankingServiceisaplainJavaclass,withnocodewhatsoevertotellwhetheritshouldbeusedinWebservices.Andthat'sfine.Wedon'tneedtoaddanythinghere.Allourworkwillbedoneinthedeploymentdescriptors.
DeploymentdescriptorsoftheWebapplication
InJava,Webapplicationsareusuallyconfiguredusingatleastonedeploymentdescriptor,namedweb.xml.XFireitselfisaservlet-basedapplication.Hence,weneedtoaddnecessaryreferencestothisfile.ThenwehavetoconfiguretheWebservicewearecreating.Wewilluseanewfilenamedservices.xmltodothat.
web.xml
First,let'sworkonweb.xml.WeneedtoaddthefollowingXFireservlet-relatedentries:
XFireServlet
XFireServlet
org.codehaus.xfire.transport.http.XfireConfigurableServlet
XFireServlet
/servlet/XFireServlet/*
XFireServlet
/services/*
services.xml
NowwehavetosaywhatourWebservicesconsistof.Thisisdoneinafilenamedservices.xml,whichisplacedundertheMETA-INF/xfiredirectory.ThiswholedirectoryisplacedundertheWEB-INF/classesfolder,whichisinthestandardclasspathofWebapplications.Herearethebasicconfigurationentriesinservices.xml:
Page3of6
//xfire.codehaus.org/config/1.0">
Banking
mybank
com.mybank.xfire.example.IBankingService
com.mybank.xfire.example.BankingService
Let'sseewhatwehavehere.ThedefinitionofourWebserviceiscontainedinsideaelement,whichcontainsafewchildelements.Thefirstchildelementis,whichcanbeanyvalidXMLnameyouprovide.Thiswillbeusedbyclientprogramsandothercomponentstolocateyourservice.Forexample,aftertheserviceisup,you'llusethisnameonabrowsertoseetheWSDL.
Thenextchildelementis.AnyvalidXMLnameisfine.willbeusedtouniquelyidentifyvariousparametersofyourservice.
TheelementcontainstheJavaclassnamethatspecifiesthemethodsignature.Inourexample,itistheinterfaceIBankingService.IfyourJavaclassdoesnotimplementanyinterface,you'llputthatclassnamehere.YoumayhaveseveralmethodsinyourJavaclassorinterface.JustoneentryisneededtoexposethemallasWebservices.
TheholdstheJavaclassnamethathasthemethodimplementations.Thisisanoptionalelement.Ifthepreviouselementcontainedaninterface,thecorrespondingimplementationclassmustbenamedhere.
That'sit.ConfigurationofourWebserviceiscomplete.
XFireandotherlibraries
Nowwecometothelaststep,whichistogetallnecessarylibraryfiles.Howdowegetthem?
GototheXFireWebsite,downloadxfire-distribution-1.0.zip,andunzipitinalocalfolder.CopythefollowingjarfilesfromthedistributionanditslibdirectoryintotheWEB-INF\lib:
∙activation-1.0.2.jar
∙commons-codec-1.3.jar
∙commons-httpclient-3.0.jar
∙commons-logging-1.0.4.jar
∙jaxen-1.1-beta-8.jar
∙jdom-1.0.jar
∙log4j-1.2.x.jar
∙mail-1.3.3_01.jar
∙spring-1.2.x.jar
∙stax-api-1.0.jar
∙wsdl4j-1.5.2.jar
∙wstx-asl-2.9.jar
∙xbean-2.1.0.jar
∙xbean-spring-2.2.jar
∙xfire-all-1.0.jar
∙XmlSchema-1.0.jar
Wearedone.Let'sdeployandstarttheapplication.Todeploytheexampleapplication,justcopywebsvc.warintothewebappsdirectoryinyourApacheTomcatenvironmentandwaitafewseconds.Itshouldstartautomatically.Theapplication'scompletesourcecodeisalsocontainedinthiswarfile.OurprogramisnowreadyasaWebservice.
HowdoweknowtheWebserviceisworking?
ToseeiftheWebserviceisworking,we'llhavetotest.First,wetesttoseeiftheWSDLisavailable.Let'stypetheURLonabrowser.WhichURL?
Sinceourapplication'swarfileiswebsvc.warandtheservicenamegiveninservices.xmlisBanking,theWSDLURLwouldbe:
http:
//localhost:
8080/websvc/services/Banking?
wsdl.
Pleasenote:
ThefirstpartofyourURL,i.e.,http:
//localhost:
8080,maydifferdependingonyourapplicationserver'ssetup.Regardless,asyoutypetheURL,you'llseeanXMLdocumentwhoserootelementisdefinitions>.Thisdocumentiscalledtheservice'sWSDL.Ifyouseeit,thisisthefirstverificationthatyourapplicationisavailableasaWebservice.
Page4of6
Butthistestisnotenough.SituationsmayarisewhereyoucouldseetheWSDL,yettheservicemaynotbeaccessib