ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Using the Jakarta Commons, Part 3
Pages: 1, 2, 3, 4

DBCP

Summary: Database Connection Pooling, based on the Pool component.



Where: Main Page, Binaries, Source.

When: Whenever access is required to a relational database.

Example Application: DBCPDemo.java requires commons-dbcp.jar, commons-pool.jar, and commons-collections.jar in the CLASSPATH. You will also require access to a database and the JDBC drivers for accessing that database. The example application tests connection to a MySQL server using the MySQL JDBC driver. Note that you will require the nightly version of the binaries, as the official release does not contain some of the required classes. Finally, when this example is run, make sure that you set the system property for the JDBC driver you are using (-Djdbc.drivers=com.mysql.jdbc.Driver).

Description:

DBCP provides a database-connection pooling mechanism based on the Pool component. Its usage is slightly more involved than regular connection pooling mechanisms, as the idea was to provide a generic architecture available as a pseudo-JDBC driver. However, since we have already covered the basics of the Pool component, understanding the usage for DBCP should be easier.

  1. Create a GenericObjectPool class:

    GenericObjectPool pool = new GenericObjectPool(null);
  2. Recall from the discussion on the Pool component that the GenericObjectPool requires a PoolableObjectFactory to create the instances of our Objects that need to be pooled. This, in DBCP's case, is provided by the PoolableConnectionFactory as shown below:

    Create the PoolableConnectionFactory:

    DriverManagerConnectionFactory cf =
        new DriverManagerConnectionFactory(
        "jdbc:mysql://host/db", "username", "password"); 
    
    PoolableConnectionFactory pcf =
        new PoolableConnectionFactory(
        CF, pool, null, "SELECT * FROM mysql.db", false, true);
  3. Now, all we need to do is to create and register the PoolingDriver.

    new PoolingDriver().registerPool("myPool", pool);

We are now ready to get connections out of this Connection Pool. Note that it has been created with default values for maxActive, maxIdle, et cetera. You can set these properties to what you require while creating the GenericObjectPool class in step 1 above. DBCPDemo.java gives the complete example.

Validator

Summary: API that combines commonly used validations of user input.

Where: Main Page, Binaries, Source.

When: Whenever you need to validate JavaBeans on a regular basis.

Example Application: ValidatorDemo.java, MyValidator.java, MyFormBean.java, validation.xml require commons-validator.jar, commons-beanutils.jar, commons-collections.jar, commons-digester.jar, and commons-logging.jar in the CLASSPATH.

Description:

If you have developed a web application using Struts before, you've come across the Validator package. It makes the job of performing validations on user input quite easy, and provides a single interface for locale-specific error messages. However, Validator is not just of use in web applications — it can be quite easily used at other places where JavaBeans are used.

Validator allows you to define validations for your user input fields, provide internationalization support in form of locale-specific error messages, and create custom Validators. There are several prebuilt validators that you can use, and you can create your own if the custom validators do not serve your purpose.

Validation rules and validation methods are defined using XML files. (The definitions can be in one or many files. It is a good idea to separate them, though.) The validation methods file defines the validators to be used and names the class that actually implements the validator. This class does not need to implement any specific interfaces or extend another class. It should simply conform to the definition, as specified in the method file.

Let us construct a validator of our own that simply checks if a String property of a bean contains a specific character (*).

import org.apache.commons.validator.*;

public class MyValidator {
    public static boolean validateContainsChar(Object bean, Field field) {

    	// first get the value of this bean property as a string
    	String val = ValidatorUtil.getValueAsString(bean, field.getProperty());

    	// now return true or false based on the presence of the '*' sign
    	return ((val.indexOf('*') == -1) ? false : true);
    }
}

The ValidatorUtil class provides useful methods to get the values of bean properties as easily manipulable String values. This validator now needs to be defined in an XML file:

<!-- This defines the validator methods that we are implementing -->
<global>
    <validator name="containsStar"
    	classname="MyValidator"
    	method="validateContainsChar"
  		methodParams="java.lang.Object, org.apache.commons.validator.Field" />
</global>

Notice that we define the exact method structure, including the parameters that it expects. To use this validator in a method of your own, follow these steps:

  1. Add the validator rules that we want to implement in the XML file above:

    <!-- This defines the validator rules -->
    <formset>
        <!-- This checks if the form bean's name property implements 
        the containsPercent method -->
        <form name="myFormBean">
        	<field property="name" depends="containsStar">
        		<arg0 key="myFormBean.name" />
        	</field> 
        </form>
    </formset>

    As you can see, all validation rules are enclosed in the formset element, following which the form for which the validations are to be performed is listed with the individual validations. In our case, we want the name property of myFormBean to be validated so that it passes the containsStar validation (so that it contains the character *).

  2. Create a Validator and initialize it, based on the XML file:

    // load the validator xml files
    InputStream in = getClass().getResourceAsStream("validator.xml");
    
    // create a ValidatorResources
    ValidatorResources resources = new ValidatorResources();
    
    // and load resources in
    ValidatorResourcesInitializer.initialize(resources, in);
    
    // now create the Validator
    Validator validator = new Validator(resources, "myFormBean");
    validator.addResource(Validator.BEAN_KEY, bean);
  3. Validate the bean:

    // finally validate
    ValidatorResults results = validator.validate();

    The results of the validation are passed as an instance of ValidatorResults. It contains a hashmap of individual ValidationResult objects for each property for which validation was requested.

  4. Process the ValidationResults:

    // the result object may contain the results of validation on other form
    
    // properties as well. For each property we can get the result individually
    ValidatorResult result = results.getValidatorResult("name");
    
    // and for each property, we can check for individual validations
    // for example, did the name property pass the containsStar validation?
    
    System.err.println(
        "Contains Star validation passed for \'name\' property?" +
        result.isValid("containsStar"));

    On each ValidationResult instance, we can query whether it passed or failed a particular validation. For example, in the code above the result instance for the name property is queried for the containsStar validation by the code result.isValid('containsStart').

Validator is quite useful in web applications, as it reduces the repetitive task of validations to be performed on user input by providing a set of prebuilt Validators. These include, but are not limited to, range checking, limitations on types and sizes of input values, and email and locale testing. Further, you can extend and create your own Validators to add to this list.

Conclusion

This concludes the third and final installment of coverage of Jakarta Commons. Although these articles covered only the basics of each component, I hope that they have given enough information for you to start exploring them further. Good Luck!

Vikram Goyal is the author of Pro Java ME MMAPI.


Return to ONJava.com.