Tải bản đầy đủ - 0 (trang)
Chapter 5. The Remote and Local Client View

Chapter 5. The Remote and Local Client View

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

5.1LocatingBeanswithJNDI

InChapter4,theclientapplicationstartedbycreatingan

InitialContext,whichitthenusedtogetaremotereference

tothehomesoftheCabinandTravelAgentEJBs.The

InitialContextispartofalargerAPIcalledtheJavaNaming

andDirectoryInterface(JNDI).WeuseJNDItolookupanEJB

homeinanEJBserverjustlikewemightuseaphonebookto

findthehomenumberofafriendorbusinessassociate.

JNDIisastandardJavapackagethatprovidesauniformAPIfor

accessingawiderangeofservices.Itissomewhatsimilarto

JDBC,whichprovidesuniformaccesstodifferentrelational

databases.JustasJDBCletsuswritecodethatdoesn'tcare

whetherit'stalkingtoanOracledatabaseoraDB2database,

JNDIletsuswritecodethatcanaccessdifferentdirectoryand

namingservices,includingthenamingservicesprovidedbyEJB

servers.EJBserversarerequiredtosupportJNDIbyorganizing

beansintoadirectorystructureandprovidingaJNDIdriver,

calledaserviceprovider,foraccessingthatdirectorystructure.

UsingJNDI,anenterprisecanorganizeitsbeans,services,

data,andotherresourcesinaunifieddirectory.

TwoofJNDI'sgreatestfeaturesarethatitisvirtualand

dynamic.JNDIisvirtualbecauseitallowsonedirectoryservice

tobelinkedtoanotherthroughsimpleURLs.TheURLsinJNDI

areanalogoustoHTMLlinks.JustasanHTMLlinkallowsyouto

downloadanewpagewithoutworryingabouttheserveron

whichthatpageislocated,JNDIletsusdrilldownthrough

directoriestofiles,printers,andEJBhomeobjectswithout

knowingwheretheresourcesoreventhedirectoryservers

holdinginformationabouttheresourcesarelocated.The

directoriesandsubdirectoriescanbelocatedinthesamehost

orphysicallyhostedatdifferentlocations.Asdevelopersor

administrators,wecancreatevirtualdirectoriesthatspana

varietyofservicesovermanydifferentphysicallocations.



JNDIisdynamicbecauseitallowstheJNDIdrivers(a.k.a.

serviceproviders)forspecifictypesofdirectoryservicestobe

loadedatruntime.Adrivermapsaspecifickindofdirectory

serviceintothestandardJNDIclassinterfaces.Whenalinktoa

differentdirectoryserviceischosen,thedriverforthattypeof

directoryserviceisautomaticallyloadedfromthedirectory's

host,ifitisnotalreadyresidentontheuser'smachine.

AutomaticallydownloadingJNDIdriversmakesitpossiblefora

clienttonavigateacrossarbitrarydirectoryserviceswithout

knowinginadvancewhatkindsofservicesitislikelytofind.

Aftertheclientapplicationlocatesandobtainsaremote

referencetotheEJBhomeusingJNDI,theclientcanusethe

EJBhometoobtainanEJBobjectreferencetoanenterprise

bean.InChapter4theclientapplicationsusedthemethod

getInitialContext()togetaJNDIInitialContextobject,

whichlookedlikethis:

publicstaticContextgetInitialContext()

throwsjavax.naming.NamingException{



Propertiesp=newProperties();

//...SpecifytheJNDIpropertiesspecifictothevendor.

returnnewjavax.naming.InitialContext(p);

}



AninitialcontextisthestartingpointforanyJNDIlookupit's

similarinconcepttotherootofafilesystem.Thewayaninitial

contextiscreatedispeculiar,butnotfundamentallydifficult.We



startwithapropertiestableoftypeProperties.Thisis

essentiallyahashtabletowhichweaddvariousvaluesthat

determinethekindofinitialcontextyouget.Ofcourse,as

mentionedinChapter4,thiscodedependsonhowourEJB

vendorhasimplementedJNDI.Forexample,withthePramati

ApplicationServer,getInitialContext()mightlook

somethinglikethis:

