Monday, March 28, 2011

potential uses for dynamic proxies

1.Event publishing - on method x(), transparently call y() or send message z.
2.Transaction management (for db connections or other transactional ops)
3.Thread management - thread out expensive operations transparently.
4.Performance tracking - timing operations checked by a CountdownLatch, for example.
5.Connection management - thinking of APIs like Salesforce's Enterprise API that require clients of their service to start a session before executing any operations.
6.Changing method parameters - in case you want to pass default values for nulls, if that's your sort of thing.
Those are just a few options in addition to validation and logging like you've described above. FWIW, JSR 303, a bean validation specification, has an AOP-style implementation in Hibernate Validator, so you don't need to implement it for your data objects specifically. Spring framework also has validation built in and has really nice integration with AspectJ for some of the stuff described here.
7. Another useful side of a dynamic proxy is when you want to apply the same operation to all methods. With a static proxy you'd need a lot of duplicated code (on each proxied method you would need the same call to a method, and then delegate to the proxied object), and a dynamic proxy would minimize this.

How Java AOP implemented

How Java AOP works

Class-weaving-based, such as AspectJ and JBoss AOP. Core and crosscutting concerns are implemented independently. Class weaving is the process of integrating the concern implementations to form the final system. Weaving can be performed at compile, load, and run time. Both AspectJ and JBoss AOP are very powerful AOP implementations. They provide field interception, caller side interception, and constructor interception.
Proxy-based, such as Spring AOP, Nanning, and dynaop. With proxies, method invocations on an object can be intercepted to inject custom code. The aforementioned AOP frameworks use JDK dynamic proxy, CGLIB proxy, or both. Unlike the class-weaving-based ones, proxy-based AOP frameworks are simpler and often focus on method interception. Most of the time, Java developers use method interception only. Some proxy-based AOP implementations, such as Spring AOP, provide close integration with AspectJ to take advantage of its capabilities.

What if you want to proxy legacy classes that do not have interfaces? You can use CGLIB. CGLIB is a powerful, high-performance code generation library. Under the cover, it uses ASM, a small but fast bytecode manipulation framework, to transform existing byte code to generate new classes. CGLIB is faster than the JDK dynamic proxy approach. Essentially, it dynamically generates a subclass to override the non-final methods of the proxied class and wires up hooks that call back to the user-defined interceptors.

1. Dynamic proxy using InvocationHandler

public Object invoke(Object target, Method method, Object[] arguments) {
System.out.println("before method " + method.getName());
return method.invoke(obj, args);
}
}

2. Java byte-code transformation:

http://asm.ow2.org/doc/tutorial-annotations.html

Refere this article : http://today.java.net/pub/a/today/2005/11/01/implement-proxy-based-aop.html

Java classpath discovery

Library which allows discovering classes at runtime. In Java one can use
ClassLoader.getResourceAsInputStream(resource);
to load the data from the CLASS_PATH provided that you know the name of the resource. This library allows you to discover what Java packages and classes are available at runtime.

ClassPathFactory factory = new ClassPathFactory();
ClassPath classPath = factory.createFromJVM();
for (String packageName : classPath.listPackages("")) {
System.out.println(packageName);
}

Catching Exception in Threads

Java 5 introduced a new way to catch unexpected exceptions: Thread.UncaughtExceptionHandler. This is an interface with the following API:
public interface UncaughtExceptionHandler {
void uncaughtException(Thread t, Throwable e);
}
Your job is to write a class that implements this interface. You then register your implementation on a per-thread basis, or globally for every thread. To register your handler for a single thread you do something like this:
Thread.currentThread().setUncaughtExceptionHandler(new MyExceptionHandler());
To register your handler for every thread, do this:
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());
Notice that setDefaultUncaughtExceptionHandler(...) is a static method in the Thread class, while setUncaughtExceptionHandler(...) is a non-static method.

Simple enough. Let’s add an uncaught exception handler.
MyExceptionHandler
Here is a simple uncaught exception handler that shows the exception message in a dialog box.
public class MyExceptionHandler implements Thread.UncaughtExceptionHandler {

public void uncaughtException(final Thread t, final Throwable e) {
if (SwingUtilities.isEventDispatchThread()) {
showException(t, e);
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
showException(t, e);
}
});
}
}

private void showException(Thread t, Throwable e) {
String msg = String.format("Unexpected problem on thread %s: %s",
t.getName(), e.getMessage());

logException(t, e);

// note: in a real app, you should locate the currently focused frame
// or dialog and use it as the parent. In this example, I'm just passing
// a null owner, which means this dialog may get buried behind
// some other screen.
JOptionPane.showMessageDialog(null, msg);
}

private void logException(Thread t, Throwable e) {
// todo: start a thread that sends an email, or write to a log file, or
// send a JMS message...whatever
}
}
To use this handler, you must register it. Simply modify the code as follows:
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());

...
Now, whenever an “unexpected” exception occurs, MyExceptionHandler kicks in and shows this lovely dialog box: