6.2.1. Basic JNDI Programming for MRG Messaging
The following code establishes the initial JNDI context, which represents the JNDI configuration:
Hashtable<String, String> jndiEnvironment = new Hashtable<String, String>();
// set the factory class
jndiEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jndi.PropertiesFileInitialContextFactory");
// set the connection factory name
jndiEnvironment.put("connectionfactory.ConnectionFactory",
"amqp://username:password@clientid/test?brokerlist='tcp://localhost:5672'");
// Set the provider URL that points to a property file
jndiEnvironment.put(Context.PROVIDER_URL, "myPRoviderURLPath");
// create the initial context
InitialContext initialContext = new InitialContext(jndiEnvironment);
Once the JNDI configuration has been created, we can get the connection factory as follows:
ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory");
The connection factory is used to create a connection, and the connection is used to create a session, as follows:
Connection connection = connectionFactory.createConnection("guest", "guest");
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Programs that use JNDI close both the connection and the JNDI context, as follows:
connection.close(); getInitialContext().close();