001    package com.khubla.pragmatach.plugin.mongodb.proxy;
002    
003    import java.beans.Introspector;
004    import java.lang.reflect.Field;
005    import java.lang.reflect.InvocationTargetException;
006    import java.lang.reflect.Method;
007    
008    import javassist.util.proxy.MethodFilter;
009    import javassist.util.proxy.MethodHandler;
010    
011    import com.khubla.pragmatach.plugin.mongodb.util.ClassTypeUtils;
012    
013    /**
014     * @author tom
015     */
016    public class MongoMethodHandler implements MethodHandler, MethodFilter {
017       /**
018        * get the field for a getter
019        */
020       private Field getField(Method thisMethod) throws NoSuchFieldException {
021          final String fieldName = Introspector.decapitalize(thisMethod.getName().substring(3));
022          return thisMethod.getDeclaringClass().getDeclaredField(fieldName);
023       }
024    
025       @Override
026       public Object invoke(Object object, Method thisMethod, Method proceed, Object[] args) throws Throwable {
027          /*
028           * do the lazy load, if required
029           */
030          lazyLoad(object, thisMethod, proceed, args);
031          /*
032           * proceed
033           */
034          return proceed.invoke(object, args);
035       }
036    
037       @Override
038       public boolean isHandled(Method method) {
039          try {
040             if (method.getName().startsWith("get")) {
041                final Field field = getField(method);
042                if (ClassTypeUtils.isLazyLoad(field)) {
043                   return true;
044                }
045             }
046             return false;
047          } catch (final Exception e) {
048             System.out.println(e.getMessage());
049             return false;
050          }
051       }
052    
053       /**
054        * lazy load
055        */
056       private void lazyLoad(Object object, Method thisMethod, Method proceed, Object[] args) throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
057          boolean fetched = MongoProxyFactory.getFetched(object);
058          if (false == fetched) {
059             String lazyLoadid = MongoProxyFactory.getId(object);
060             System.out.println(lazyLoadid);
061          }
062       }
063    }