Browse DevX
Sign up for e-mail newsletters from DevX


Extend the JDK Classes with Jakarta Commons, Part III : Page 4

Explore Jakarta Commons components that enable you to parse arguments in a command-line application, connect to various file systems at the same time, allow an application to uniformly access configurations loaded from various sources, and pool any object.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Commons Pool is a cool framework that lets you pool any object. Ideally, you will find it useful for pooling JDBC connections, threads, business objects, and JNDI connections.

The sample application utilizes a JNDI connection pool. You need a JNDI-compatible directory server to run the application. This example uses Active Directory Application Mode (ADAM), which you can download here. The following paragraphs explain how the sample application uses Commons Pool to pool JNDI connections.

Listing 16 is the interface that exposes methods for performing a JNDI operation.

Listing 16. Interface That Exposes Methods to Perform a JNDI Operation
public interface IJNDIConnection { /** * Execute the given query against the directory server. * * @param query JNDI query of the form ((objectclass=user)(cn=john)) * @return Search result * @throws NamingException Directory server error */ NamingEnumeration executeQuery(String query) throws NamingException; /** * Fetch the attributed of a given DN of an object. * * @param dn Distinguished name of the object * @return Attributes of an object * @throws NamingException Directory server error */ Attributes getAttributes(String dn) throws NamingException; }

The class in.co.narayanan.commons.pool.JNDIConnection implements the interface and uses the javax.naming.directory.DirContext class to perform a requested JNDI operation. Listing 17 presents a code snippet taken from the TestPool test case class to demonstrate how the sample application fetches and uses a pooled connection.

Listing 17. Connection Pool Usage
String host = "localhost"; String port = "389"; String binDN = "CN=guest,CN=Users,DC=narayanan,DC=co,DC=in"; String password = "guest"; String baseDN = "DC=narayanan,DC=co,DC=in"; JNDIConnectionManager manager = JNDIConnectionManager.getJNDIConnectionManager(host, port, binDN, password, baseDN); IJNDIConnection connection = manager.getConnection(); String query = "(objectclass=container)"; NamingEnumeration users = connection.executeQuery(query); while (users.hasMoreElements()) { System.out.println(users.next()); }

The code obtains a reference to IJNDIConnection from the connection pool using the JNDIConnectionManager, and then executes a simple search query. The basic steps for utilizing the Commons Pool are to implement the interface org.apache.commons.pool.PoolableObjectFactory methods and pass the reference to an implementation of the org.apache.commons.pool.ObjectPool interface. In most cases, the org.apache.commons.pool.impl.GenericObjectPool class—the default implementation of ObjectPool—will suffice. Listing 18 is a code snippet from JNDIConnectionFactory that creates JNDI connections when the Commons Pool requests a new object.

Listing 18. JNDIConnectionFactory Implementation
public class JNDIConnectionFactory implements PoolableObjectFactory { private JNDIConnectionInfo connInfo; public JNDIConnectionFactory(String host, String port, String bindDN, String password, String baseDN) { connInfo = new JNDIConnectionInfo(host, port, bindDN, password, baseDN); } public Object makeObject() throws Exception { Hashtable dirProps = connInfo.getJNDIConnectionProps(); DirContext dirContext = new InitialDirContext(dirProps); return dirContext; } public void destroyObject(Object context) throws Exception { DirContext dirContext = (DirContext)context; dirContext.close(); } // remaining methods // inner class JNDIConnectionInfo }

The highlighted lines show how a new DirContext is created and destroyed on a request from the Commons Pool. The ObjectPool-implemented class will call the makeObject and destroyObject appropriately. Listing 19 presents the code snippet from the class JNDIConnectionManager.

Listing 19. Manager Class, Which Fetches a Connection from the Pool
public class JNDIConnectionManager { // remaining declarations private GenericObjectPool pool; private PoolableObjectFactory factory; private JNDIConnectionManager(String host, String port, String bindDN, String password, String baseDN) { factory = new JNDIConnectionFactory(host, port, bindDN, password, baseDN); pool = new GenericObjectPool(factory); } // remaining code public IJNDIConnection getConnection() { try { return new JNDIConnection((DirContext)pool.borrowObject()); } catch (Exception e) { return null; } } public void returnConnection(IJNDIConnection connection) { try { pool.returnObject(((JNDIConnection)connection).getContext()); } catch (Exception e) { System.out.println("Unable return the object back to pool"); } } }

The code passes the JNDIConnectionFactory reference to the GenericObjectPool to let the Commons pool create JNDI connections. The highlighted lines show how the connection is fetched and returned to the pool.

Commons Pool can definitely be useful for all Java applications since resource pooling is a common requirement. You can further customize the GenericObjectPool class to suite your needs. (Find more details in the javadoc of the class.)

So What Have You Learned?
Now that you've completed this final installment of the Jakarta Commons series, you know the following:
  • The rich features provided by various Commons components
  • Where in your Java projects you can use a particular component or method from a utility class
  • The packages and classes contained in various APIs

Now, when you design or develop a Java application, you'll be able to pick a useful class and use it appropriately.

In Case You Missed It
  • Extend the JDK Classes with Jakarta Commons, Part I
  • Extend the JDK Classes with Jakarta Commons, Part II

  • Narayanan A.R. is a passionate advocate of test-driven development, agile methodologies, Java technology, and design patterns. He has several years of experience in software design and development using Java technologies.
    Comment and Contribute






    (Maximum characters: 1200). You have 1200 characters left.



    Thanks for your registration, follow us on our social networks to keep up-to-date