Exemplo n.º 1
0
 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;
 }
  /**
   * 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;
  }
  @Override
  public Jedis getResource() {
    // add a simplistic retry strategy so we don't fail on the occasional pool timeout
    Jedis resource = null;
    try {
      resource = super.getResource();
    } catch (RuntimeException e) {
      try {
        Thread.sleep(500); // give it half a second to recover
      } catch (InterruptedException ex) {
        throw new IllegalStateException(ex);
      }
      try {
        resource = super.getResource();
        poolRetryCounter.inc();
      } catch (RuntimeException e2) {
        LOG.error(
            "redis connect failure after retry once. Host: '"
                + redisHost
                + "' port: '"
                + redisPort
                + "' redis db: '"
                + redisDatabase
                + "' redis password: '******'");
        poolFailCounter.inc();
        // rethrow and let things escalate
        throw e2;
      }
    }

    return (Jedis) Enhancer.create(Jedis.class, new MeasuringJedisHandler(resource));
  }
Exemplo n.º 4
0
  public static <T> T recordDefaults(Class<T> type) {
    final T instance = newDefaultInstance(type);
    T proxy =
        (T)
            Enhancer.create(
                type,
                new Class<?>[] {$$RecordingConfigProxy.class},
                new MethodInterceptor() {
                  private final ConcurrentMap<Method, Object> invokedMethods =
                      new MapMaker().makeMap();

                  @Override
                  public Object intercept(
                      Object proxy, Method method, Object[] args, MethodProxy methodProxy)
                      throws Throwable {
                    if (GET_RECORDING_CONFIG_METHOD.equals(method)) {
                      return new $$RecordedConfigData<>(
                          instance, ImmutableSet.copyOf(invokedMethods.keySet()));
                    }

                    invokedMethods.put(method, Boolean.TRUE);

                    Object result = methodProxy.invoke(instance, args);
                    if (result == instance) {
                      return proxy;
                    } else {
                      return result;
                    }
                  }
                });

    return proxy;
  }
Exemplo n.º 5
0
 @SuppressWarnings("unchecked")
 public static <T> T mixinMapIntoBean(final T bean) {
   Enhancer<T> e = new Enhancer<T>();
   e.setSuperclass((Class<T>) bean.getClass());
   e.setInterfaces(new Class[] {Map.class});
   final Map<Object, Object> map = BeanMap.create(bean);
   e.setCallbackFilter(
       new CallbackFilter<T>() {
         public int accept(Method method) {
           return method.getDeclaringClass().equals(Map.class) ? 1 : 0;
         }
       });
   e.setCallbacks(
       new Callback[] {
         new Dispatcher() {
           public Object loadObject() {
             return bean;
           }
         },
         new Dispatcher() {
           public Object loadObject() {
             return map;
           }
         }
       });
   return e.create();
 }
 /**
  * This method returns a JDO proxy.
  *
  * @param <T> The type of object being dealt with.
  * @param type The source object.
  * @param resource The resource.
  * @return The result.
  * @throws BasicJDOException
  */
 public static <T> T createJDOProxy(
     Class typeRef,
     PersistanceSession persistanceSession,
     PersistanceResource resource,
     OntologySession ontologySession)
     throws BasicJDOException {
   try {
     Class type = typeRef;
     if (Enhancer.isEnhanced(typeRef)) {
       type = typeRef.getSuperclass();
     }
     T result;
     if (Resource.class.isAssignableFrom(type)) {
       BasicJDOResourceInvocationHandler handler =
           new BasicJDOResourceInvocationHandler(persistanceSession, resource, ontologySession);
       result =
           (T)
               Proxy.newProxyInstance(
                   Thread.currentThread().getContextClassLoader(),
                   new Class[] {Resource.class},
                   handler);
     } else {
       BasicJDOInvocationHandler handler =
           new BasicJDOInvocationHandler(type, persistanceSession, resource, ontologySession);
       result = (T) Enhancer.create(type, new Class[] {Resource.class}, handler);
       handler.initObject(result);
     }
     return result;
   } catch (Exception ex) {
     throw new BasicJDOException(
         "Failed to create the JDO proxy [" + typeRef.getName() + "] :" + ex.getMessage(), ex);
   }
 }
Exemplo n.º 7
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;
      }
    }
 /**
  * Performs a benchmark of an interface implementation using cglib.
  *
  * @return The created instance, in order to avoid JIT removal.
  */
 @Benchmark
 public ExampleInterface benchmarkCglib() {
   Enhancer enhancer = new Enhancer();
   enhancer.setUseCache(false);
   enhancer.setClassLoader(newClassLoader());
   enhancer.setSuperclass(baseClass);
   CallbackHelper callbackHelper =
       new CallbackHelper(Object.class, new Class[] {baseClass}) {
         @Override
         protected Object getCallback(Method method) {
           if (method.getDeclaringClass() == baseClass) {
             return new FixedValue() {
               @Override
               public Object loadObject() throws Exception {
                 return null;
               }
             };
           } else {
             return NoOp.INSTANCE;
           }
         }
       };
   enhancer.setCallbackFilter(callbackHelper);
   enhancer.setCallbacks(callbackHelper.getCallbacks());
   return (ExampleInterface) enhancer.create();
 }
