Getting started with Java LanguageInheritanceStreamsExceptions and exception handlingCollectionsLambda ExpressionsGenericsFile I/OArraysInterfacesMapsStringsInputStreams and OutputStreamsDefault MethodsClasses and ObjectsBasic Control StructuresConcurrent Programming (Threads)Console I/OSingletonsVisibility (controlling access to members of a class)Regular ExpressionsAutoboxingDocumenting Java CodeExecutor, ExecutorService and Thread poolsObject Class Methods and ConstructorJAXBPrimitive Data TypesNetworkingOptionalEnumsHttpURLConnectionAnnotationsAudioDate ClassCalendar and its SubclassesNashorn JavaScript engineJava Native InterfaceRemote Method Invocation (RMI)Iterator and IterableOperatorsAssertingScannerProperties ClassPreferencesReflection APIConstructorsByteBufferSerializationJSON in JavaRandom Number GenerationRecursionPolymorphismStringBuilderReference Data TypesBit ManipulationJava AgentsEncapsulationType ConversionBigIntegerBigDecimalRSA EncryptionVarargs (Variable Argument)ThreadLocalLogging (java.util.logging)Using the static keywordDisassembling and DecompilingResources (on classpath)log4j / log4j2JVM FlagsOracle Official Code StandardCharacter encodingJava Memory ManagementImmutable ObjectsObject CloningAlternative CollectionsListsBufferedWriterLocalTimeSetsComparable and ComparatorJVM Tool InterfaceNested and Inner ClassesApache Commons LangGetters and SettersThe ClasspathBytecode ModificationXML Parsing using the JAXP APIsReference TypesLocalization and InternationalizationJAX-WSXML XPath EvaluationJava Performance TuningParallel programming with Fork/Join frameworkCommon Java PitfallsNon-Access ModifiersJava Compiler - 'javac'XJCProcessInstalling Java (Standard Edition)Command line Argument ProcessingDates and Time (java.time.*)Fluent InterfaceXOM - XML Object ModelJust in Time (JIT) compilerFTP (File Transfer Protocol)Java Native AccessModulesJava Pitfalls - Exception usageJava Pitfalls - Language syntaxServiceLoaderClassloadersObject ReferencesJava Pitfalls - Performance IssuesCreating Images ProgrammaticallyAppletsNIO - NetworkingNew File I/OSecure objectsJava Pitfalls - Threads and ConcurrencySplitting a string into fixed length partsJava Pitfalls - Nulls and NullPointerExceptionSecurityManagerJNDIsuper keywordThe java.util.Objects ClassThe Java Command - 'java' and 'javaw'Atomic TypesJava Floating Point OperationsConverting to and from Stringssun.misc.UnsafeJava Memory ModelJava deploymentJava plugin system implementationsQueues and DequesRuntime CommandsNumberFormatSecurity & CryptographyJava Virtual Machine (JVM)Unit TestingJavaBeanExpressionsLiteralsJava SE 8 FeaturesJava SE 7 FeaturesPackagesCurrency and MoneyConcurrent CollectionsUsing ThreadPoolExecutor in MultiThreaded applications.Java Editions, Versions, Releases and DistributionsDynamic Method DispatchJMXSecurity & CryptographyGenerating Java CodeJShellBenchmarksCollection Factory MethodsMulti-Release JAR FilesStack-Walking APITreeMap and TreeSetSocketsJava SocketsUsing Other Scripting Languages in JavaFunctional InterfacesList vs SET2D Graphics in JavaClass - Java ReflectionDequeue InterfaceEnum MapEnumSet classLocal Inner ClassJava Print ServiceImmutable ClassString TokenizerFileUpload to AWSAppDynamics and TIBCO BusinessWorks Instrumentation for Easy IntegrationReaders and WritersHashtableEnum starting with numberSortedMapWeakHashMapLinkedHashMapStringBufferChoosing CollectionsC++ ComparisonCompletableFuture

JNDI

Other topics

RMI through JNDI

This example shows how JNDI works in RMI. It has two roles:

  • to provide the server with a bind/unbind/rebind API to the RMI Registry
  • to provide the client with a lookup/list API to the RMI Registry.

The RMI Registry is part of RMI, not JNDI.

