JNDI pregled, 3. dio: Napredni JNDI

Ovaj mjesec moram pokriti puno zemlje, pa ću izostaviti paperje i presjeći točno do metaka. Prvo, imenovanje Java i sučelje direktorija igra važnu ulogu u nekoliko Java tehnologija. Pogledat ćemo ovu ulogu kako bismo bolje razumjeli strateški položaj JNDI-a u cjelokupnoj Java slici. Dalje, prepoznajući vašu potrebu za radom JNDI usluge s kojom ću se poigrati, upoznat ću vas s slobodno dostupnom, prijenosnom implementacijom LDAP-a i naučit ću vas kako se povezati i koristiti JNDI davatelja usluga. Na kraju ću vas detaljno upoznati s povezivanjem objekata na unose u JNDI.

TEXTBOX:

TEXTBOX_HEAD: JNDI pregled: Pročitajte cijelu seriju!

  • Dio 1. Uvod u usluge imenovanja

  • Dio 2. Koristite JNDI usluge direktorija za bolje upravljanje distribuiranim aplikacijama

  • Dio 3. Koristite JNDI za spremanje objekata vaše distribuirane aplikacije

  • Dio 4. Spojite ono što ste naučili s aplikacijom s omogućenom JNDI

: END_TEXTBOX

Prije nego što započnem, malo je dvostrukog razmišljanja. Tijekom posljednja dva mjeseca pokušao sam vas uvjeriti da su imenovanje i imeničke usluge približno elektronički ekvivalent kataloga kartica koji se nalaze u knjižnicama. Sada, kad započinjemo obilazak naprednih značajki JNDI-ja, želim da u potpunosti zaboravite ovu analogiju - ona grubo potcjenjuje moć JNDI-ja.

Počnimo s pogledom na to kako se JNDI pojavljuje u drugim Java tehnologijama.

JNDI posvuda

JNDI igra ulogu u brojnim Java tehnologijama. Razmotrimo tri od njih: JDBC (paket povezivanja Java baze podataka), JMS (Java Messaging Service) i EJB (Enterprise JavaBeans).

JDBC je Java tehnologija za relacijske baze podataka. JNDI se prvi put pojavio u dodatnom paketu JDBC 2.0 (vidi Resursi) zajedno sa DataSourcesučeljem. DataSourcePrimjer, kao što joj i ime kaže, predstavlja izvor podataka - često iz baze podataka, ali ne uvijek. DataSourceInstance pohranjuje informacije o izvoru podataka - kao što su ime, vozača za učitavanje i korištenje, i njegov položaj - i omogućuje zahtjev za dobivanje vezu s izvorom podataka, bez obzira na temeljne pojedinosti. Specifikacija JDBC preporučuje upotrebu JNDI za spremanje DataSourceobjekata.

JMS je Java tehnologija za razmjenu poruka. JMS specifikacija opisuje upravljane objekte - objekte koji sadrže informacije o JMS konfiguraciji i koje JMS klijenti koriste za lociranje određenih redova poruka i tema. Kao što je slučaj s JDBC, specifikacija preporučuje lociranje objekata kojima upravlja JMS putem JNDI.

Na kraju, razmotrite Enterprise JavaBeans. Svi grahovi poduzeća objavljuju matično sučelje - jedinstveno mjesto putem kojeg klijenti pronalaze određeni grah tvrtke - putem JNDI.

Što JNDI donosi na stol zbog čega je tako cijenjen?

Prvo, JNDI promiče pojam centralno upravljanog izvora informacija - ključni zahtjev za poslovne aplikacije. Centralno upravljanim izvorom informacija lakše je upravljati nego distribuiranom zbirkom izvora podataka. Također je jednostavnije za klijente da pronađu potrebne podatke ako moraju tražiti samo jedno mjesto.

Drugo, kao što ćete vidjeti, sposobnost JNDI-a da izravno pohranjuje Java objekte omogućuje mu da se gotovo transparentno integrira u Java programe.

Poanta davatelja

Da biste koristili JNDI, trebaju vam usluga imenovanja i imenika i davatelj usluga JNDI. Sun nudi nekoliko davatelja usluga zajedničkog imenovanja i direktorija (COS imenovanje, NIS, RMI registar, LDAP i još mnogo toga). Odlučio sam se za LDAP.

