package com.github.zhongl.hs4j.kit.proxy;

<<<<<<< HEAD
=======
import java.io.*;
>>>>>>> 74777f9... To contribute hs4j-kit, which can help developers easy to use hs4j.
import java.lang.reflect.*;
import java.util.*;

import com.github.zhongl.hs4j.kit.annotations.*;

/**
 * {@link ProxyFactory}
 * 
 * @author <a href=mailto:zhong.lunfu@gmail.com>zhongl</a>
 * @created 2011-6-2
 * 
 */
public abstract class ProxyFactory {

  @SuppressWarnings("unchecked")
<<<<<<< HEAD
  public <T> T newProxyOf(Class<T> clazz) {
=======
  public <T> T newProxyOf(Class<T> clazz) throws IOException {
>>>>>>> 74777f9... To contribute hs4j-kit, which can help developers easy to use hs4j.
    scanAndMapMethodToInvacationHandlerWith(clazz);
    Class<?>[] interfaces = { clazz };
    return (T) Proxy.newProxyInstance(clazz.getClassLoader(), interfaces, dispatcher);
  }

  protected abstract InvocationHandler createInvocationHandlerWith(Method method, String database, String table);

  private void scanAndMapMethodToInvacationHandlerWith(Class<?> clazz) {
    final Repository repository = clazz.getAnnotation(Repository.class);
    if (repository == null)
      throw new IllegalArgumentException(Repository.class + " should be annotated to class: " + clazz);
    final String database = repository.database();
    final String table = repository.table();
    Method[] methods = clazz.getMethods();
    for (Method method : methods) {
      InvocationHandler handler = createInvocationHandlerWith(method, database, table);
      if ((handler == null)) continue; // no need to map, so skip.
      invocationMap.put(method, handler);
    }
  }

  protected final Map<Method, InvocationHandler> invocationMap = new HashMap<Method, InvocationHandler>();
  private final Dispatcher dispatcher = new Dispatcher();

  private final class Dispatcher implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      InvocationHandler invocationHandler = invocationMap.get(method);
      if (invocationHandler == null) throw new UnsupportedOperationException("No implement method: " + method);
      return invocationHandler.invoke(proxy, method, args);
    }
  }

}

@@ -36,16 +36,29 @@
 proxy;%0A%0A
+%3C%3C%3C%3C%3C%3C%3C HEAD%0A
 %3C%3C%3C%3C%3C%3C%3C 
@@ -175,16 +175,70 @@
 e hs4j.%0A
+=======%0A%3E%3E%3E%3E%3E%3E%3E 5538931... Remove useless Exception .%0A
 import j
@@ -532,16 +532,29 @@
 %3C%3C HEAD%0A
+%3C%3C%3C%3C%3C%3C%3C HEAD%0A
   public
@@ -660,16 +660,16 @@
 ption %7B%0A
-
 %3E%3E%3E%3E%3E%3E%3E 
@@ -747,16 +747,114 @@
 e hs4j.%0A
+=======%0A  public %3CT%3E T newProxyOf(Class%3CT%3E clazz) %7B%0A%3E%3E%3E%3E%3E%3E%3E 5538931... Remove useless Exception .%0A
     scan

Add pull requests from zhongl