To make this simple, we will use java.rmi.registry.CreateRegistry() to create the RMI Registry.

  1. Server.java(the JNDI server)

    package com.neohope.jndi.test;
    
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import java.io.IOException;
    import java.rmi.RemoteException;
    import java.rmi.registry.LocateRegistry;
    import java.util.Hashtable;
    
    /**
     * JNDI Server
     * 1.create a registry on port 1234
     * 2.bind JNDI
     * 3.wait for connection
     * 4.clean up and end
     */
    public class Server {
        private static Registry registry;
        private static InitialContext ctx;
    
        public static void initJNDI() {
            try {
                registry = LocateRegistry.createRegistry(1234);
                final Hashtable jndiProperties = new Hashtable();
                jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
                jndiProperties.put(Context.PROVIDER_URL, "rmi://localhost:1234");
                ctx = new InitialContext(jndiProperties);
            } catch (NamingException e) {
                e.printStackTrace();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    
        public static void bindJNDI(String name, Object obj) throws NamingException {
            ctx.bind(name, obj);
        }
    
        public static void unbindJNDI(String name) throws NamingException {
            ctx.unbind(name);
        }
    
        public static void unInitJNDI() throws NamingException {
            ctx.close();
        }
    
        public static void main(String[] args) throws NamingException, IOException {
            initJNDI();
            NMessage msg = new NMessage("Just A Message");
            bindJNDI("/neohope/jndi/test01", msg);
            System.in.read();
            unbindJNDI("/neohope/jndi/test01");
            unInitJNDI();
        }
    }
    
  2. Client.java(the JNDI client)

    package com.neohope.jndi.test;
    
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import java.util.Hashtable;
    
    /**
     * 1.init context
     * 2.lookup registry for the service
     * 3.use the service
     * 4.end
     */
    public class Client {
        public static void main(String[] args) throws NamingException {
            final Hashtable jndiProperties = new Hashtable();
            jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
            jndiProperties.put(Context.PROVIDER_URL, "rmi://localhost:1234");
    
            InitialContext ctx = new InitialContext(jndiProperties);
            NMessage msg = (NeoMessage) ctx.lookup("/neohope/jndi/test01");
            System.out.println(msg.message);
            ctx.close();
        }
    }
    
  3. NMessage.java (RMI server class)

    package com.neohope.jndi.test;
    
    import java.io.Serializable;
    import java.rmi.Remote;
    
    /**
     * NMessage
     * RMI server class
     * must implements Remote and Serializable 
     */
    public class NMessage implements Remote, Serializable {
        public String message = "";
    
        public NMessage(String message)
        {
            this.message = message;
        }
    }
    

How to run the eaxmple:

  1. build and start the server
  2. build and start the client

Introduce

JNDI Model

The Java Naming and Directory Interface (JNDI) is a Java API for a directory service that allows Java software clients to discover and look up data and objects via a name. It is designed to be independent of any specific naming or directory service implementation.

The JNDI architecture consists of an API (Application Programming Interface) and an SPI (Service Provider Interface). Java applications use this API to access a variety of naming and directory services. The SPI enables a variety of naming and directory services to be plugged in transparently, allowing the Java application using the API of the JNDI technology to access their services.

As you can see form the picture above, JNDI supports LDAP, DNS, NIS, NDS, RMI and CORBA. Of course, you can extend it.

How it works

In this example, the Java RMI use the JNDI API to look up objects in a network. If you want to look up a object, you need at least two pieces of information:

  • Where to find the object

The RMI Registry manages the name bindings, it tells you where to find the object.

  • The name of the object

What is a object's name? It is usually a string, it can also be a object that implements the Name interface.

Step by step

  1. First you need a registry, which manage the name binding. In this example, we use java.rmi.registry.LocateRegistry.

    //This will start a registry on localhost, port 1234
    registry = LocateRegistry.createRegistry(1234);
    
  2. Both client and server need a Context. Server use the Context to bind the name and object. Client use the Context to lookup the name and get the object.

    //We use com.sun.jndi.rmi.registry.RegistryContextFactory as the InitialContextFactory
    final Hashtable jndiProperties = new Hashtable();
    jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
    //the registry usrl is "rmi://localhost:1234"
    jndiProperties.put(Context.PROVIDER_URL, "rmi://localhost:1234");
    InitialContext ctx = new InitialContext(jndiProperties);
    
  3. The server bind the name and object

    //The jndi name is "/neohope/jndi/test01"
    bindJNDI("/neohope/jndi/test01", msg);
    
  4. The client look up the object by the name "/neohope/jndi/test01"

    //look up the object by name "java:com/neohope/jndi/test01"
    NeoMessage msg = (NeoMessage) ctx.lookup("/neohope/jndi/test01");
    
  5. Now the client can use the object

  6. When the server is ending, need to clean up.

    ctx.unbind("/neohope/jndi/test01");
    ctx.close();
    

Contributors

Topic Id: 5720

Example Ids: 20252

This site is not affiliated with any of the contributors.