publicstaticContextgetInitialContext()throwsException{

Hashtablep=newHashtable();

p.put(Context.INITIAL_CONTEXT_FACTORY,



"com.pramati.naming.client.PramatiClientContextFactory

p.put(Context.PROVIDER_URL,"rmi://127.0.0.1:9191");

returnnewInitialContext(p);

}



ForamoredetailedexplanationofJNDI,seeO'Reilly'sJava

EnterpriseinaNutshellbyDavidFlanagan,JimFarley,William

Crawford,andKrisMagnusson.



5.2TheRemoteClientAPI

Enterprisebeandevelopersarerequiredtoprovideabean

class,componentinterfaces,and,forentitybeans,aprimary

key.Thecomponentinterfacesandprimarykeyclassarevisible

totheclient;thebeanclassitselfisnot.Thecomponent

interfacesandprimarykeycontributetotheclient-sideAPIin

EJB.

Anyclient,whetheritisinthesamecontainersystemornot,

mayusetheRemoteClientAPI,whichmeansthatitmayuse

theremoteinterface,theremotehomeinterface,andJavaRMI

toaccessentityandsessionbeans.Enterprisebeansthatare

locatedinthesameEJBcontainerhavetheoptionofusingthe

LocalClientAPI.TheLocalClientAPIprovideslocalcomponent

interfacesandavoidstherestrictionsandoverheadofthe

RemoteClientAPI.Thissectionexaminestheremote

componentinterfacesandtheprimarykey,aswellasother

JavatypesthatmakeupEJB'sremoteclient-sideAPI.



5.2.1JavaRMI-IIOP

EnterpriseJavaBeansdefinesanenterprisebean'sremoteclient

APIintermsofJavaRMI-IIOP,whichenforcescompliancewith

CORBA.Thismeansthattheunderlyingprotocolusedby

remoteclientstoaccessenterprisebeanscanbeanythingthe

vendorwantsaslongasitsupportsthetypesofinterfacesand

argumentsthatarecompatiblewithJavaRMI-IIOP.However,in

additiontoanyproprietaryprotocols,vendorsmustalso

supporttheCORBAIIOP1.2protocolasdefinedintheCORBA

2.3.1specification.

TousetheRemoteClientAPI,defineyourcomponentinterfaces

andargumenttypessothattheycomplywithJavaRMI-IIOP



types.It'snotallthatdifficulttocomplywiththisrestriction.

ThenextfewsectionsdiscusstheJavaRMI-IIOPprogramming

modelforEJB.



5.2.1.1JavaRMIreturntypes,parameters,and

exceptions

AsanimplementationofJavaRMI,JavaRMI-IIOPmustfirst

complywiththebasicrestrictionsofJavaRMI.We'llfirsttakea

lookatJavaRMIrestrictionsandthenproceedtoexamine

additionrestrictionsimposedbyJavaRMI-IIOP.

Thesupertypesoftheremotehomeinterfaceandremote

interface,javax.ejb.EJBHomeandjavax.ejb.EJBObject,both

extendjava.rmi.Remote.AsRemoteinterfacesubtypes,they

areexpectedtoadheretotheJavaRMIspecificationforRemote

interfaces.



5.2.1.2Returntypesandparameters

Theremotecomponentinterfacesmustfollowseveral

guidelines,someofwhichapplytothereturntypesand

parametersthatareallowed.Therearetwokindsofreturnand

parametertypes:declaredtypes,whicharecheckedbythe

compiler,andactualtypes,whicharecheckedbytheruntime.

JavaRMIrequirestheuseofactualtypes.Theactualtypes

usedinthejava.rmi.Remoteinterfacesmustbeprimitives,

java.rmi.Remotetypes,orserializabletypes(includingthe

Stringtype).java.rmi.Remotetypesandserializabletypesdo

nothavetoimplementjava.rmi.Remoteand

java.io.Serializableexplicitly.Forexample,the

java.util.Collectiontype,whichdoesnotexplicitlyextend

java.io.Serializable,isaperfectlyvalidreturntypefora

remotefindermethod,providedthattheconcreteclass



implementingCollection,theactualtype,doesimplement

java.io.Serializable.

JavaRMIhasnospecialrulesregardingdeclaredreturntypesor

parametertypes.Atruntime,atypethatisnota

java.rmi.Remotetypeisassumedtobeserializable;ifitisnot,

anexceptionisthrown.Theactualtypethatispassedcannot

becheckedbythecompiler;itmustbecheckedatruntime.

Hereisalistofthetypesthatcanbepassedasparametersor

returnedinJavaRMI:



Primitives

Theseincludebyte,boolean,char,short,int,long,

double,andfloat.



Javaserializabletypes

Anyclassthatimplementsoranyinterfacethatextends

java.io.Serializable.



JavaRMIremotetypes

Anyclassthatimplementsoranyinterfacethatextends

java.rmi.Remote.

Serializableobjectsarepassedbycopy(a.k.a.passedby

value),notbyreference,whichmeansthatchangesina

serializedobjectononetierarenotautomaticallyreflectedon

theothers.ObjectsthatimplementRemote,like

TravelAgentRemoteorCabinRemote,arepassedasremote

references,whicharealittledifferent.Aremotereferenceisa



Remoteinterfaceimplementedbyadistributedobjectstub.

Whenaremotereferenceispassedasaparameterorreturned

fromamethod,thestubisserializedandpassedbyvalue,not

theobjectreferencedbythestub.InChapter11,thehome

interfacefortheTravelAgentEJBismodifiedsothatthe

create()methodtakesareferencetoaCustomerEJBasits

onlyargument:



publicinterfaceTravelAgentHomeRemoteextendsjavax.ejb.EJBHom

publicTravelAgentRemotecreate(CustomerRemotecustomer)

throwsRemoteException,CreateException;

}



