Tải bản đầy đủ - 0 (trang)
Chapter 14. Building a Web Service

Chapter 14. Building a Web Service

Tải bản đầy đủ - 0trang

Chapter14.BuildingaWebService

INTHISCHAPTER

DesigningaWebService

BuildingtheWebService

CreatingaWSDLFile

RegisteringWithinUDDI

UsingJavatoAccessaWSDLDocument

Summary

ThischapterwillshowyouhowtobuildaWebservicesystemfornewsdelivery.

UsingtheJSPBuzzasanexample,youwillbuildasystemfordeliveringnews

stories.

TheWebservicesbuiltsofarinthisbookhavebeensimple.Uptothispoint,we

didn'tworryaboutregisteringtheWebservices,becausetheservicecallswere

hard-codedtoworkbetweentheexamples.Becausetheexampleswerenotina

registry,therewasn'tanyneedtocreateaWSDLdescriptionfile.Thischapter

willtakethingsonestepfurtherandwalkthroughthecreationofasimple

WSDLfile.WithWSDL,it'spossibletodefineaWebservicethatotherscan

easilyuse.Theothermajornewstepshowshowtoregisteraservicewithina

UDDIregistry.

Webservicesaresimple—it'stheframeworkaroundtheWebservicesthat's

complicated.Aframeworktendstobelarge,andbuildingoneconsistsofmany

tedioussteps.Webserviceframeworksusuallyhavefiveelements:

TheactualWebservicebusinesslogic.

Aserver.ThisisusuallyaSOAPserver,andthisservermediatestraffic

betweenauserandtheWebservice.

AWSDLfiletodescribetheWebservice.

AWebserviceregistry.Typically,aframeworkprovidesdirectaccessto

oneofthepublicregistries,ratherthanaprivateregistry.



Automatedcodegenerationformostoftheinstallationandusageofthe

Webservice.

AlthoughtheWebservicemightbeasimpleclass,buildingtheoverall

frameworkisalargerandmorecomplicatedtask.Manuallycreatingeverypiece

ofaWebserviceframeworkisbothtime-consumingandpronetoerrorsbecause

ofhumanmistakes.Fortunately,withframeworksmostoftheworkcanbe

automatedbysoftware.Usinganautomatedtoolismuchadvisedforcreatinga

Webserviceandthesupportingframework.Thetimesavingsinusingsucha

toolwillbehugefrombothadevelopmentandmaintenanceperspective,and

willmorethanmakeupforthecostofusingsuchatool.

NOTE

BecauseaframeworkautomatespartoftheprocessofbuildingaWeb

service,usingonewouldactuallybeahindranceinteachingyouthe

basicsbehindbuildingaWebservice.Thus,thisbookdoesn'tusea

framework.

Thegoodnewsisthatmanycommercialproductsarebeingcreatedtofillthe

needforcreatingandsupportingWebservices.Infact,somanytoolsare

poppingup,thatit'simpossibletogivearecommendationtoanysingleproduct.

Generally,thisbookhasrecommendedusingopensourceproductsbecauseof

thelowcostandgreatsupport.Currently,nosatisfactoryopensourceproducts

existthatwecanrecommendtofillthisneed.Althoughseveraloptionsexist,

noneareuptothelevelofqualityorcompletenessthatwouldearnasolid

recommendation.Eventually,asolidopensourcetoolwillappear;untilthen,

don'thesitatetoevaluatevariouscommercialproductsandchoosethesolution

thatfitsyourneeds.



DesigningaWebService

ThefirststepinthischapterwillbetobuildtheactualWebservice.Designinga

Webserviceisnodifferentthandesigninganyotherprocess—establishinga

solidgoalanddefiningservicerequirementsareveryimportantpartsofthe

actualbuildingoftheservice.



Becausethischapterrepresentsasmallprojectinitself,thegoalsand

requirementsoftheexamplewillbeoutlinedforthereader'sbenefit.



WhatIstheGoal?

EachWebserviceshouldhaveonegoalandonlyonegoal.Ifyouhaveseveral

goals,thenchancesareyouhaveseveralWebservicesthatneedtobebuilt.

Unlikeageneralapplication,whichcanfulfillmanyneeds,Webservicesare