LDAP (lagani protokol za pristup direktoriju) ima dvostruke prednosti široke primjene (kako u komercijalnim, tako i u besplatnim oblicima) i relativno jednostavne upotrebe. Njegove značajke također dobro podržava Sunov pružatelj LDAP usluga i JNDI.

Budući da pribavljanje i konfiguriranje LDAP poslužitelja zapravo nije predmet Java, samo ću vas uputiti u pravom smjeru i pružiti vam reference na internetske resurse.

Dostupne su brojne implementacije LDAP-a. Mnogi su komercijalni proizvodi kao što su Netscape Directory Server i IBM-ov Secure Way Directory. Neki su pakirani u sklopu veće ponude (Microsoftov Active Directory dio je sustava Windows 2000). Ako imate pristup takvoj implementaciji, možete preskočiti veći dio ovog odjeljka. Inače, opisat ću OpenLDAP - slobodno dostupnu implementaciju LDAP-a koja se temelji na referentnoj implementaciji Sveučilišta Michigan - kao i njegovu instalaciju i konfiguraciju.

OpenLDAP je dostupan kod OpenLDAP Foundation (vidi Resursi). Njegova se licenca temelji na Perlovoj "umjetničkoj licenci", što znači da je OpenLDAP besplatan (ili otvoren izvor) softver. Predpakirani binarni programi dostupni su za različite okuse Linuxa (Debian, Red Hat), kao i BSD Unix. U tijeku su radovi na priključku na Windows NT.

Ako planirate instalirati OpenLDAP, trebali biste pročitati Vodič za administratore SLAPD i SLURPD (slapd je ime izvršne datoteke LDAP poslužitelja, a slurpd je ime poslužitelja replikacije LDAP; za to mjesto pogledajte Resursi).

I have one final suggestion to make your entire experience more pleasing: no matter which LDAP implementation you use, turn schema checking off. An LDAP schema, like a database schema, defines constraints on the stored information. In normal use, schema checking helps ensure that entries (think of address book entries) conform to the correct format. However, since you'll probably be playing rather than building something of lasting significance, schema checking will just get in the way. Take my word for it.

Connecting to a JNDI context

In previous articles, I tried to avoid explaining in detail how to interact with a JNDI service provider such as the LDAP service provider. I mentioned that you need an initial context to do JNDI operations, but I didn't spend much time telling you how to get one. Let me fill in the gaps. (For more on initial contexts, see the first two articles in this series.)

Before you can do anything with JNDI, you need an initial context. All operations are performed relative to the context or one of its subcontexts.

Obtaining an initial context requires three steps:

  1. First, select a service provider. If you're going to use OpenLDAP or some other LDAP implementation, Sun supplies a reference LDAP service provider (see Resources). Add the name of the service provider to the set of environment properties (stored in a Hashtable instance):

     Hashtable hashtableEnvironment = new Hashtable(); hashtableEnvironment.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" ); 
  2. Add any extra information the service provider requires. For LDAP, that includes the URL that identifies the service, the root context, and the name and password to connect with:

     // the service: ldap://localhost:389/ // the root context: dc=etcee,dc=com hashtableEnvironment.put( Context.PROVIDER_URL, "ldap://localhost:389/dc=etcee,dc=com" ); hashtableEnvironment.put( Context.SECURITY_PRINCIPAL, "name" ); hashtableEnvironment.put( Context.SECURITY_CREDENTIALS, "password" ); 
  3. Finally, get the initial context. If you just intend to perform naming operations, you'll only need a Context instance. If you intend to perform a directory operation as well, you'll need a DirContext instance instead. Not all providers supply both:

     Context context = new InitialContext(hashtableEnvironment); 

    Or:

     DirContext dircontext = new InitialDirContext(hashtableEnvironment); 

That's all there is to it. Now let's look at how applications store objects to and retrieve objects from JNDI.

Work with objects

The ability to store Java objects is useful: object storage provides persistence and allows objects to be shared between applications or between different executions of the same application.

