Tải bản đầy đủ - 0 (trang)
Chapter 4. Java Naming and Directory Interface

Chapter 4. Java Naming and Directory Interface

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

WhyApplicationsNeedNamingandDirectoryServices

Afundamentalfacilityofanyenterpriseapplicationisthe

capabilitytolocatecomponentsandservices.Aclientwishingto

locateacomponentorserviceinanenterprisetypicallywill

knowthenameofthecomponentorservice,butprobablywill

beunawareofthephysicallocationofthatcomponent.The

nameofthecomponentusuallyisanaliasoruser-friendly

substitutionfortherealname,whichmightbemoreofa

computer-friendlyname.ThisissimilartohowtheInternet

DomainNameService(DNS)mapsmachinenames,suchas

www.apache.org,toInternetProtocol(IP)addressessuchas

64.208.42.41.

Buildingsoftwareapplicationswherecomponentsandservices

aredecentralizedthroughouttheenterpriseincreasestheneed

foranamingservicewhencomparedtoamoretraditionaltwotierclient/serverapplication.Inamulti-tierenterprise

application,youtypicallyhavetheClienttier(browser),Web

tier(Webserver),Applicationtier(applicationserver),andthe

EnterpriseInformationSystemtier(RDBMSandERPsystems).

Allthesetierscanbelocatedondifferentmachines.

Sonowthatcomponentsarespreadthroughoutthenetwork,

howdotheyfindeachotherwhentheyneedtorequestservices

fromoneanother?Thewholeideaofseparatingservicesinto

componentsistoassignresponsibilitiesandtoallowfor

componentstoinvokerequestsonothercomponents.They

needawaytolocateeachotherthatistransparent.By

transparent,wemeanthattheclientcomponentdoesnotknow

theexactphysicallocationoftheservercomponent.For

example,ifwehadanOrderFulfillmentcomponentthat

wascalledbytheWebtier,andtheOrderFulfillment

componentmovedtoadifferentphysicalserver,itshouldnot

negativelyaffecttheothercomponentsthatuseitsservices.

Thereasonwhyenterpriseapplicationsneedsometypeof



namingand/ordirectoryserviceistohelplocateeachotherin

thisvastexpansewecalltheenterprise.Remember,foran

enterpriseapplication,acomponentmightbeaclientinone

requestandthenaserverinanother.

Forenterpriseapplications,anaminganddirectoryservice

providesameansbywhichyourapplicationcanlocatea

referencetoneededservices.TheservicemightbeaJDBC

datasource,aJMSconnectionfactory,areferencetoahome

interfaceforanenterprisebean,oranyotherobjectordata

thatisneededbytheenterprise.

Naminganddirectoryserviceseachprovideadistinctpurpose

foruseinenterpriseapplications.Althoughwe'lldescribeeach

servicebrieflyinthenextsection,ouraimistounderstandthe

namingservice.We'llnotspendanyconsiderableamountof

timeondirectoryservicesotherthantodescribewhattheyare.

Forthepurposeofthisbook,it'sthenamingservicethatwe

needtounderstand.



NamingService

Anamingserviceisanapplicationthatholdsontoacollection

ofobjectsorreferencestoobjectsandassociatesauserfriendlynamewitheachone.Thisassociationisknownasa

binding.Figure4.1showsanexampleofabinding.

Figure4.1.Anexampleofanamingservicebinding.



Aresourceboundtoanamecanbeanobjectorpossiblya

referencetoanobjectthatresidessomewhereelseonthe

reachablenetwork.Forexample,youcouldbuildaHashtable

withdatainitandstorethisobjectintoanamingserviceand

associateitwithaname.YoucouldalsobuildaHashtableand

createanRMIservertoaccessthatHashtableandassociate

theRMIstubwithaname.Ineithercase,clientswhowantedto

gettheinformationfromtheHashtablecouldconnecttothe

namingserviceandfinditbyusingthenamethatitwas

associatedwith.

Note

Howyougoaboutconnectingtoanamingservice

andlocatingobjectsinitarecoveredlaterinthis

chapter.



Thisissimilartoaphonebook,ifyouuseyourimaginationa

bit.Inaphonebook,let'ssaythename"Fred'sPlumbing

Service"pointstoanadvertisementforaplumbingservice.I

usethenameoftheservicetolocatethetelephonenumber,

whichisjustareferencetotheactualservice.IfIwantedto

makearequestontheservice,Iwouldhavetofollowthe

