net.sf.cglib.proxy.MethodInterceptor Java Examples

The following examples show how to use net.sf.cglib.proxy.MethodInterceptor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CglibProxy.java    From festival with Apache License 2.0 6 votes vote down vote up
@Override
public Object getProxy(ClassLoader classLoader) {
    Enhancer enhancer = new Enhancer();
    enhancer.setClassLoader(classLoader);
    enhancer.setCallbackType(MethodInterceptor.class);

    Class<?> targetClass = support.getBeanClass();
    enhancer.setSuperclass(targetClass);
    enhancer.setInterfaces(new Class[]{FestivalProxy.class, TargetClassAware.class});
    Class<?> proxyClass = enhancer.createClass();

    Objenesis objenesis = new ObjenesisStd();
    ObjectInstantiator<?> instantiator = objenesis.getInstantiatorOf(proxyClass);
    Object proxyInstance = instantiator.newInstance();

    ((Factory) proxyInstance).setCallbacks(new Callback[]{new CglibMethodInterceptor(support)});

    return proxyInstance;
}
 
Example #2
Source File: NotesNativeAPI.java    From domino-jna with Apache License 2.0 6 votes vote down vote up
/**
 * Wraps the specified API object to dump caller stacktraces right before invoking
 * native methods
 * 
 * @param api API
 * @return wrapped API
 */
static <T> T wrapWithCrashStackLogging(final Class<T> apiClazz, final T api) {

	try {
		return AccessController.doPrivileged(new PrivilegedExceptionAction<T>() {

			@Override
			public T run() throws Exception {
				MethodInterceptor handler = new MethodInterceptorWithStacktraceLogging<T>(api);
				T wrapperWithStacktraceLogging = (T) Enhancer.create(apiClazz, handler);
				return wrapperWithStacktraceLogging;
			}
		});
	} catch (PrivilegedActionException e) {
		e.printStackTrace();
		return api;
	}
}
 
Example #3
Source File: SpringLiteContext.java    From nuls-v2 with MIT License 6 votes vote down vote up
public static void init(MethodInterceptor interceptor, String... packName) {
    if (packName.length == 0) {
        throw new IllegalArgumentException("spring lite init package can't be null");
    }
    SpringLiteContext.interceptor = interceptor;
    Log.info("spring lite scan package : " + Arrays.toString(packName));
    Set<Class> classes = new HashSet<>(ScanUtil.scan("io.nuls.core.core.config"));
    Arrays.stream(packName).forEach(pack -> classes.addAll(ScanUtil.scan(pack)));
    classes.stream()
            //通过Order注解控制类加载顺序
            .sorted((b1, b2) -> getOrderByClass(b1) > getOrderByClass(b2) ? 1 : -1)
            .forEach(SpringLiteContext::checkBeanClass);
    configurationInjectToBean();
    autowireFields();
    callAfterPropertiesSet();
}
 
Example #4
Source File: PropertyStateSupport.java    From ymate-platform-v2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public T bind() {
    if (__bound == null) {
        __bound = (T) ClassUtils.wrapper(__source).duplicate(Enhancer.create(__targetClass, new MethodInterceptor() {
            @Override
            public Object intercept(Object targetObject, Method targetMethod, Object[] methodParams, MethodProxy methodProxy) throws Throwable {
                PropertyStateMeta _meta = __propertyStates.get(targetMethod.getName());
                if (_meta != null && ArrayUtils.isNotEmpty(methodParams) && !ObjectUtils.equals(_meta.getOriginalValue(), methodParams[0])) {
                    if (__ignoreNull && methodParams[0] == null) {
                        methodParams[0] = _meta.getOriginalValue();
                    }
                    _meta.setNewValue(methodParams[0]);
                }
                return methodProxy.invokeSuper(targetObject, methodParams);
            }
        }));
    }
    return __bound;
}
 
Example #5
Source File: ReflectiveParserManifest.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
ReflectiveParserImpl(Class<?> base, List<Property<?, ?>> properties) {
    InjectionChecks.checkInjectableCGLibProxyBase(base);

    this.properties = properties;
    this.propertyNames = properties.stream()
                                   .flatMap(property -> property.parser.names().stream())
                                   .collect(Collectors.toImmutableSet());

    final Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(base);
    enhancer.setInterfaces(new Class[]{ type.getRawType() });
    enhancer.setCallbackType(MethodInterceptor.class);
    enhancer.setUseFactory(true);
    this.impl = enhancer.createClass();
    this.injector = getMembersInjector((Class<T>) impl);
}
 