Exemplo n.º 9
0
  public Object createProxy(PersistanceManager persistanceManager) {
    this.persistanceManager = persistanceManager;
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(PersistanceManager.class);
    enhancer.setCallback(this);

    return enhancer.create();
  }
Exemplo n.º 10
0
 private Object create(final Enhancer enhancer, List callbacks, boolean useFactory) {
   Object result = enhancer.create();
   if (useFactory) {
     ((Factory) result)
         .setCallbacks((Callback[]) callbacks.toArray(new Callback[callbacks.size()]));
   }
   return result;
 }
Exemplo n.º 11
0
 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;
 }
Exemplo n.º 12
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();
 }
Exemplo n.º 13
0
 public static Chinese getAuthInstance() {
   Enhancer en = new Enhancer();
   // 设置要代理的目标类
   en.setSuperclass(Chinese.class);
   // 设置要代理的拦截器
   en.setCallback(new AroundAdvice());
   // 生成代理类的实例
   return (Chinese) en.create();
 }
Exemplo n.º 14
0
  public static DynProxy newHeavyMethod() {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(DynProxy.class);
    enhancer.setCallback(new CglibHeavyMethodInterceptor());

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

    return cglibProxy;
  }
Exemplo n.º 15
0
 @Override
 public Object bind(Object targetImpl) {
   this.target = targetImpl;
   Enhancer enhancer = new Enhancer();
   enhancer.setSuperclass(this.target.getClass());
   // 回调方法
   enhancer.setCallback(this);
   // 创建代理对象
   return enhancer.create();
 }
Exemplo n.º 16
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();
 }
Exemplo n.º 18
0
  @SuppressWarnings("unchecked")
  public static <T> MethodCapturer<T> capture(T obj) {
    synchronized (s_cache) {
      MethodCapturer<T> capturer = (MethodCapturer<T>) s_cache.get(obj);
      if (capturer != null) {
        return capturer;
      }

      final MethodCapturer<T> capturerNew = new MethodCapturer<T>();

      Enhancer en = new Enhancer();
      en.setSuperclass(obj.getClass());
      en.setCallbacks(
          new Callback[] {
            new MethodInterceptor() {
              @Override
              public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3)
                  throws Throwable {
                capturerNew.setMethod(arg1);
                return null;
              }
            },
            new MethodInterceptor() {
              @Override
              public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3)
                  throws Throwable {
                return null;
              }
            }
          });
      en.setCallbackFilter(
          new CallbackFilter() {
            @Override
            public int accept(Method method) {
              if (method.getParameterTypes().length == 0 && method.getName().equals("finalize")) {
                return 1;
              }
              return 0;
            }
          });

      capturerNew.setInstance((T) en.create());

      // We expect MethodCapturer is only used for singleton objects here, so we only maintain a
      // limited cache
      // here
      if (s_cache.size() < CACHE_SIZE) {
        s_cache.put(obj, capturerNew);
      }

      return capturerNew;
    }
  }
Exemplo n.º 19
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();
  }
Exemplo n.º 20
0
  /**
   * Create a caching (memoizing) proxy for an object that contains methods with <code>Remember
   * </code> annotation. Calling these methods will cause them to be cached.
   *
   * @param <T> The type of the object
   * @param targetClass The class to create a proxy for. The class must provide a parameter-less
   *     constructor.
   * @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 the type <code>targetClass</code> where methods that are annotated by
   *     <code>Remember</code> will be cached.
   * @since 1.0
   */
  @SuppressWarnings("unchecked")
  public static <T> T createProxy(Class<T> targetClass, ICacheFactory cacheFactory) {
    cacheFactory = getCacheFactory(cacheFactory);

    MethodInterceptor interceptor = new ProxyInterceptor(cacheFactory);
    // Control which methods should go thru the interceptor
    Callback[] callbacks = RememberCallbackFilter.createCallbacks(interceptor);

    Enhancer enhancer = new Enhancer(); // cglib class
    enhancer.setSuperclass(targetClass);
    enhancer.setCallbacks(callbacks);
    enhancer.setCallbackFilter(RememberCallbackFilter.INSTANCE);

    return (T) enhancer.create();
  }
  /**
   * 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);
    }
  }
Exemplo n.º 22
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;
  }
Exemplo n.º 23
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);
      }
    }
Exemplo n.º 24
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);
    }
  }
Exemplo n.º 25
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;
  }
Exemplo n.º 26
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();
    }
  }
Exemplo n.º 27
0
 @SuppressWarnings("unchecked")
 private <T> T proxyForClass(final Class<T> proxyClass) {
   return (T) Enhancer.create(proxyClass, EMPTY_INTERFACES, CALLBACK_FILTER, callbacks);
 }
Exemplo n.º 28
0
 public <T> T getProxy(Class<T> CLS) {
   return (T) Enhancer.create(CLS, this);
 }
 @SuppressWarnings("unchecked")
 public <T> T newInstance(final Class<T> cls) {
   final Enhancer enhancer = lookupOrCreateEnhancerFor(cls);
   return (T) enhancer.create();
 }
Exemplo n.º 30
0
 /**
  * 生成代理类工厂
  *
  * @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();
 }