reference,inthiscasemakeaphonecall.Ifwewerereferring

toanactualnamingserviceinsteadofaphonenumber,we

mightlocateanRMIproxyobject.Inthatcase,wecouldfollow

thereferenceandinvokemethodsontheremoteobject.

ThisalsoisanalogouswithhowaDNSworks.Whenyoulookup

aWebsiteaddresssuchasjava.sun.com,theDNSdoesn't

storethesun.comdomain;itstoresareferencetotheIP

addressthathasbeenassociatedwiththisdomain.UsingtheIP

address,aclientcangetintouchwiththeWebsitebyusingthe

address204.160.241.48.

Figure4.2showshowreferencescanbestoredaswellas



objectsinanamingservice.

Figure4.2.Namingservicescanstorereferencesaswell

astheobjectdata.



Acollectionofinterconnectedbindingsmakeupsomething

calledanamespace.Alltelephonenumbersinaphonebook,for

example,couldbeconsideredanamespace,justasthe

sun.comdomainisessentiallyanamespace.Thenaming

serviceisresponsibleformanagingthebindingswithinthe

namespace.Forenterpriseapplications,youcanlocatea

resourcewithinanamespacebyusingtheuser-friendlyname

andgettingtheresourcethatisassociatedwiththatname.

Figure4.3showshowbindingsandnamespacesarerelated.

Figure4.3.Namespacesaremadeupofasetofbindings.



DirectoryServices

ADirectoryserviceisjustanextensionofthefeaturesprovided

byanamingservice.Directoryservicesallowattributestobe

associatedwithabinding.Clientscanuseadirectoryserviceto

searchforaspecificbindingwithspecificattributevalues.

We'lluseoneofthemostcommonexamplestodescribehow

youmightuseadirectoryservice.Let'ssayanorganizationhas

severalprintersandeachoneoftheseprintersisaccessible

throughanaminganddirectoryservice.Eachprinterinthe

directoryservicecouldhaveanattributethatsayswhetheror

notitcanprintinduplexmode(thismeansonbothsides).A

clientcouldfindaprinterinthedirectoryservicebyfiltering

bindingswheretheduplexmodeistrue.

Thefollowingisalistofsomecommondirectoryservice

implementations:



LightweightDirectoryAccessProtocol(LDAP)

NetworkDirectoryService(NDS)

NetworkInformationServicePlus(NIS+)

X.500



OverviewoftheJNDIArchitecture

TheJavaNamingandDirectoryInterface(JNDI)enablesJava

clientstohaveaccesstovariousnaminganddirectoryservices.

LikeotherthingsintheJ2EESpecification,JNDIprovidesaset

ofAPIsthatcontainJavainterfacesandclasses.

JNDIisdividedintofivecorepackages:



javax.naming

java.naming.directory

javax.naming.event

javax.naming.ldap

javax.naming.spi

FormostEJBapplications,thenamingservicefeaturesareused

morethanthedirectoryservicefeatures.Thedirectoryservice

featuresareveryimportantbutarealittleoutofscopeforthis

book.WewillcoverthenamingserviceonlyasitrelatestoEJB.

Ifyouareinterestedinmoreinformationonthedirectory

servicefeaturesofferedthroughJNDI,seetheSunJNDIsite:

http://java.sun.com/products/jndi

Becausewearefocusingstrictlyonthenamingservice

features,wewilllookexclusivelyatthejavax.naming

package.

Youmusthaveavendor-providedimplementationtotake

advantageofJNDIservices.ThisissimilartotheJavaDatabase

Connectivity(JDBC)APIwhereyoumusthaveaJDBCdriverto



usetheJDBCAPIstoconnecttoadatabase.WithJNDI,the

vendor-providedimplementationisknownasaServiceProvider

Interface(SPI),anditallowstheJNDImethodstobecalledon

aparticularnamingservice.Figure4.4showshowanSPI

providestheimplementationbehindtheAPIs.

Figure4.4.JavaclientsusetheJNDIAPIsandaService

ProviderInterfacetotakeadvantageofnamingand

directoryservices.



TheSPIenablesJNDItoconnecttoaparticularnamingservice

implementationanditwrapstheproprietarynamingservice

APIswiththeonesdefinedbyJNDI.TheSPImapstheJNDI

callstoonesthataparticularnamingservicecanunderstand.

ThisallowstheclienttousetheJNDIAPIsonlyandtoswitch

betweendifferentnamingserviceswithoutnegativelyaffecting