Example #6
Source File: DynamicProxyPerfClient.java    From JavaDesignPattern with Apache License 2.0 5 votes vote down vote up
private static void testCglibCreation() {
  long start = System.currentTimeMillis();
  for (int i = 0; i < creation; i++) {
    MethodInterceptor methodInterceptor = new SubjectInterceptor();
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(ConcreteSubject.class);
    enhancer.setCallback(methodInterceptor);
    enhancer.create();
  }
  long stop = System.currentTimeMillis();
  LOG.info("cglib creation time : {} ms", stop - start);
}
 
Example #7
Source File: NoHeapJvmOomExecutor.java    From chaosblade-exec-jvm with Apache License 2.0 5 votes vote down vote up
@Override
protected void innerRun(EnhancerModel enhancerModel, JvmOomConfiguration jvmOomConfiguration) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(OomObject.class);
    enhancer.setUseCache(false);
    enhancer.setCallback(new MethodInterceptor() {
        @Override
        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)
            throws Throwable {
            return proxy.invokeSuper(obj, args);
        }
    });
    enhancer.create();

}
 
Example #8
Source File: DynamicProxyPerfClient.java    From JavaDesignPattern with Apache License 2.0 5 votes vote down vote up
private static void testCglibExecution() {
  MethodInterceptor methodInterceptor = new SubjectInterceptor();
  Enhancer enhancer = new Enhancer();
  enhancer.setSuperclass(ConcreteSubject.class);
  enhancer.setCallback(methodInterceptor);
  ISubject subject = (ISubject) enhancer.create();
  long start = System.currentTimeMillis();
  for (int i = 0; i < execution; i++) {
    subject.action();
  }
  long stop = System.currentTimeMillis();
  LOG.info("cglib execution time : {} ms", stop - start);
}
 
Example #9
Source File: CgLibProxyClient.java    From JavaDesignPattern with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  MethodInterceptor methodInterceptor = new SubjectInterceptor();
  Enhancer enhancer = new Enhancer();
  enhancer.setSuperclass(ConcreteSubject.class);
  enhancer.setCallback(methodInterceptor);
  ISubject subject = (ISubject)enhancer.create();
  subject.action();
}
 
Example #10
Source File: DefaultProxyFactory.java    From ymate-platform-v2 with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T createProxy(final Class<?> targetClass, final List<IProxy> proxies) {
    return (T) Enhancer.create(targetClass, new MethodInterceptor() {
        @Override
        public Object intercept(Object targetObject, Method targetMethod, Object[] methodParams, final MethodProxy methodProxy) throws Throwable {
            return new AbstractProxyChain(DefaultProxyFactory.this, targetClass, targetObject, targetMethod, methodParams, proxies) {
                @Override
                protected Object doInvoke() throws Throwable {
                    return methodProxy.invokeSuper(getTargetObject(), getMethodParams());
                }
            }.doProxyChain();
        }
    });
}
 
Example #11
Source File: ProxyManager.java    From smart-framework with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T createProxy(final Class<?> targetClass, final List<Proxy> proxyList) {
    return (T) Enhancer.create(targetClass, new MethodInterceptor() {
        @Override
        public Object intercept(Object targetObject, Method targetMethod, Object[] methodParams, MethodProxy methodProxy) throws Throwable {
            return new ProxyChain(targetClass, targetObject, targetMethod, methodProxy, methodParams, proxyList).doProxyChain();
        }
    });
}
 
Example #12
Source File: ProxyManager.java    From smart-framework with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T createProxy(final Class<?> targetClass, final List<Proxy> proxyList) {
    return (T) Enhancer.create(targetClass, new MethodInterceptor() {
        @Override
        public Object intercept(Object targetObject, Method targetMethod, Object[] methodParams, MethodProxy methodProxy) throws Throwable {
            return new ProxyChain(targetClass, targetObject, targetMethod, methodProxy, methodParams, proxyList).doProxyChain();
        }
    });
}
 
Example #13
Source File: FixtureFactory.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
/**
 * Creates new instance of fixture.
 * @param clazz class to instantiate.
 * @param constructorTypes types of arguments used to determine which constructor to use.
 * @param constructorArgs arguments to pass to constructor of clazz.
 * @param <T> type to create.
 * @return instance of clazz (subclass, actually) that will have #aroundSlimInvoke() invoked on each method call.
 */