ThecustomerargumentisaremotereferencetoaCustomer

EJBthatispassedintothecreate()method.Whenaremote

referenceispassedorreturnedinEnterpriseJavaBeans,the

EJBobjectstubispassedbycopy.ThecopyoftheEJBobject

stubpointstothesameEJBobjectastheoriginalstub.

Therefore,boththeenterprisebeaninstanceandtheclient

haveremotereferencestothesameEJBobject.Changesmade

ontheclientusingtheremotereferencewillbereflectedwhen

theenterprisebeaninstanceusesthesameremotereference.

FiguresFigure5-1andFigure5-2showthedifferencebetween

aserializableobjectandaremotereferenceargument.



Figure5-1.Serializablearguments



Figure5-2.Remotereferenceargumentsin

RMIExceptions



TheRMIspecificationstatesthateverymethoddefinedina

Remoteinterfacemustthrowthejava.rmi.RemoteException.

TheRemoteExceptionisusedwhenproblemsoccurwith

distributedobjectcommunications,suchasanetworkfailureor

inabilitytolocatetheobjectserver.Remoteinterfacescanalso

throwapplication-specificexceptions(exceptionsdefinedbythe

applicationdeveloper).Thefollowingcodeshowstheremote

interfacetotheTravelAgentEJBdiscussedinChapter2.The

bookPassage()methodintheTravelAgentRemoteinterface

throwstheRemoteException(asrequired)inadditiontoan

applicationexception,IncompleteConversationalState:



publicinterfaceTravelAgentRemoteextendsjavax.ejb.EJBObject



publicvoidsetCruiseID(intcruise)

throwsRemoteException,FinderException;

publicintgetCruiseID()throwsRemoteException;



publicvoidsetCabinID(intcabin)

throwsRemoteException,FinderException;

publicintgetCabinID()throwsRemoteException;



publicintgetCustomerID()throwsRemoteException;





publicTicketbookPassage(CreditCardRemotecard,doublepri

throwsRemoteException,IncompleteConversationalState;



publicString[]listAvailableCabins(intbedCount)

throwsRemoteException;



}



5.2.1.3JavaRMI-IIOPtyperestrictions

AlongwiththeJavaRMIprogrammingmodel,JavaRMI-IIOP

imposesrestrictionsontheremoteinterfacesandvaluetypes

usedintheRemoteClientAPI.Therestrictionsarebornof

limitationsintheInterfaceDefinitionLanguage(IDL)upon

whichCORBAIIOP1.2isbased.Theexactnatureofthese

limitationsisoutsidethescopeofthisbook.Herearetwo;the

others,likeIDLnamecollisions,arerarelyencountered:[1]

[1]TolearnmoreaboutCORBAIDLanditsmappingtotheJavalanguage,consult"TheCommon

ObjectRequestBroker:ArchitectureandSpecification"and"TheJavaLanguagetoIDLMapping,"

bothavailableattheOMGwebsite(http://www.omg.org).



Methodoverloadingisrestricted;aremoteinterfacemay

notdirectlyextendtwoormoreinterfacesthathave

methodswiththesamename(eveniftheirargumentsare

different).Aremoteinterfacemay,however,overloadits

ownmethodsandextendaremoteinterfacewith



overloadedmethodnames.Overloadingisviewed,here,as

includingoverriding.Figure5-3illustratesbothofthese

situations.

Serializabletypesmustnotdirectlyorindirectlyimplement

thejava.rmi.Remoteinterface.



Figure5-3.Overloadingrulesforremoteinterface

inheritance



5.2.1.4Explicitnarrowingusing

PortableRemoteObject

InJavaRMI-IIOP,remotereferencesmustbeexplicitly

narrowedusingthe

javax.rmi.PortableRemoteObject.narrow()method.The

typicalpracticeinJavaistocastthereferencetothemore

specifictype:

javax.naming.ContextjndiContext;



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

Chapter 5. The Remote and Local Client View

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

×