public static Object createProxy(Object realObject) { try { MethodInterceptor interceptor = new HammerKiller(); Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(realObject.getClass()); enhancer.setCallbackType(interceptor.getClass()); Class classForProxy = enhancer.createClass(); Enhancer.registerCallbacks(classForProxy, new Callback[]{interceptor}); Object createdProxy = classForProxy.newInstance(); for (Field realField : FieldUtils.getAllFieldsList(realObject.getClass())) { if (Modifier.isStatic(realField.getModifiers())) continue; realField.setAccessible(true); realField.set(createdProxy, realField.get(realObject)); } CreeperKiller.LOG.info("Removed HammerCore main menu hook, ads will no longer be displayed."); return createdProxy; } catch (Exception e) { CreeperKiller.LOG.error("Failed to create a proxy for HammerCore ads, they will not be removed.", e); } return realObject; }
private Callback createReverseEngineeredCallbackOfProperType(final Callback callback, final int index, final Map<? super Object, ? super Object> callbackIndexMap) { Class<?> iface = null; Class<?>[] interfaces = callback.getClass().getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if (Callback.class.isAssignableFrom(interfaces[i])) { iface = interfaces[i]; if (iface == Callback.class) { final ConversionException exception = new ConversionException("Cannot handle CGLIB callback"); exception.add("CGLIB callback type", callback.getClass().getName()); throw exception; } interfaces = iface.getInterfaces(); if (Arrays.asList(interfaces).contains(Callback.class)) { break; } i = -1; } } return (Callback)Proxy.newProxyInstance(iface.getClassLoader(), new Class[]{iface}, new ReverseEngineeringInvocationHandler(index, callbackIndexMap)); }
public ConstructionProxy<T> create() throws ErrorsException { if (interceptors.isEmpty()) { return new DefaultConstructionProxyFactory<T>(injectionPoint).create(); } @SuppressWarnings("unchecked") Class<? extends Callback>[] callbackTypes = new Class[callbacks.length]; for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] == net.sf.cglib.proxy.NoOp.INSTANCE) { callbackTypes[i] = net.sf.cglib.proxy.NoOp.class; } else { callbackTypes[i] = net.sf.cglib.proxy.MethodInterceptor.class; } } // Create the proxied class. We're careful to ensure that all enhancer state is not-specific // to this injector. Otherwise, the proxies for each injector will waste PermGen memory try { Enhancer enhancer = BytecodeGen.newEnhancer(declaringClass, visibility); enhancer.setCallbackFilter(new IndicesCallbackFilter(methods)); enhancer.setCallbackTypes(callbackTypes); return new ProxyConstructor<T>(enhancer, injectionPoint, callbacks, interceptors); } catch (Throwable e) { throw new Errors().errorEnhancingClass(declaringClass, e).toException(); } }
@Test public void shouldGetValuesUsingProxyWrapper() { BusinessProposal businessProposal = getHibernateObjectOnRepository(); Negotiation negotiationProxy = BusinessModelProxy.from(businessProposal).proxy(Negotiation.class); List<Negotiation> list = new ArrayList<>(); if (negotiationProxy instanceof Factory) { Callback callback = ((Factory) negotiationProxy).getCallback(0); Object objectModel = ((ProxyInterceptor) callback).getObjectModel(); Object hibernateEntity = ((ProxyInterceptor) callback).getHibernateEntity(); System.out.println("testet"); System.out.println("testet"); System.out.println("testet"); System.out.println("testet"); } assertThat(negotiationProxy.getId(), Matchers.is(1l)); assertThat(negotiationProxy.getIntroduction(), Matchers.is("test introduction")); assertThat(negotiationProxy.getCareOf(), Matchers.is("Smith")); }
/** * @param object The object to check * @return The proxied type, null if the object is not a proxy */ public static Class<?> getProxiedTypeIfProxy(Object object) { if (object == null) { return null; } if (object instanceof Factory) { Callback[] callbacks = ((Factory) object).getCallbacks(); if (callbacks == null || callbacks.length == 0) { return null; } if (callbacks[0] instanceof CglibProxyMethodInterceptor) { return ((CglibProxyMethodInterceptor) callbacks[0]).getProxiedType(); } } return null; }
/** * note: don't remove, used through reflection from {@link org.unitils.core.util.ObjectFormatter} * * @param object The object to check * @return The proxied type, null if the object is not a proxy or mock */ @SuppressWarnings({"UnusedDeclaration"}) public static String getMockName(Object object) { if (object == null) { return null; } if (object instanceof MockObject) { return ((MockObject) object).getName(); } if (object instanceof Factory) { Callback callback = ((Factory) object).getCallback(0); if (callback instanceof CglibProxyMethodInterceptor) { return ((CglibProxyMethodInterceptor) callback).getMockName(); } } return null; }
@DB() protected T toEntityBean(final ResultSet result, final boolean cache) throws SQLException { final T entity = (T) _factory.newInstance(new Callback[]{NoOp.INSTANCE, new UpdateBuilder(this)}); toEntityBean(result, entity); if (cache && _cache != null) { try { _cache.put(new Element(_idField.get(entity), entity)); } catch (final Exception e) { s_logger.debug("Can't put it in the cache", e); } } return entity; }
@Override public Object intercept(final Object proxy, final Method method, final Object[] args, final MethodProxy methodProxy) throws Throwable { final Object other = args[0]; if (proxy == other) { return true; } else if (other instanceof Factory) { for (final Callback callback : ((Factory) other).getCallbacks()) { if (callback.getClass().isAssignableFrom(EqualsInterceptor.class)) { return target.equals(((EqualsInterceptor) callback).target); } } } return target.equals(other); }
@Override public <T> T createDynamicProxy(Class<T> type, Supplier<T> targetSupplier, String descriptionPattern, Object... descriptionParams) { final String description = String.format(descriptionPattern, descriptionParams); final Enhancer enhancer = new Enhancer(); enhancer.setClassLoader(new DelegatingClassLoader(type.getClassLoader(), Enhancer.class.getClassLoader())); enhancer.setInterfaces(new Class[]{type}); enhancer.setSuperclass(Object.class); enhancer.setCallbackFilter(FILTER); enhancer.setCallbacks(new Callback[]{ (Dispatcher) targetSupplier::get, (MethodInterceptor) (proxy, method, params, methodProxy) -> proxy == params[0], (MethodInterceptor) (proxy, method, params, methodProxy) -> System.identityHashCode(proxy), (MethodInterceptor) (proxy, method, params, methodProxy) -> description }); return type.cast(enhancer.create()); }
private Callback createReverseEngineeredCallbackOfProperType(final Callback callback, final int index, final Map<? super Object, ? super Object> callbackIndexMap) { Class<?> iface = null; Class<?>[] interfaces = callback.getClass().getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if (Callback.class.isAssignableFrom(interfaces[i])) { iface = interfaces[i]; if (iface == Callback.class) { final ConversionException exception = new ConversionException("Cannot handle CGLIB callback"); exception.add("CGLIB-callback-type", callback.getClass().getName()); throw exception; } interfaces = iface.getInterfaces(); if (Arrays.asList(interfaces).contains(Callback.class)) { break; } i = -1; } } return (Callback)Proxy.newProxyInstance(iface.getClassLoader(), new Class[]{iface}, new ReverseEngineeringInvocationHandler(index, callbackIndexMap)); }
public T getProxy() { Class proxyClass = getProxy(delegateClass.getName()); if (proxyClass == null) { Enhancer enhancer = new Enhancer(); if (delegateClass.isInterface()) { // 判断是否为接口,优先进行接口代理可以解决service为final enhancer.setInterfaces(new Class[] { delegateClass }); } else { enhancer.setSuperclass(delegateClass); } enhancer.setCallbackTypes(new Class[] { ProxyDirect.class, ProxyInterceptor.class }); enhancer.setCallbackFilter(new ProxyRoute()); proxyClass = enhancer.createClass(); // 注册proxyClass registerProxy(delegateClass.getName(), proxyClass); } Enhancer.registerCallbacks(proxyClass, new Callback[] { new ProxyDirect(), new ProxyInterceptor() }); try { Object[] _constructorArgs = new Object[0]; Constructor _constructor = proxyClass.getConstructor(new Class[] {});// 先尝试默认的空构造函数 return (T) _constructor.newInstance(_constructorArgs); } catch (Throwable e) { throw new OptimizerException(e); } finally { // clear thread callbacks to allow them to be gc'd Enhancer.registerStaticCallbacks(proxyClass, null); } }
@SuppressWarnings("unchecked") public <T> T create(Class<T> clazz, String widgetId) { // creating proxy class Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(clazz); enhancer.setUseFactory(true); enhancer.setCallbackType(RemoteObjectMethodInterceptor.class); if (clazz.getSigners() != null) { enhancer.setNamingPolicy(NAMING_POLICY_FOR_CLASSES_IN_SIGNED_PACKAGES); } Class<?> proxyClass = enhancer.createClass(); // instantiating class without constructor call ObjenesisStd objenesis = new ObjenesisStd(); Factory proxy = (Factory) objenesis.newInstance(proxyClass); proxy.setCallbacks(new Callback[]{new RemoteObjectMethodInterceptor(this, invoker, widgetId)}); T widget = (T) proxy; widgetIds.put(widget, widgetId); return widget; }
private Callback createReverseEngineeredCallbackOfProperType(Callback paramCallback, int paramInt, Map paramMap) { Object localObject1 = null; Object localObject2 = paramCallback.getClass().getInterfaces(); for (int i = 0; i < localObject2.length; i++) if (Callback.class.isAssignableFrom(localObject2[i])) { Object localObject3 = localObject2[i]; localObject1 = localObject3; if (localObject3 == Callback.class) { ConversionException localConversionException = new ConversionException("Cannot handle CGLIB callback"); localConversionException.add("CGLIB callback type", paramCallback.getClass().getName()); throw localConversionException; } Class[] arrayOfClass = localObject1.getInterfaces(); localObject2 = arrayOfClass; if (Arrays.asList(arrayOfClass).contains(Callback.class)) break; i = -1; } return (Callback)Proxy.newProxyInstance(localObject1.getClassLoader(), new Class[] { localObject1 }, new ReverseEngineeringInvocationHandler(paramInt, paramMap)); }
public void testMe(){ Article a = (Article) Enhancer.create(Article.class, new Class[]{DynamicUpdatable.class}, null, new Callback[]{ new MethodInterceptor(){ public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { proxy.invokeSuper(obj, args) ; System.out.println(method.getName()) ; return null; } } }) ; assertTrue(a instanceof DynamicUpdatable) ; a.getContent() ; }
/** * Creates a new instance of the given class, using the supplied interceptor. * Uses the EasyMock ClassInstantiatorFactory in order to avoid the cglib * limitation that prevents us from creating instances of classes that do not * have public default constructors. */ private Object create(Class<?> clss, Interceptor interceptor) { Enhancer e = new Enhancer(); e.setSuperclass(clss); e.setCallbackType(interceptor.getClass()); Class<?> controlClass = e.createClass(); Enhancer.registerCallbacks(controlClass, new Callback[] { interceptor }); Factory result = (Factory) objenesis.newInstance(controlClass); // This call is required to work around a cglib feature. See the comment in // org.easymock.classextension.internal.ClassProxyFactory, which uses the // same approach. result.getCallback(0); // And this call is required to work around a memory leak in cglib, which // sticks references to the class in a ThreadLocal that is never cleared. // See http://opensource.atlassian.com/projects/hibernate/browse/HHH-2481 Enhancer.registerCallbacks(controlClass, null); return result; }
@SuppressWarnings("unchecked") @DB() protected T toEntityBean(final ResultSet result, final boolean cache) throws SQLException { final T entity = (T)_factory.newInstance(new Callback[] {NoOp.INSTANCE, new UpdateBuilder(this)}); toEntityBean(result, entity); if (cache && _cache != null) { try { _cache.put(new Element(_idField.get(entity), entity)); } catch (final Exception e) { s_logger.debug("Can't put it in the cache", e); } } return entity; }
@SuppressWarnings("unchecked") static <T> T of(final Class<?> originalBeanClass, final TypeSafeWicketId parent) { final Enhancer enhancer = new Enhancer(); final List<Class<?>> interfaces = new ArrayList<>(); if (Modifier.isInterface(originalBeanClass.getModifiers())) { interfaces.add(originalBeanClass); } else { enhancer.setSuperclass(originalBeanClass); } interfaces.add(TYPE_SAFE_WICKET_ID_INTERFACE); final Class<?>[] interfacesAsArray = interfaces.toArray(EMPTY); enhancer.setInterfaces(interfacesAsArray); enhancer.setCallbackType(InterfaceMethodInterceptor.class); final Class<?> proxyClass = enhancer.createClass(); Enhancer.registerCallbacks(proxyClass, new Callback[] {new InterfaceMethodInterceptor(parent)}); final T proxy = (T) ObjenesisHelper.newInstance(proxyClass); saveProxy((TypeSafeWicketId) proxy); return proxy; }
public Remote createServiceEndpoint() throws ServiceException { //TODO figure out why this can't be called in readResolve! // synchronized (this) { // if (!initialized) { // initialize(); // initialized = true; // } // } Service service = ((ServiceImpl) serviceImpl).getService(); GenericServiceEndpoint serviceEndpoint = new GenericServiceEndpoint(portQName, service, location); Callback callback = new ServiceEndpointMethodInterceptor(serviceEndpoint, sortedOperationInfos, credentialsName); Callback[] callbacks = new Callback[]{NoOp.INSTANCE, callback}; Enhancer.registerCallbacks(serviceEndpointClass, callbacks); try { return (Remote) constructor.newInstance(new Object[]{serviceEndpoint}); } catch (InvocationTargetException e) { throw (ServiceException) new ServiceException("Could not construct service instance", e.getTargetException()).initCause(e); } }
@Override public Object createProxy(Interceptor interceptor, Class<?>[] types, MethodPointcut methodPointcut) { ProxyType proxyType = evalProxyType(types); Enhancer eh = new Enhancer(); DefaultMethodInterceptor dmi = new DefaultMethodInterceptor(interceptor); DefaultDispatcher dispatcher = new DefaultDispatcher(interceptor.getTarget()); Callback[] callbacks = new Callback[] { dmi, dispatcher }; eh.setCallbacks(callbacks); CallbackFilter cf = new CallbackFilterAdapter(methodPointcut); eh.setCallbackFilter(cf); switch (proxyType) { case CLASS: Class<?> clazz = types[0]; eh.setSuperclass(clazz); return eh.create(); case INTERFACES: eh.setInterfaces(types); return eh.create(); } throw new UnsupportedOperationException("Unsupported proxy types!"); }
private static Object newProxyByCglib(Typing typing, Handler handler) { Enhancer enhancer = new Enhancer() { /** includes all constructors */ protected void filterConstructors(Class sc, List constructors) {} }; enhancer.setClassLoader(Thread.currentThread().getContextClassLoader()); enhancer.setUseFactory(true); enhancer.setSuperclass(typing.superclass); enhancer.setInterfaces(typing.interfaces.toArray(new Class[0])); enhancer.setCallbackTypes(new Class[] { MethodInterceptor.class, NoOp.class }); enhancer.setCallbackFilter(new CallbackFilter() { /** ignores bridge methods */ public int accept(Method method) { return method.isBridge() ? 1 : 0; } }); Class<?> proxyClass = enhancer.createClass(); Factory proxy = (Factory) new ObjenesisStd().newInstance(proxyClass); proxy.setCallbacks(new Callback[] { asMethodInterceptor(handler), new SerializableNoOp() }); return proxy; }
private Callback getMessageCallback(LocalizationProvider localizationProvider, Method method, Class<?> type, String key) { if (type != String.class) { throw new InvalidReturnTypeException(type, method); } int selectorParameterIndex = GingerUtils.indexOfParameterAnnotation(method, Select.class); if (selectorParameterIndex != -1) { return createSelectorMessageLookupCallback(localizationProvider, method, key, selectorParameterIndex); } int pluralCountParameterIndex = GingerUtils.indexOfParameterAnnotation(method, PluralCount.class); if (pluralCountParameterIndex != -1) { return createPluralMessageLookupCallback(localizationProvider, method, key, pluralCountParameterIndex); } return new MessageLookupCallback(localizationProvider, key); }
static Map.Entry<Object, SetterInterceptor> getProxiedEntity(Class<?> entityClass) { EntityProxyFactory proxyFactory = getFactory(ClassHelper.actualClass(entityClass)); try { Object entity = null; SetterInterceptor interceptor = proxyFactory.new SetterInterceptor(); if (proxyFactory.isDistinguishable) { entity = proxyFactory.factory.newInstance(new Callback[] { interceptor, NoOp.INSTANCE }); } else { entity = proxyFactory.factory.newInstance(interceptor); } proxyFactory.modifiedPropNames.set(entity, new HashSet<String>()); interceptor.setEntity(entity); return new AbstractMap.SimpleEntry<Object, SetterInterceptor>(entity, interceptor); } catch (Throwable t) { throw new ODMException("Unable to instantiate proxy instance", t); } }
public T enhance(Class<T> clz) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(clz); enhancer.setCallbacks(new Callback[]{new PropertyInterceptor<>(this, schema), NoOp.INSTANCE}); enhancer.setCallbackFilter(new SchemaFilter<>(clz)); return (T) enhancer.create(); }
private void readCallback(final HierarchicalStreamReader reader, final UnmarshallingContext context, final List<Callback> callbacksToEnhance, final List<Callback> callbacks) { final Callback callback = (Callback)context.convertAnother(null, mapper.realClass(reader.getNodeName())); callbacks.add(callback); if (callback == null) { callbacksToEnhance.add(NoOp.INSTANCE); } else { callbacksToEnhance.add(callback); } }
private Object create(final Enhancer enhancer, final List<Callback> callbacks, final boolean useFactory) { final Object result = enhancer.create(); if (useFactory) { ((Factory)result).setCallbacks(callbacks.toArray(new Callback[callbacks.size()])); } return result; }
@SuppressWarnings("unchecked") // the constructor promises to construct 'T's ProxyConstructor(Enhancer enhancer, InjectionPoint injectionPoint, Callback[] callbacks, ImmutableMap<Method, List<MethodInterceptor>> methodInterceptors) { this.enhanced = enhancer.createClass(); // this returns a cached class if possible this.injectionPoint = injectionPoint; this.constructor = (Constructor<T>) injectionPoint.getMember(); this.callbacks = callbacks; this.methodInterceptors = methodInterceptors; this.fastClass = newFastClassForMember(enhanced, constructor); this.constructorIndex = fastClass.getIndex(constructor.getParameterTypes()); }
/** * 代理某一个对象指定方法,并在这个方法执行前后加入新方法,可指定过滤掉非代理的方法 * @author nan.li * @param t * @param before 执行目标方法前要执行的方法 * @param after 执行目标方法后要执行的方法 * @return */ @SuppressWarnings("unchecked") public static <T> T proxySurround(T t, CustomMethod before, CustomMethod after, CallbackFilter callbackFilter) { MethodInterceptor methodInterceptor = new MethodInterceptor() { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { before.execute(obj, method, args); Object result = null; try { result = proxy.invokeSuper(obj, args); } finally { after.execute(obj, method, args); } return result; } }; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(t.getClass()); // 回调方法 // enhancer.setCallback(methodInterceptor); enhancer.setCallbacks(new Callback[] {methodInterceptor, NoOp.INSTANCE}); //NoOp回调把对方法的调用直接委派到这个方法在父类中的实现。 //Methods using this Enhancer callback ( NoOp.INSTANCE ) will delegate directly to the default (super) implementation in the base class. //setCallbacks中定义了所使用的拦截器,其中NoOp.INSTANCE是CGlib所提供的实际是一个没有任何操作的拦截器, 他们是有序的。一定要和CallbackFilter里面的顺序一致。 enhancer.setCallbackFilter(callbackFilter); // 创建代理对象 return (T)enhancer.create(); }
public ComponentInstantiationPostProcessor() { _callbacks = new Callback[2]; _callbacks[0] = NoOp.INSTANCE; _callbacks[1] = new InterceptorDispatcher(); _callbackFilter = new InterceptorFilter(); }
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; CglibImplementeeInvocationHandler otherHandler = null; if (obj instanceof CglibImplementeeInvocationHandler) { otherHandler = (CglibImplementeeInvocationHandler) obj; } else if (obj instanceof Factory) { Callback[] callbacks = ((Factory) obj).getCallbacks(); // there is only one Callback if (callbacks == null || callbacks.length != 1) return false; Callback ih = callbacks[0]; if (!(ih instanceof CglibImplementeeInvocationHandler)) return false; otherHandler = (CglibImplementeeInvocationHandler) ih; } else { return false; } return super.equals(otherHandler); }
private static Object getDelegate(final Object fixtureObject) { final Callback[] callbacks = ((Factory) fixtureObject).getCallbacks(); for (final Callback callback : callbacks) { if (callback instanceof ConcordionInterceptor) { return ((ConcordionInterceptor) callback).getDelegate(); } } throw new JpaUnitException("Internal Error. No ConcordionInterceptor registered. Please submit a bug report!"); }
@SuppressWarnings("unchecked") public static <T> T create(Class<T> targetClass) throws InstantiationException, IllegalAccessException { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(targetClass); enhancer.setClassLoader(targetClass.getClassLoader()); enhancer.setCallbackFilter(new TransactionalCallbackFilter()); Callback[] callbacks = new Callback[]{new DalTransactionInterceptor(), NoOp.INSTANCE}; enhancer.setCallbacks(callbacks); enhancer.setInterfaces(new Class[]{TransactionalIntercepted.class}); return (T)enhancer.create(); }
public static <T> MethodProxy<T> forClass(Class<T> clazz) { MethodSignatureInterceptor methodSignatureInterceptor = new MethodSignatureInterceptor(); final Enhancer enhancer = new Enhancer(); enhancer.setUseCache(false); enhancer.setSuperclass(clazz); enhancer.setCallbackType(methodSignatureInterceptor.getClass()); final Class<?> proxyClass = enhancer.createClass(); Enhancer.registerCallbacks(proxyClass, new Callback[]{methodSignatureInterceptor}); T proxied = (T) ObjenesisHelper.newInstance(proxyClass); return new MethodProxy<>(methodSignatureInterceptor, proxied); }
@SuppressWarnings("unchecked") private <T> T proxifyBean(T bean) throws IllegalAccessException, InstantiationException { if (!isEnhanceable(bean.getClass())) { return bean; } Factory factory = getFactory(bean.getClass()); Callback[] callbacks = getCallbacks(bean); T newInstance = (T) factory.newInstance(callbacks); ExceptionMethodInterceptor exceptionCallback = (ExceptionMethodInterceptor) callbacks[1]; // By default the ExceptionMethodInterceptor is not active to allow calling setters in class constructor // After class instance creation it should be immediately activated exceptionCallback.setActive(true); return newInstance; }
private <T> Callback[] getCallbacks(T bean) { return new Callback[]{ new EqualsMethodInterceptor(bean), new ExceptionMethodInterceptor(bean), new DelegatingMethodInterceptor(bean), new FreezingMethodInterceptor(this, bean) }; }
static Object deProxy(final Object o) { if (o instanceof Factory) { final Factory factory = (Factory) o; final Callback callback = factory.getCallback(0); if (callback instanceof Supplier) { final Supplier<?> supplier = (Supplier<?>) callback; return supplier.get(); } } return o; }