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.
Create a
GenericObjectPoolclass:GenericObjectPool pool = new GenericObjectPool(null);Recall from the discussion on the Pool component that the
GenericObjectPoolrequires aPoolableObjectFactoryto create the instances of ourObjects that need to be pooled. This, in DBCP's case, is provided by thePoolableConnectionFactoryas 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);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:
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
formsetelement, following which the form for which the validations are to be performed is listed with the individual validations. In our case, we want thenameproperty ofmyFormBeanto be validated so that it passes thecontainsStarvalidation (so that it contains the character*).Create a
Validatorand 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);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 individualValidationResultobjects for each property for which validation was requested.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
ValidationResultinstance, we can query whether it passed or failed a particular validation. For example, in the code above theresultinstance for thenameproperty is queried for thecontainsStarvalidation by the coderesult.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.
-
Commons JXPath tutorial!
2007-02-24 13:49:05 BartVanRiel [View]
- Trackback from http://www.JohnMunsch.com/archives/2003_07.html#000907
Last Jakarta Commons Article
2004-11-28 18:21:32 [View]
-
Nice Job.
2003-08-24 15:48:30 anonymous2 [View]
-
It helped me
2003-08-08 11:35:29 anonymous2 [View]
-
NSKeyValueCoding
2003-07-27 11:04:40 shmert [View]