From the standpoint of the code involved, object storage is surprisingly easy:

 context.bind("name", object) 

The bind() operation binds a name to a Java object. The syntax of the command is reminiscent of RMI, but the semantics are not as clearly defined. It's permissible for the bind() operation to store either a snapshot of the object or a reference to a "live" object, for example.

Be aware that the bind() operation throws a NamingException if an exception occurs during the execution of the operation.

Now let's take a look at the bind() operation's complement -- lookup():

 Object object = context.lookup("name") 

The lookup() operation retrieves the object bound to the specified name. Once again, the syntax is reminiscent of RMI, but the method's semantics are not as clearly defined.

Just as with bind(), the lookup() operation throws a NamingException if an exception occurs during the execution of the operation.

Object storage

What does it mean to store an object in a JNDI naming and directory service? We've already mentioned that the exact semantics of the bind() and lookup() operations aren't tightly defined; it's up to the JNDI service provider to define their semantics.

According to the JNDI specification, service providers are encouraged (but not required) to support object storage in one of the following formats:

  • Serialized data
  • Reference
  • Attributes in a directory context

If all JNDI service providers support these standard mechanisms, Java programmers are free to develop generic solutions that work even when the underlying service provider layer changes.

Each of the methods above has advantages and disadvantages. The best method will depend on the requirements of the application under development.

Let's consider each in turn.

As serialized data

The most obvious approach to storing an object in a directory is to store the serialized representation of an object. The only requirement is that the object's class implement the Serializable interface.

When an object is serialized, its state becomes transformed into a stream of bytes. The service provider takes the stream of bytes and stores it in the directory. When a client looks up the object, the service provider reconstructs it from the stored data.

The following code demonstrates how to bind a LinkedList to an entry in an JNDI service:

 // create linked list LinkedList linkedlist = new LinkedList(); . . . // bind context.bind("cn=foo", linkedlist); . . . // lookup linkedlist = (LinkedList)context.lookup("cn=foo"); 

It's that easy!

Unfortunately, the other two methods are more complicated. I will describe them briefly but reserve a detailed discussion for a later date.

As a reference

Sometimes it's not appropriate (or possible) to serialize an object. If the object provides a service on a network, for example, it doesn't make sense to store the state of the object itself. We're interested in the information necessary to find and communicate with the object.

An example is a connection to an external resource (one outside the scope of the Java Virtual Machine) such as a database or file. It clearly doesn't make sense to try to store the database or the file itself in the JNDI service. Instead, we want to store the information necessary to reconstruct the connection.

In this case the programmer should either bind a Reference instance that corresponds to the object or have the object's class implement the Referenceable interface (in which the object generates and provides a Reference instance when requested by the service provider).

The Reference instance contains enough information to recreate the reference. If a reference to a file was stored, the reference contains enough information to create a File object that points to the correct file.

As attributes

If you're using a service provider that provides directory functionality instead of only naming functionality, you can also store an object as a collection of attributes on a DirContext object (a DirContext instance differs from a Context instance in that it may have attributes).

To use this method, you must create objects that implement the DirContext interface and contain the code necessary to write their internal state as an Attributes object. You must also create an object factory to reconstitute the object.

This approach is useful when the object must be accessible by non-Java applications.

Conclusion

If you've read the series, you should understand and appreciate the power and importance of JNDI -- you don't hear much about it, but it's there under the covers.

Sljedeći ćemo mjesec pogledati aplikaciju temeljenu na JNDI. U međuvremenu biste trebali pokušati pokrenuti i pokrenuti JNDI na LDAP poslužitelju.

Saznajte više o ovoj temi

  • Dodatni paket JDBC 2.0

    //java.sun.com/products/jdbc/articles/package2.html

  • Idite na OpenLDAP Foundation da biste preuzeli OpenLDAP

    //www.openldap.org/

  • Da biste preuzeli SLAPD i SLURPD administrativni vodič , idite na

    //www.umich.edu/~dirsvcs/ldap/doc/guides/

  • JNDI informacije, pružatelji usluga i tako dalje

    //java.sun.com/products/jndi/

Ovu priču, "JNDI pregled, 3. dio: Napredni JNDI" izvorno je objavio JavaWorld.