smallerpackagesofworkforasingletask.KeepeachWebserviceassmalland

atomicaspossible.

ThegoaloftheJSPBuzzWebserviceistoproducealistoflinkstopopulatea

newsfeed.EachlinkwilltakethereaderbacktotheoriginalJSPBuzzdocument,

totheexactlocationofthenewsstory.



WhatAretheRequirements?

Therequirementsshouldalwaysbewrittendowninaconciseand

understandablemanner.Fortunately,wehaveasimplesetofrequirementsforthe

JSPBuzzWebservice:

1. Eachlinkinthenewsfeedneedstotaketheuserbacktotheoriginal

pagedisplayingthenewsstory.

TheWebservicewillpermitthereadertotypeinasearchstringtonarrow

whatstoriesareshowninthenewsfeed.

ThecodeinthisversiongetsitsdatafromasingleJSPBuzzissue.However,

thecodeneedstobesetupsothatinthefutureitwillbeeasyfortheprocessto

workagainstmultipleJSPBuzzdocumentsatthesametime.

OneadvantagetobuildingWebservicesisthataWebservicebyitselfisjusta

verysmallandcontrollableproject.Thismakesbuildingrequirementsforthe

Webservicearelativelysimplematter.



WhatDataDoestheServiceNeed?



It'stimetotalkaboutdata.AWebserviceserverdoesn'tneedtobelocatedwith

yourWebserver,whichmeansthataWebserviceserverdoesn'tnecessarilyhave

accesstothesameresourcesasyourWebserver.Inourexample,theSOAPWeb

servercanconvenientlypulltheXMLfilesoutofthexmlbookWebsite.

RemembertomakesureyourWebservicehasconvenient,quickandreliable

accesstoanydatasourceitwillrequire.



BuildingtheWebService

Muchofthecodeinthisexamplewillbefamiliar,asitwillreuseandexpand

muchofwhathasalreadybeenshowninpreviouschapters.Anewchangeisthe

directory.BecausethiscodewillbeusedattheJSPInsidersite,thecodehas

beenplacedwithinthecom.jspinsider.jspbuzzpackage.Forthis

example,thecodewillbeinstalledonthelocalApacheSOAPserver.Thiswill

makeitpossibletorunandtesttheWebservicelocally.Theexamplewilluse

dom4jastheAPItohandletheXMLdocuments.



BuildingaFileHandler

Thefirstclasswe'llbuildisasimplefilehandler.Thisclasswilldetermine

whereallthevariousfilesarelocatedwithinthesystem.Becausethefileswill

bespreadaround,itmakessensetohaveonecentralclasstofindthefiles.Save

thecodeinListing14.1aswebapps/soap/WEB-



INF/classes/com/jspinsider/jspbuzz/BuzzIssues.java

Listing14.1AJavaClasstoDefinetheLocationofXMLFiles



packagecom.jspinsider.jspbuzz;

importjava.io.File;

importorg.dom4j.Document;

importorg.dom4j.io.SAXReader;

publicclassBuzzIssues