theclientapplication.Infact,aclientcannavigatefromone

typeofnamingservicetoanotherusingJNDIwithoutknowing

it.Forexample,abindingfromanLDAPservermighthavea

referencetoanobjectthatexistsinanRMIRegistrynaming

service.AslongastheclientusestheJNDIAPI,thetransition

fromonenamingservicetoanotherwillbetransparent.Allthe



proprietarycodefortheparticularnamingserviceis

encapsulatedwithintheSPI.



TheAvailableJNDIServiceProviders

Thereareseveraldifferenttypesofnamingservices.Thereisa

JNDIimplementationformostofthedifferenttypes.Therealso

mightbedifferentprovidersforaparticulartype.Forexample,

bothIonaandInprisehaveaCommonObjectServices(COS)

nameservicewithintheirCORBAproducts.YoucanuseJNDIto

accessbothofthem.ThefollowingisalistoftheJNDI

implementationsavailable:

LightweightDirectoryAccessProtocol(LDAP)

CORBACommonObjectServices(COS)NameService

RMIRegistry

NIS(Sun'sversionforNetworkInformationService)

DSML(Sun'sversionforDirectoryServicesMarkup

Language)

DNS(DomainNameSystem)

FileSystem(thefilesystemcanbeusedasanaming

service)

Someofthesearestillbetareleases.Thelistisbeingaddedto

frequently.Togetacurrentlistofimplementationsthatare

available,seethelistmaintainedontheSunsiteat

http://java.sun.com/products/jndi/serviceproviders.html



Lookingatthedifferenttypesofnamingservices,youmightbe

abletoimaginethatnotallnamingservicesarecreatedequal.

Thewayinwhichtheystorebindinginformationorallowclients

tolocatecertainbindingscanbeverydifferent.Eachnaming

servicemightstoretheinformationinaslightlydifferentformat

thananother.Becausesomenamesinabindingmightpointto

anothernameinadifferentbinding,mostnamingservicesstore

thebindingsinahierarchicalfashion.However,themannerin

whichaclientseesthishierarchyandnavigatesthroughitcan

becompletelydifferentfromonenamingservicetoanother.For

example,theDNSusesdots(".")toseparatethebindings,asin

www.sun.com.LDAP,ontheotherhand,usesacompletely

differentformat.Becausenamingservicescanbesodifferent,

theremustbeaJavawayofhidingthenamingservice-specific

detailsandallowingforasingleAPI.Thisisthepurposeof

JNDI.JNDIallowsaclienttoseeallthesedifferentnaming

servicesinthesameway.



SelectingandConfiguringaJNDIProvider

AswithvirtuallyeveryotherJavatechnology,JNDImustbe

properlyconfiguredbeforeyoucanbegintouseit.Thisis

mainlyduetotheseparationofinterfacesandimplementation.

Thenamingservicemustbeproperlyconfiguredsothatan

installedproviderwillhandletheworkwhenaclientusesthe

JNDIAPIs.Also,anyclientapplicationthatwantstousethe

namingservicemustalsobeproperlyconfiguredsothatitcan

locatethenamingserviceandthenlookupresourceswithinit.

ConfiguringJNDIsometimescancausegreatfrustrationunless

youreallyunderstandwhatyouaretryingtosetupandwhy.

WhenusinganEJBserver,JNDIisusuallyalreadyconfigured

fortheserverandstartsupwhentheEJBserverstartsup.The

onlypartthatyoutypicallyneedtoconfigureistheclient

applicationthatislookingforhomeorremotereferences.The

EJBservertypicallyhasanimplementationthathandlesthe

JNDIservice,andyoujustneedtoknowhowtofindand

connecttoit.

ToprovideyouwithalittlemoredepthaboutJNDIandhowitis

used,wewilltakeyouthroughthestepsofsettingupyourown

JNDInamingserviceandnotusingtheoneprovidedwiththe

EJBserver.Thisshouldgiveyoualittlemoreinsightonwhat's

goingonwithintheEJBserverforJNDIandhowanSPIreally

handlestheservice,notjusttheJNDIAPIs.

Note

Toreiterate,ifyouareusinganEJBserver,youwill

typicallynothavetosetupyourownJNDIservice.

TheJNDIserverconfigurationistakencareofby

mostEJBservers.However,youstillwillneedtoset

uptheclientapplicationsthatneedtouseJNDI.



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

Chapter 4. Java Naming and Directory Interface

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

×