public <T extends InteractionAwareFixture> T create(Class<T> clazz, Class<?>[] constructorTypes, Object[] constructorArgs) {
    MethodInterceptor callback = createCallback();

    T result;
    if (FACTORIES.containsKey(clazz)) {
        Factory factory = FACTORIES.get(clazz);
        result = createUsingFactory(callback, factory, constructorTypes, constructorArgs);
    } else {
        result = createFirst(callback, clazz, constructorTypes, constructorArgs);
        FACTORIES.put(clazz, (Factory) result);
    }
    return result;
}
 
Example #14
Source File: TitledTable.java    From lambda-behave with MIT License 5 votes vote down vote up
public TitledTable<T, F, S> toShow(final String description, final ColumnDataSpecification<T> specification) {
    final Iterator<F> fit = firsts.iterator();
    final Iterator<S> sit = seconds.iterator();
    while (fit.hasNext()) {
        Object[] values = new Object[]{fit.next(), sit.next()};
        final T mock = (T) Enhancer.create(clazz, (MethodInterceptor) (o, method, objects, methodProxy) ->
            values[methods.indexOf(method)]);
        final String describe = String.format(description,
                values[0], values[1],
                methods.get(0).getName(), methods.get(1).getName());
        specifier.should(describe, expect -> specification.specifyBehaviour(expect, mock));
    }
    return this;
}
 
Example #15
Source File: Specifier.java    From lambda-behave with MIT License 5 votes vote down vote up
public <T, F, S> TitledTable<T, F, S> usesTable(final Class<T> clazz, final Function<T, F> first, final Function<T, S> second) {
    List<Method> m = new ArrayList<>();
    final T mock = (T) Enhancer.create(clazz, (MethodInterceptor) (o, method, objects, methodProxy) -> {
        m.add(method);
        return null;
    });
    first.apply(mock);
    second.apply(mock);
    return new TitledTable<>(m, this, clazz);
}
 
Example #16
Source File: CglibProxyHelper.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected Object getProxyInternal(ClassLoader loader, Class<?>[] interfaces,
                                  final java.lang.reflect.InvocationHandler h) {

    Class<?> superClass = null;
    List<Class<?>> theInterfaces = new ArrayList<>();

    for (Class<?> c : interfaces) {
        if (!c.isInterface()) {
            if (superClass != null) {
                throw new IllegalArgumentException("Only a single superclass is supported");
            }
            superClass = c;
        } else {
            theInterfaces.add(c);
        }
    }
    if (superClass != null) {
        Enhancer enhancer = new Enhancer();
        enhancer.setClassLoader(loader);
        enhancer.setSuperclass(superClass);
        enhancer.setInterfaces(theInterfaces.toArray(new Class<?>[0]));
        enhancer.setCallback(new MethodInterceptor() {

            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)
                throws Throwable {
                return h.invoke(obj, method, args);
            }

        });
        return enhancer.create();
    }
    return super.getProxyInternal(loader, interfaces, h);
}
 
Example #17
Source File: GenericDaoBase.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public T createSearchEntity(MethodInterceptor interceptor) {
    T entity = (T)_searchEnhancer.create();
    final Factory factory = (Factory)entity;
    factory.setCallback(0, interceptor);
    return entity;
}
 
Example #18
Source File: RpcCallbackDispatcher.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public T getTarget() {
    return (T)Enhancer.create(_targetObject.getClass(), new MethodInterceptor() {
        @Override
        public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
            _callbackMethod = arg1;
            return null;
        }
    });
}
 
Example #19
Source File: SecureCoreAdminHandlerTest.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
private CoreContainer getZkAwareCoreContainer(final CoreContainer cc) {
  Enhancer e = new Enhancer();
  e.setClassLoader(cc.getClass().getClassLoader());
  e.setSuperclass(CoreContainer.class);
  e.setCallback(new MethodInterceptor() {
    public Object intercept(Object obj, Method method, Object [] args, MethodProxy proxy) throws Throwable {
      if (method.getName().equals("isZooKeeperAware")) {
        return Boolean.TRUE;
      }
      return method.invoke(cc, args);
    }
  });
  return (CoreContainer)e.create();
}
 
Example #20
Source File: SeiFactoryImpl.java    From tomee with Apache License 2.0 5 votes vote down vote up
private Class enhanceServiceEndpointInterface(Class serviceEndpointInterface, ClassLoader classLoader) {
    Enhancer enhancer = new Enhancer();
    enhancer.setClassLoader(classLoader);
    enhancer.setSuperclass(GenericServiceEndpointWrapper.class);
    enhancer.setInterfaces(new Class[]{serviceEndpointInterface});
    enhancer.setCallbackFilter(new NoOverrideCallbackFilter(GenericServiceEndpointWrapper.class));
    enhancer.setCallbackTypes(new Class[]{NoOp.class, MethodInterceptor.class});
    enhancer.setUseFactory(false);
    enhancer.setUseCache(false);

    return enhancer.createClass();
}
 
