Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Java Validation with Dynamic Proxies

In this article we will discuss about an important concept of jdk, the dynamic proxy.

Introduction:

A dynamic proxy is a class which implements multiple interfaces specified at runtime when the class is created. Proxy interface is one of these interfaces, which is implemented by the proxy class.

Instance of a proxy class is known as proxy instance. Each proxy instance is associated to an invocation handler object. This invocation handler object implements the InvocationHandler interface.

Potential uses of Dynamic proxy:

Dynamic proxy can be used in several scenarios. Most commonly used are as under:

  • Event Publishing
  • Transaction management
  • Thread management
  • Performance tracking
  • Connection management
  • Validation
  • Logging

Out of these, validation is an essential aspect of any enterprise application and is used everywhere. The business methods contain validation logic to ensure that certain pre conditions are met prior to carrying out the business logic. In situations where the business logic deals with user entered values, it becomes more important to check the values for correctness before exposing them to the complex business logic. These validations are done at the UI level. Let us consider the following code snippet:

Listing 1: A sample proxy Interface

public interface User {
	/**
 	 * Gets the username of the User.
 	 */
	String getUsername ();

	/**
 	 * Sets the username of the User.
 	 * @throws ValidationException indicates that validation of the 
    	 * proposed username variable failed. Contains information about
	 * what went wrong.
 	 */
   	void setUsername ( String username ) throws ValidationException;

	/**
 	 * Gets the password of the User.
 	 */
	String getPassword ();

	/**
 	 * Sets the password of the User.
 	 * @throws ValidationException indicates that validation of the 
	 * proposed password variable failed. Contains information about what 	
	 * went wrong.
 	 */
	void setPassword ( String password ) throws ValidationException;
}

The above sample code is an interface which has getters and setters for simple two fields’ userName and password. Implementation of validation can be of two types:

Tightly coupled validation : In the tight coupled validation implementation, we need to write the validation logic in the method's implementation as under :

Listing 2: Tight coupled validation implementation

public void setPassword(String password) throws ValidationException {
    if ( ( password == null ) || ( password.length() < MIN_PASSWORD_LENGTH )) {
        throw new ValidationException("INVALID_PASSWORD",
                                      "The password must be at least " +
                                      MIN_PASSWORD_LENGTH + 
                                      " characters long" );
    }

    this.password = password;
}

Loosely coupled validation: In loose coupled validation scheme, we call a validation service instead of writing the validation logic within the code.

Listing 3: Loose coupled validation implementation

public void setPassword(String password) throws ValidationException {
    BusinessObjectValidationService.validate( this, "setPassword" , 
                                             new Object[] { password } );

    this.password = password;
}

Though tight coupled validation mechanism is straight forward and easy to use it has certain drawbacks as under:

The code can't be re-used. In this example though the code contains the validation for null check and certain length of a string we cannot reuse the same code for other similar type of validation.

The code isn't configurable. If we want to add another validation rule for the password field, e.g the password should be alphanumeric, we need to change the code and recompile it.

In the loose coupled scheme, the validation service is run as a part of external object which calls it. The coupled scheme can easily overcome the drawbacks of the tight coupled scheme by:

  • writing a code which can be reused;
  • writing a code which can be configured;

Since interfaces are an integral part of the main business objects and services in many frameworks, we all know very well how to swap in and out different implementations of such interfaces. Using dynamic proxy classes is very similar to this approach. But instead of dealing directly writing the implementation of the interface, most developers write a proxy class that implements the interface, performs the desired validation, and delegates method calls through to an implementation class. In the dynamic proxy approach, the entire validation logic is made transparent to the clients of the proxy classes. As a result, implementing a new validation rule is pretty simple and straight forward. Developers don’t need to change a single line of the code that uses the User interface.

Let us create a custom invocation handler class which executes the validation rules. The invocation handlers contain an instance of the actual implementation class as an instance variable. It first validates the method parameters for their correctness and then delegates the method call to the implementation class. When the application requires a business object instance, it actually receives an instance of the dynamic proxy class.

The Invocation handler:

Invocation handler is the class, where all the data validation logic is handled. This class also delegates method calls to a real implementation class once the validation process is passed, in order to process the core business logic. The following code shows an invocation handler which is not tightly coupled to any specific business object, and hence could be used along with any business object that needs to be validated:

Listing 4: Invocation handler implementation

/**
 * This is the object to which methods are delegated if they are not
 * handled directly by this invocation handler.  Typically, this is the
 * real implementation of the business object interface.
 */
private Object delegate = null;

/**
 * Create a new invocation handler for the given delegate.
 * @param delegate the object to which method calls are delegated if
 * they are not handled directly by this invocation handler.
 */
public BusinessObjectInvocationHandler(Object delegate) {
    this.delegate = delegate;
}

/**
 * Processes a method call.
 * @param proxy the proxy instance upon which the method was called.
 * @param method the method that was invoked.
 * @param args the arguments to the method call.
 */
public Object invoke(Object proxy, Method method, Object[] args) 
throws Throwable {

    // call the validator:
    BusinessObjectValidationService.validate(proxy, method.getName(), args);

    // could perform any other method pre-processing routines here...

    /* validation succeeded, so invoke the method on the delegate.  I
       only catch the InvocationTargetException here so that I can
       unwrap it and throw the contained target exception.  If a checked 
       exception is thrown by this method that is not assignable to any of 
       the exception types declared in the throws clause of the interface 
       method, then an UndeclaredThrowableException containing the 
       exception that was thrown by this method will be thrown by the 
       method invocation on the proxy instance.
    */
    Object retVal = null;
    try {
        retVal = method.invoke(delegate, args);
    } catch (InvocationTargetException ite) {
        /* the method invocation threw an exception, so "unwrap" it and
           throw it.
        */
        throw ite.getTargetException();
    }

    // could do method post-processing routines here if necessary...

    return retVal;
}

We can see here that, the implementation of the invocation handler makes use of a generic validator service, which is also used in listing 3. As an alternative solution, we could have created an invocation handler similar to the one mentioned in listing 2 where the validation code is executed directly within the invocation handler.

Drawbacks:

As every good approach comes with some drawbacks or the other, dynamic proxy is no exception here. Validation using dynamic proxy degrades the performance of the application.

Conclusion:

To conclude the discussion we can summarize the following points.

  • Dynamic proxy is a class which implements multiple interfaces specified at runtime when the class is created. This was introduced in jdk1.3.
  • Dynamic proxy is used in several scenarios: e.g.
    • Event Publishing
    • Transaction management
    • Thread management
    • Performance tracking
    • Connection management
    • Validation
    • Logging
  • Validation can be implemented using tightly coupled mechanism or loosely coupled mechanism.


Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login