private static Object crateProxy(
     Class<?> type,
     Callback callback,
     List<Class<?>> constructorArgTypes,
     List<Object> constructorArgs) {
   Enhancer enhancer = new Enhancer();
   enhancer.setCallback(callback);
   enhancer.setSuperclass(type);
   try {
     type.getDeclaredMethod(WRITE_REPLACE_METHOD);
     // ObjectOutputStream will call writeReplace of objects returned by writeReplace
     log.debug(
         WRITE_REPLACE_METHOD
             + " method was found on bean "
             + type
             + ", make sure it returns this");
   } catch (NoSuchMethodException e) {
     enhancer.setInterfaces(new Class[] {WriteReplaceInterface.class});
   } catch (SecurityException e) {
     // nothing to do here
   }
   Object enhanced = null;
   if (constructorArgTypes.isEmpty()) {
     enhanced = enhancer.create();
   } else {
     Class<?>[] typesArray = constructorArgTypes.toArray(new Class[constructorArgTypes.size()]);
     Object[] valuesArray = constructorArgs.toArray(new Object[constructorArgs.size()]);
     enhanced = enhancer.create(typesArray, valuesArray);
   }
   return enhanced;
 }
Exemple #2
0
    @SuppressWarnings("unchecked")
    protected boolean setValueFromResultSet(Object obj, ResultSet rs) throws SQLException {
      Object value = rs.getObject(this.getColumnName());
      if (value != null) {
        try {
          T bean = dao.newEntityInstance();
          FieldUtils.writeField(bean, dao.getPKColumn().getFieldName(), value, true);

          if (preFetch) {
            Class<T> beanClass = dao.getEnitityClass();
            bean = DBContext.getDAO(beanClass).queryByPK(DBContext.getContext(), bean);
          } else {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(beanClass);
            enhancer.setCallback(new DBObjectProxy<T>(pkColumn, obj, bean, getFieldName()));
            bean = (T) enhancer.create();
            FieldUtils.writeField(bean, dao.getPKColumn().getFieldName(), value, true);
          }

          FieldUtils.writeField(obj, getFieldName(), bean, true);

          return true;
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      } else {
        return false;
      }
    }
  /**
   * Creates proxy basing on the given configurable target class.
   *
   * @param targetClass the given configurable target class.
   * @param argsType the args type
   * @param args the args
   * @return returns the <code>proxy instance</code>.
   */
  @SuppressWarnings("unchecked")
  public static <T extends Configurable> T createProxy(
      Class<T> targetClass, Class<?>[] argsType, Object[] args) {

    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(targetClass);
    enhancer.setInterfaces(new Class[] {ConfigModule.class});
    // Kiểm tra interface cài đặt
    Set<Class<?>> interfaceList = ReflectUtils.getAllInterfaces(targetClass, true);
    if (AbstractConfig.class.isAssignableFrom(targetClass)) {
      interfaceList.remove(SystemConfig.class);
    }
    HashMap<String, Object> optionsList = new HashMap<String, Object>();
    HashMap<Class<?>, Object> configObjList = new HashMap<Class<?>, Object>();
    for (Class<?> interfaze : interfaceList) {
      if (JGentle.containsConfigClass(interfaze)) {
        Class<?> clazz = JGentle.getConfigClass(interfaze);
        Object obj = null;
        obj = ReflectUtils.createInstance(clazz);
        // Nếu config class extends từ AbstractConfigModule
        if (AbstractConfigModule.class.isAssignableFrom(clazz)) {
          try {
            ((AbstractConfigModule) obj)
                .setOptionsList(
                    optionsList, ReflectUtils.getSupportedMethod(targetClass, "configure", null));
          } catch (NoSuchMethodException e) {
            if (log.isFatalEnabled()) {
              log.fatal(
                  "Could not found 'configure' method on configurable class [" + targetClass + "]",
                  e);
            }
          }
        }
        configObjList.put(interfaze, obj);
      }
    }
    enhancer.setCallback(new ConfigurationProxy(targetClass, optionsList, configObjList));
    Object result = null;
    if (argsType != null && args != null) {
      result = enhancer.create(argsType, args);
    } else {
      result = enhancer.create();
    }
    // thiết lập optionsList trong trường hợp targetClass kế thừa từ
    // AbstractConfig
    if (AbstractConfig.class.isAssignableFrom(targetClass)) {
      try {
        ((AbstractConfig) result)
            .setOptionsList(
                optionsList, ReflectUtils.getSupportedMethod(targetClass, "configure", null));
      } catch (NoSuchMethodException e) {
        if (log.isFatalEnabled()) {
          log.fatal(
              "Could not found 'configure' method on configurable class [" + targetClass + "]", e);
        }
      }
    }
    return (T) result;
  }
  public Object createProxy(PersistanceManager persistanceManager) {
    this.persistanceManager = persistanceManager;
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(PersistanceManager.class);
    enhancer.setCallback(this);

    return enhancer.create();
  }
 private static ObjectWithInterceptor newEnancedInstance(EntityManagerSimpleJPA em, Class tClass) {
   LazyInterceptor interceptor = new LazyInterceptor(em);
   Enhancer e = new Enhancer();
   e.setSuperclass(tClass);
   e.setCallback(interceptor);
   Object bean = e.create();
   ObjectWithInterceptor cwi = new ObjectWithInterceptor(bean, interceptor);
   return cwi;
 }
 public static Chinese getAuthInstance() {
   Enhancer en = new Enhancer();
   // 设置要代理的目标类
   en.setSuperclass(Chinese.class);
   // 设置要代理的拦截器
   en.setCallback(new AroundAdvice());
   // 生成代理类的实例
   return (Chinese) en.create();
 }
Exemple #7
0
 /**
  * 创建代理对象
  *
  * @param target
  * @return
  */
 public Object getInstance(Object target) {
   this.target = target;
   Enhancer enhancer = new Enhancer();
   enhancer.setSuperclass(this.target.getClass());
   // 回调方法
   enhancer.setCallback(this);
   // 创建代理对象
   return enhancer.create();
 }
Exemple #8
0
  public static DynProxy newHeavyMethod() {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(DynProxy.class);
    enhancer.setCallback(new CglibHeavyMethodInterceptor());

    DynProxy cglibProxy = (DynProxy) enhancer.create();

    return cglibProxy;
  }
 @Override
 public Object bind(Object targetImpl) {
   this.target = targetImpl;
   Enhancer enhancer = new Enhancer();
   enhancer.setSuperclass(this.target.getClass());
   // 回调方法
   enhancer.setCallback(this);
   // 创建代理对象
   return enhancer.create();
 }
Exemple #10
0
 public static Object newInstance(Class clazz) {
   try {
     Enhancer e = new Enhancer();
     e.setSuperclass(clazz);
     e.setCallback(callback);
     return e.create();
   } catch (Throwable e) {
     e.printStackTrace();
     throw new Error(e.getMessage());
   }
 }
 public Object createProxy() {
   Enhancer enhancer = new Enhancer();
   enhancer.setSuperclass(proxiedClass);
   if (null != additionalInterface) {
     enhancer.setInterfaces(new Class[] {additionalInterface});
   }
   Method[] targetInterceptMethods = getActualTargetMethods(delegate, methodsToIntercept);
   Method[] targetDuplicateMethods = getActualTargetMethods(delegate, methodsToDuplicate);
   enhancer.setCallback(
       new DelegatingInterceptor(delegate, targetInterceptMethods, targetDuplicateMethods));
   return enhancer.create();
 }
 private Enhancer lookupOrCreateEnhancerFor(final Class<?> cls) {
   Enhancer enhancer = enhancerByClass.get(cls);
   if (enhancer == null) {
     enhancer = new Enhancer();
     enhancer.setSuperclass(cls);
     enhancer.setInterfaces(
         ArrayUtil.combine(cls.getInterfaces(), new Class<?>[] {CglibEnhanced.class}));
     enhancer.setCallback(callback);
     enhancerByClass.put(cls, enhancer);
   }
   return enhancer;
 }
Exemple #13
0
  /**
   * Memoize methods of an existing object. Allows integrating with other frameworks like
   * <i>Spring</i>.
   *
   * @param <T> The type of the object
   * @param objectTobeDecorated The object should have at least one Remember annotation
   * @param cacheFactory Factory for creating cache objects. If it is null, a default (simple)
   *     factory will be used. Programmers can use other cache libraries by implementing the
   *     ICacheFactory and ICache interfaces.
   * @return an object of type T which decorates <code>objectTobeDecorated</code>. Method
   *     invocations will be routed to the objectTobeDecorated after checking for memoization.
   * @since 1.1
   */
  @SuppressWarnings("unchecked")
  public static <T> T decorate(T objectTobeDecorated, ICacheFactory cacheFactory) {
    if (objectTobeDecorated == null) {
      throw new NullPointerException("Memoizer cannot decorate a null object");
    }
    cacheFactory = getCacheFactory(cacheFactory);

    MethodInterceptor interceptor = new DecoratorInterceptor(cacheFactory, objectTobeDecorated);
    Enhancer enhancer = new Enhancer(); // cglib class
    enhancer.setSuperclass(objectTobeDecorated.getClass());
    enhancer.setCallback(interceptor);
    return (T) enhancer.create();
  }
Exemple #14
0
  @Override
  public <T extends PropertyContainer> Object createProxy(
      T container, TypeWrapper<T> wrapper, Class<?> instanceClass) {

    CglibEntityInterceptor<T> interceptor = new CglibEntityInterceptor<T>(container, wrapper);

    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(instanceClass);
    enhancer.setInterfaces(new Class[] {ContainerWrapper.class});
    enhancer.setCallback(interceptor);
    enhancer.setClassLoader(config.getResourceLoader().getClassLoader());

    Object proxy = enhancer.create();

    wrapper.onLoad(proxy, container);

    return proxy;
  }
Exemple #15
0
    @SuppressWarnings("unchecked")
    protected void setListValue(Object obj) {
      List<T> list = null;

      DBCondition condition = fkColumn.equalsTo(obj);
      if (preFetch) {
        list = dao.query(DBContext.getContext(), condition);
      } else {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(ArrayList.class);
        enhancer.setCallback(new DBListProxy<T>(obj, beanClass, getFieldName(), condition));
        list = (List<T>) enhancer.create();
      }
      try {
        FieldUtils.writeField(obj, getFieldName(), list, true);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
Exemple #16
0
  private void installSystemPropertiesProxy() {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(Properties.class);
    enhancer.setCallback(
        new Dispatcher() {
          @Override
          public Object loadObject() throws Exception {
            return instance.getContext().getProperties();
          }
        });
    Properties contextAwareProperties = (Properties) enhancer.create();

    try {
      Field props = System.class.getDeclaredField("props");
      props.setAccessible(true);
      props.set(System.class, contextAwareProperties);
    } catch (NoSuchFieldException | IllegalAccessException e) {
      throw new AssertionError("Unable to override System.props", e);
    }
  }
Exemple #17
0
  /** -XX:PermSize=10M -XX:MaxPermSize=10M */
  @Test
  public void methodAreaOOMTest() {

    while (true) {
      Enhancer enhancer = new Enhancer();
      enhancer.setSuperclass(OOMObject.class);
      enhancer.setUseCache(false);
      enhancer.setCallback(
          new MethodInterceptor() {
            @Override
            public Object intercept(
                Object o, Method method, Object[] objects, MethodProxy methodProxy)
                throws Throwable {
              return methodProxy.invokeSuper(
                  o,
                  objects); // To change body of implemented methods use File | Settings | File
                            // Templates.
            }
          });
      enhancer.create();
    }
  }
Exemple #18
0
  @SuppressWarnings({"unchecked"})
  protected <X> X performAugmentation(CompoundHandler handler, X from) {
    if (handler.isNeedingApplication()) {
      Class<?> superClass = from.getClass();
      while (Enhancer.isEnhanced(superClass)) {
        superClass = superClass.getSuperclass();
      }

      Enhancer enhancer = new Enhancer();
      enhancer.setCallback(handler);
      enhancer.setSuperclass(superClass);

      Set<Class<?>> interfaces = Sets.newHashSet();
      interfaces.addAll(ImmutableList.copyOf(from.getClass().getInterfaces()));
      interfaces.addAll(handler.getInterfaces());
      enhancer.setInterfaces(interfaces.toArray(new Class<?>[interfaces.size()]));

      return (X) enhancer.create();
    }

    return from;
  }
  /**
   * The factory method to create connector/message processors beans
   *
   * @param realMpClass
   *     <p>The class of the message processor/ connector
   * @param objects
   *     <p>Constructor arguments
   * @return
   *     <p>An @see #Enhancer of the message processor/connector
   */
  public Object create(Class realMpClass, Object... objects) {
    try {

      Enhancer e = new Enhancer();
      e.setSuperclass(realMpClass);

      MethodInterceptor callback = createInterceptor();

      e.setCallback(callback);
      if (objects.length != 0) {

        Constructor[] constructors = realMpClass.getConstructors();
        for (Constructor constructor : constructors) {
          Class[] parameterTypes = constructor.getParameterTypes();
          boolean matchConstructor = parameterTypes.length == objects.length;
          for (int j = 0; j < parameterTypes.length; j++) {
            if (j < objects.length) {
              matchConstructor =
                  matchConstructor && parameterTypes[j].isAssignableFrom(objects[j].getClass());
            } else {
              matchConstructor = false;
            }
          }

          if (matchConstructor) {
            return e.create(constructor.getParameterTypes(), objects);
          }
        }
        throw new Error("Could not mock the connectors");
      }
      return e.create();

    } catch (Throwable e) {
      throw new Error("Could not mock the connectors", e);
    }
  }
 @SuppressWarnings("unchecked")
 protected <T> T proxyInstance() {
   enhancer.setSuperclass(target.getClass());
   enhancer.setCallback(this);
   return (T) enhancer.create();
 }
 /**
  * 生成代理类工厂
  *
  * @author com.tiantian
  * @param realObj
  * @return 返回生成的代理类
  */
 public Object getProxyInstance(Object realObj) {
   Enhancer enhancer = new Enhancer();
   enhancer.setSuperclass(realObj.getClass());
   enhancer.setCallback(this);
   return enhancer.create();
 }
 /**
  * 创建clazz的子类
  *
  * @param clazz
  * @return
  * @return Object
  */
 public Object getProxy(Class<?> clazz) {
   // 设置创建子类的类
   enhancer.setSuperclass(clazz);
   enhancer.setCallback(this);
   return enhancer.create();
 }
  @Override
  public ExporterTask getExporter(String type, HibernateToolTask parent, String serviceName) {
    Enhancer enhancer = new Enhancer();
    enhancer.setCallbackType(ExporterTaskInterceptor.class);
    enhancer.setCallback(new ExporterTaskInterceptor());

    ExporterTask proxy = null;
    if (type.equals("config")) {
      enhancer.setSuperclass(HibernateConfigExporterTask.class);
      enhancer.setClassLoader(HibernateConfigExporterTask.class.getClassLoader());
      proxy =
          (HibernateConfigExporterTask)
              enhancer.create(
                  new Class[] {HibernateToolTask.class, Folder.class},
                  new Object[] {parent, this.destDir});
    } else if (type.equals("java")) {
      enhancer.setSuperclass(Hbm2JavaExporterTaskWrapper.class);
      enhancer.setClassLoader(Hbm2JavaExporterTaskWrapper.class.getClassLoader());
      proxy =
          (Hbm2JavaExporterTaskWrapper)
              enhancer.create(
                  new Class[] {HibernateToolTask.class, Folder.class},
                  new Object[] {parent, this.destDir});
    } else if (type.equals("query")) {
      enhancer.setSuperclass(QueryExporterTask.class);
      enhancer.setClassLoader(QueryExporterTask.class.getClassLoader());
      proxy =
          (QueryExporterTask)
              enhancer.create(
                  new Class[] {HibernateToolTask.class, String.class, Folder.class},
                  new Object[] {parent, serviceName, this.destDir});
    } else if (type.equals("mapping")) {
      enhancer.setSuperclass(Hbm2HbmXmlExporterTaskWrapper.class);
      enhancer.setClassLoader(Hbm2HbmXmlExporterTaskWrapper.class.getClassLoader());
      proxy =
          (Hbm2HbmXmlExporterTaskWrapper)
              enhancer.create(
                  new Class[] {HibernateToolTask.class, Folder.class},
                  new Object[] {parent, this.destDir});
    } else if (type.equals("springConfig")) {
      enhancer.setSuperclass(HibernateSpringConfigExporterTask.class);
      enhancer.setClassLoader(HibernateSpringConfigExporterTask.class.getClassLoader());
      proxy =
          (HibernateSpringConfigExporterTask)
              enhancer.create(
                  new Class[] {
                    HibernateToolTask.class,
                    Folder.class,
                    String.class,
                    String.class,
                    String.class,
                    String.class,
                    boolean.class,
                    boolean.class,
                    String.class,
                    Integer.class
                  },
                  new Object[] {
                    parent,
                    this.destDir,
                    serviceName,
                    this.packageName,
                    this.dataPackage,
                    this.className,
                    this.useIndividualCRUDOperations,
                    this.impersonateUser,
                    this.activeDirectoryDomain,
                    this.batchSize
                  });
    }
    return proxy;
  }
Exemple #24
0
 public ClassProxy(MethodInterceptor interceptor, Class<?> clazz) {
   enhancer = new Enhancer();
   enhancer.setSuperclass(clazz);
   enhancer.setCallback(interceptor);
 }