Example #21
Source File: MyTest4.java    From Project with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    //使用动态代理动态生成类(不是实例)
    while (true) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(MyTest4.class);
        enhancer.setUseCache(false);
        enhancer.setCallback((MethodInterceptor) (obj, method, ags, proxy) -> proxy.invokeSuper(obj, ags));
        System.out.println("Hello World");
        // 在运行期不断创建 MyTest 类的子类
        enhancer.create();
    }
}
 
Example #22
Source File: MetaSpaceOOM.java    From Java-Interview with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    while (true){
        Enhancer  enhancer = new Enhancer() ;
        enhancer.setSuperclass(HeapOOM.class);
        enhancer.setUseCache(false) ;
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                return methodProxy.invoke(o,objects) ;
            }
        });
        enhancer.create() ;

    }
}
 
Example #23
Source File: MethodAreaOOM.java    From JavaBase with MIT License 5 votes vote down vote up
public static void main(String[] args) {
  while (true) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(OOMObject.class);
    enhancer.setUseCache(false);
    enhancer.setCallback((MethodInterceptor) (obj, method, args1, proxy) ->
        proxy.invokeSuper(obj, args)
    );
    enhancer.create();
  }
}
 
Example #24
Source File: SpringLiteContext.java    From nuls-v2 with MIT License 5 votes vote down vote up
/**
 * 使用动态代理的方式创建对象的实例
 * Create an instance of the object using a dynamic proxy.
 */
private static Object createProxy(Class clazz, MethodInterceptor interceptor) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(clazz);
    enhancer.setCallback(interceptor);
    return enhancer.create();
}
 
Example #25
Source File: LibCGDecoratorGenerator.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public <T, D extends Decorator<T>> DecoratorGenerator.Meta<T, D> implement(Class<T> type, Class<D> decorator) {
    final Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(decorator);
    enhancer.setCallbackType(MethodInterceptor.class);
    final Class<? extends D> impl = enhancer.createClass();
    enhancer.setCallback(new Callback<>(type, decorator));
    return new CGMeta(type, decorator, impl, enhancer);
}
 
Example #26
Source File: MetaSpaceOOM.java    From Java-Interview with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    while (true){
        Enhancer  enhancer = new Enhancer() ;
        enhancer.setSuperclass(HeapOOM.class);
        enhancer.setUseCache(false) ;
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                return methodProxy.invoke(o,objects) ;
            }
        });
        enhancer.create() ;

    }
}
 
Example #27
Source File: AopUtils.java    From nuls with MIT License 5 votes vote down vote up
public static final <T> T createProxy(Class<T> clazz,MethodInterceptor interceptor) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(clazz);
    enhancer.setCallback(new NulsMethodInterceptor(interceptor));

    return (T) enhancer.create();
}
 
Example #28
Source File: RpcCallbackDispatcher.java    From cosmic with Apache License 2.0 5 votes vote down vote up
public T getTarget() {
    return (T) Enhancer.create(_targetObject.getClass(), new MethodInterceptor() {
        @Override
        public Object intercept(final Object arg0, final Method arg1, final Object[] arg2, final MethodProxy arg3) throws Throwable {
            _callbackMethod = arg1;
            return null;
        }
    });
}
 
Example #29
Source File: SpringLiteContext.java    From nuls with MIT License 5 votes vote down vote up
/**
 * 根据传入的参数加载roc环境
 * Load the roc environment based on the incoming parameters.
 *
 * @param packName    扫描的根路径,The root package of the scan.
 * @param interceptor 方法拦截器,Method interceptor
 */
public static void init(final String packName, MethodInterceptor interceptor) {
    SpringLiteContext.interceptor = interceptor;
    List<Class> list = ScanUtil.scan(packName);
    list.forEach((Class clazz) -> checkBeanClass(clazz));
    autowireFields();
    success = true;
}
 
Example #30
Source File: FixtureFactory.java    From hsac-fitnesse-fixtures with Apache License 2.0 4 votes vote down vote up
protected MethodInterceptor createCallback() {
    FixtureInteraction nestedInteraction = getInteraction();
    return new LikeSlimInteraction(nestedInteraction);
}