@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; } }
/** * 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); } }
public Object createProxy(PersistanceManager persistanceManager) { this.persistanceManager = persistanceManager; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(PersistanceManager.class); enhancer.setCallback(this); return enhancer.create(); }
/** * 创建代理对象 * * @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(); }
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 DynProxy newHeavyMethod() { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(DynProxy.class); enhancer.setCallback(new CglibHeavyMethodInterceptor()); DynProxy cglibProxy = (DynProxy) enhancer.create(); return cglibProxy; }
public static Chinese getAuthInstance() { Enhancer en = new Enhancer(); // 设置要代理的目标类 en.setSuperclass(Chinese.class); // 设置要代理的拦截器 en.setCallback(new AroundAdvice()); // 生成代理类的实例 return (Chinese) en.create(); }
@Override public Object bind(Object targetImpl) { this.target = targetImpl; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(this.target.getClass()); // 回调方法 enhancer.setCallback(this); // 创建代理对象 return enhancer.create(); }
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(); }
@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; } }
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; }
/** * 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(); }
/** * 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(); }
public static <T> T proxy(Class<T> type, Callback callback) { callback = callback != null ? callback : BLOCKER; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(type); enhancer.setCallbackType(callback.getClass()); @SuppressWarnings("unchecked") Class<T> proxyClass = enhancer.createClass(); @SuppressWarnings("unchecked") T proxy = (T) ObjenesisHelper.newInstance(proxyClass); ((Factory) proxy).setCallback(0, callback); return proxy; }
@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)); }
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; }
/** * @param factory * @param value */ public void invoke(ConfigurableListableBeanFactory factory, String value) { for (Map.Entry<Field, List<Class>> entry : targets.entrySet()) { Field field = entry.getKey(); for (Class clazz : entry.getValue()) { Map map = factory.getBeansOfType(clazz); for (Object target : map.values()) { try { Object convert = convert(field.getType(), value); if (Enhancer.isEnhanced(target.getClass())) { Object source = getCGLIBSource(target, clazz); field.set(source, convert); } else { field.set(target, convert); } } catch (IllegalAccessException e) { logger.warn( "Can't set value: " + value + "in field: " + field.getName() + "because of: " + e.getMessage()); } } } } }
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; }
/** * 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(); }
@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); } }
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { final Enhancer enhancer = new Enhancer(); reader.moveDown(); enhancer.setSuperclass((Class) context.convertAnother(null, Class.class)); reader.moveUp(); reader.moveDown(); List interfaces = new ArrayList(); while (reader.hasMoreChildren()) { reader.moveDown(); interfaces.add(context.convertAnother(null, mapper.realClass(reader.getNodeName()))); reader.moveUp(); } enhancer.setInterfaces((Class[]) interfaces.toArray(new Class[interfaces.size()])); reader.moveUp(); reader.moveDown(); boolean useFactory = Boolean.valueOf(reader.getValue()).booleanValue(); enhancer.setUseFactory(useFactory); reader.moveUp(); List callbacksToEnhance = new ArrayList(); List callbacks = new ArrayList(); Map callbackIndexMap = null; reader.moveDown(); if ("callbacks".equals(reader.getNodeName())) { reader.moveDown(); callbackIndexMap = (Map) context.convertAnother(null, HashMap.class); reader.moveUp(); while (reader.hasMoreChildren()) { reader.moveDown(); readCallback(reader, context, callbacksToEnhance, callbacks); reader.moveUp(); } } else { readCallback(reader, context, callbacksToEnhance, callbacks); } enhancer.setCallbacks( (Callback[]) callbacksToEnhance.toArray(new Callback[callbacksToEnhance.size()])); if (callbackIndexMap != null) { enhancer.setCallbackFilter(new ReverseEngineeredCallbackFilter(callbackIndexMap)); } reader.moveUp(); Object result = null; while (reader.hasMoreChildren()) { reader.moveDown(); if (reader.getNodeName().equals("serialVersionUID")) { enhancer.setSerialVersionUID(Long.valueOf(reader.getValue())); } else if (reader.getNodeName().equals("instance")) { result = create(enhancer, callbacks, useFactory); super.doUnmarshalConditionally(result, reader, context); } reader.moveUp(); } if (result == null) { result = create(enhancer, callbacks, useFactory); } return serializationMethodInvoker.callReadResolve(result); }
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); } }
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; }
@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(); }
/** -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(); } }
@Override public String serializedClass(final Class<?> type) { final String serializedName = super.serializedClass(type); if (type == null) { return serializedName; } final String typeName = type.getName(); return typeName.equals(serializedName) && typeName.indexOf(DEFAULT_NAMING_MARKER) > 0 && Enhancer.isEnhanced(type) ? alias : serializedName; }
/** * 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; }
private Enhancer createEnhancer(Class<?> toMock) { // Create the mock Enhancer enhancer = new Enhancer() { /** Filter all private constructors but do not check that there are some left */ @SuppressWarnings("rawtypes") @Override protected void filterConstructors(Class sc, List constructors) { CollectionUtils.filter(constructors, new VisibilityPredicate(sc, true)); } }; enhancer.setSuperclass(toMock); // ///CLOVER:OFF (I don't know how to test it automatically yet) // See issue ID: 2994002 if (toMock.getSigners() != null) { enhancer.setNamingPolicy(ALLOWS_MOCKING_CLASSES_IN_SIGNED_PACKAGES); } // ///CLOVER:ON return enhancer; }
/** * 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); } }