{publicBuzzIssues(){}



publicstaticStringls_tomcat_path="c:/java/tomc

publicstaticStringbuzzurl="http://www.jspinsi

publicstaticStringsite_path="webapps/xmlb

publicstaticStringservice_path="webapps/xmlb



publicstaticStringcurrentbuzzXML=

ls_tomcat_path+site_path+



publicstaticStringcurrentbuzzJSP=buzzurl+"bu



publicstaticStringcurrentbuzzXSL=

ls_tomcat_path+service_path



publicStringgetcurrentxml(){returncurrentbuzzXML

publicStringgetcurrentjsp(){returncurrentbuzzJSP

publicStringgetlistingxsl(){returncurrentbuzzXSL

}

Becausethecodefromtheoverallexamplewillbeusedinseveralplaces,itisn't

agoodideatohard-codethefilesinthemainclasses.Instead,thisoneclasswill

trackallthefilesandprovidehelperfunctionstoaccesstheinformation.This

particularversionishard-codedtomaketheexampleeasy.Thefinalproduction

versionwillbedrivenbyanXMLfile.Thisway,newfilescanbeaddedwithout

recompilingtheactualclass.Also,additionalhelpermethodscanbebuiltto

querydirectoriesforthevariousJSPBuzzissues.Thiswouldincreasethe

usefulnessofthisclass.Again,thecodeisnotincludedhere,asit'snotrequired

forthelocalexampletorun.

Youwillhavetoupdatethefollowingline:



publicstaticStringls_tomcat_path="c:/java/tomcat4/

ThefirstthingtonoteisthatthiscodewaswrittenforaWindows-based



machine.YoucanusetheFile.separatorstringtocreateaplatformindependentfilepathsysteminsteadofemployingthehard-codedWindowsbasedseparator(/).IfyouareusingUnixorLinux,youwillhavetomakethe

appropriatechangesforyourfilepath.

It'srequiredtochangethevaluetomatchyourownlocalTomcatdirectory.Also

noticethiscodeassumesthexmlbookdirectoryisinstalledwithinthesameWeb

contextastheSOAPserver.Whilethisisthecaseforthisexample,inthefuture

rememberthatyourSOAPservercouldbelocatedelsewhere,includingona

differentmachine.



BuildingaSearchUtility

TomaketheWebserviceuseful,wewanttheusertobeabletoretrievestories

thatmatchasearchstring.WewillexpandtheQueryElementclassfound

inChapter9,"AdvancedJSPandXMLTechniques,"toperformthistask.

SavetheclassinListing14.2aswebapps/soap/WEB-



INF/classes/com/jspinsider/jspbuzz/QueryElement.java

Listing14.2SearchingforStringMatchesinanXMLElement



packagecom.jspinsider.jspbuzz;

importjava.util.Iterator;

importjava.util.StringTokenizer;

importorg.dom4j.Element;

publicclassQueryElement

{publicQueryElement(){}



publicString[]buildSearchArray(Stringas_search)

{StringTokenizerst=newStringTokenizer(as_searc

intcount=st.countTokens();



intindex=0;

if(count>0)

{String[]tokens=newString[count];

while(st.hasMoreTokens())

{tokens[index]=st.nextToken();

index++;

}

returntokens;

}

returnnull;

}

publicbooleanfindString(Stringsearch,Elementel

{String[]searchlist=buildSearchArray(search);

returnfindString(searchlist,element);

}



publicbooleanfindString(String[]searchlist,Elem

{if(searchlist==null)returnfalse;

for(inti=0;i
{if(findExactString(searchlist[i],element)==

}

returntrue;

}



publicbooleanfindExactString(Stringas_search,El

{as_search=as_search.toLowerCase();

if(element.getText().toLowerCase().indexOf(as_s

Iteratorelementlist=element.elementIterator()



while(elementlist.hasNext())

{Elementchild=(Element)elementlist.next();

booleanlb_test=findString(as_search,child

if(lb_test)returnlb_test;



}

returnfalse;

}

}

Thisclasshasallthefunctionalityoftheoriginalclass.Ithasmerelybeen

expandedtoperformanand-basedsearchonastringarray.Thenewclassalso

containsahelpermethodbuildSearchArray,whichcanbeusedto

tokenizeastringintoanarray.



CreatinganElementHandler

TheWebservicewillbeabletoperformasearchtoselectonlythearticlesauser

askstoread.ThismeansthatitmakessensetobuildtheXMLdocument

representationtoincludeonlythelinkstheuserwantstosee.UsingaSAX

handler,ormorespecificallyadom4jElementHandler,letsyoualso

worktowardstheotherlong-termgoalofbeingabletosearchthroughmultiple

issuesoftheJSPBuzzandcondensetheresultstoasingledom4jDocument.

Althoughthisexamplewon'tcurrentlymergethefiles,theoverallcodestructure

hasbeenbuiltinmodulestosupportthisfutureenhancement.Wewillexpand

theSearchHandlerclassfoundinChapter9toperformthistask.The

classshowninListing14.3shouldbesavedaswebapps/soap/WEB-



INF/classes/com/jspinsider/jspbuzz/SearchHandler.java

Listing14.3AHandlertoOptimizeBuildingadom4jDocument

Object



packagecom.jspinsider.jspbuzz;

importjava.util.Iterator;

importorg.dom4j.Attribute;

importorg.dom4j.Element;

importorg.dom4j.ElementHandler;

importorg.dom4j.ElementPath;



publicclassSearchHandlerimplementsElementHandler

{

privateStringsearch="";

privateString[]searchlist=null;

privateStringlinksource="";



publicvoidsetSearch(Stringas_search)

{search=as_search;

searchlist=testelement.buildSearchArray(as_searc

}



publicvoidsetLinkSource(Stringas_source){links



privateQueryElementtestelement=newQueryElement(



publicSearchHandler(){}

publicSearchHandler(Stringas_search){setSearch(as

publicSearchHandler(Stringas_search,Stringas_sou

{setSearch(as_search);

setLinkSource(as_source);

}

publicvoidonStart(ElementPathpath){}



publicvoidonEnd(ElementPathpath)

{Elementrow=path.getCurrent();

/*RemoveBuzzStoriesthatdon'tmatchthesear

if(search.length()>0)

{if(testelement.findString(searchlist,row)==

row.detach();

else

{attachSource(row);}



}

else

{attachSource(row);}

}



publicvoidattachSource(Elementrow)

{if(linksource.length()>0)

{Attributelink=row.attribute("linkso

if(link==null)

{row.addAttribute("linksource",linksou

else

{link.setValue(linksource);}

}

}

}

Keepinmindthatthedom4jElementHandlerwearecreatinghereis

appliedduringtheSAXprocess,sothiswillbeafastandefficientwaytobuild

theDocumentobject.

Nowlet'sexaminethenewsections.Thefirstbuildsasearcharray.Itwouldn't

makesensetobuildasearcharrayeverytimeanelementisprocessedbythis

class.Instead,whenthesearchstringisinitialized,thecodealsocreatesthe

searcharray:



publicvoidsetSearch(Stringas_search)

{search=as_search;

searchlist=testelement.buildSearchArray(as_search);

}

TheothernewpieceofcodeistheattachSourcemethod:



publicvoidattachSource(Elementrow)

{if(linksource.length()>0)

{Attributelink=row.attribute("linksourc



if(link==null)

{row.addAttribute("linksource",linksource

else

{link.setValue(linksource);}

}

}

ThismethodattachesanewAttributecalledlinksourcetoeachrow

Element.Thebusinessrulebeingenforcedisthateachlinkbeingdisplayed

needstobeabletolinkbacktotheoriginalstorywithinaJSPBuzzpage.The

linksourceattributeisusedtostoretheparentpagecontainingthestory.It

shouldbementionedthattheXMLfilecontainingtheoriginalJSPBuzzdata

doesnotcontainthisdata—andshouldn'tbydesign.AnXMLdocumentshould

onlyknowaboutitselfanditsdataset.Puttinginformationaboutfilesusingthe

XMLdatasetwouldresultinrottendata,becausethissortofdataislikelyto

becomeoutofdate.Whatwouldhappenifthedestinationfileweretochange,or

thepagelocationsweretomove?TheXMLfilewouldbeleftwithbaddata

embeddedwithinit.

Theotherproblemarisesfromtherequirementthatthisprocesswilllatermerge

togetherdozensofJSPBuzznewsletters.Weneedawaytoembedreliable

informationforeachlinkdisplayedtotheuser.

Thebestsolutionistopassintheparentpagereferenceforeachindividuallink

astheXMLdocumentisparsed.Then,whenwedomergemultipledocuments,

eachlinkwillsafelyhaveareferencetoitsparentpage,orthelinksource

attributeinthiscase.Thisattributeisnotusedbytheoriginaldocument.Instead,

it'susedbythetemporarydom4jDocumenttoinformastylesheethowto

buildareferencelink.Thisway,eachkeptlinkwillalwayshaveacorrectand

up-to-datereferencetotheJSPpagedisplayingtheoriginalstory.

Thepagebeingsetwithinthelinksourceattributeispassedinjustbefore

thedocumentisparsedwiththesetLinkSourcemethod:



publicvoidsetLinkSource(Stringas_source){linksour



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 14. Building a Web Service

Tải bản đầy đủ ngay(0 tr)

×