Java Code Examples for net.sf.cglib.proxy.Enhancer#setCallbackFilter()

The following examples show how to use net.sf.cglib.proxy.Enhancer#setCallbackFilter() . 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: ProxyFactory.java    From businessworks with Apache License 2.0 6 votes vote down vote up
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();
  }
}
 
Example 2
Source File: ComponentInstantiationPostProcessor.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@Override
public Object postProcessBeforeInstantiation(final Class<?> beanClass, final String beanName) throws BeansException {
    if (_interceptors != null && _interceptors.size() > 0) {
        if (ComponentMethodInterceptable.class.isAssignableFrom(beanClass)) {
            final Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(beanClass);
            enhancer.setCallbacks(getCallbacks());
            enhancer.setCallbackFilter(getCallbackFilter());
            enhancer.setNamingPolicy(ComponentNamingPolicy.INSTANCE);

            final Object bean = enhancer.create();
            return bean;
        }
    }
    return null;
}
 
Example 3
Source File: ProxyFactoryFactoryImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public BasicProxyFactoryImpl(Class superClass, Class[] interfaces) {
	if ( superClass == null && ( interfaces == null || interfaces.length < 1 ) ) {
		throw new AssertionFailure( "attempting to build proxy without any superclass or interfaces" );
	}

	Enhancer en = new Enhancer();
	en.setUseCache( false );
	en.setInterceptDuringConstruction( false );
	en.setUseFactory( true );
	en.setCallbackTypes( CALLBACK_TYPES );
	en.setCallbackFilter( FINALIZE_FILTER );
	if ( superClass != null ) {
		en.setSuperclass( superClass );
	}
	if ( interfaces != null && interfaces.length > 0 ) {
		en.setInterfaces( interfaces );
	}
	proxyClass = en.createClass();
	try {
		factory = ( Factory ) proxyClass.newInstance();
	}
	catch ( Throwable t ) {
		throw new HibernateException( "Unable to build CGLIB Factory instance" );
	}
}
 
Example 4
Source File: ComponentInstantiationPostProcessor.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
    if (_interceptors != null && _interceptors.size() > 0) {
        if (ComponentMethodInterceptable.class.isAssignableFrom(beanClass)) {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(beanClass);
            enhancer.setCallbacks(getCallbacks());
            enhancer.setCallbackFilter(getCallbackFilter());
            enhancer.setNamingPolicy(ComponentNamingPolicy.INSTANCE);

            Object bean = enhancer.create();
            return bean;
        }
    }
    return null;
}
 
Example 5
Source File: ClassByImplementationBenchmark.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * 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}) {
        protected Object getCallback(Method method) {
            if (method.getDeclaringClass() == baseClass) {
                return new FixedValue() {
                    public Object loadObject() {
                        return null;
                    }
                };
            } else {
                return NoOp.INSTANCE;
            }
        }
    };
    enhancer.setCallbackFilter(callbackHelper);
    enhancer.setCallbacks(callbackHelper.getCallbacks());
    return (ExampleInterface) enhancer.create();
}
 
Example 6
Source File: DalTransactionManager.java    From das with Apache License 2.0 5 votes vote down vote up
@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 DasTransactionInterceptor(), NoOp.INSTANCE};
    enhancer.setCallbacks(callbacks);
    enhancer.setInterfaces(new Class[] {TransactionalIntercepted.class});
    return (T) enhancer.create();
}
 
Example 7
Source File: DalTransactionManager.java    From dal with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 8
Source File: CGLIBLazyInitializer.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Class getProxyFactory(Class persistentClass, Class[] interfaces)
		throws HibernateException {
	Enhancer e = new Enhancer();
	e.setSuperclass( interfaces.length == 1 ? persistentClass : null );
	e.setInterfaces(interfaces);
	e.setCallbackTypes(new Class[]{
		InvocationHandler.class,
		NoOp.class,
  		});
 		e.setCallbackFilter(FINALIZE_FILTER);
 		e.setUseFactory(false);
	e.setInterceptDuringConstruction( false );
	return e.createClass();
}
 
Example 9
Source File: NodeDelegate.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 10
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 11
Source File: GenericDaoBase.java    From cosmic with Apache License 2.0 4 votes vote down vote up
protected GenericDaoBase() {
    super();
    final Type t = getClass().getGenericSuperclass();
    if (t instanceof ParameterizedType) {
        _entityBeanType = (Class<T>) ((ParameterizedType) t).getActualTypeArguments()[0];
    } else if (((Class<?>) t).getGenericSuperclass() instanceof ParameterizedType) {
        _entityBeanType = (Class<T>) ((ParameterizedType) ((Class<?>) t).getGenericSuperclass()).getActualTypeArguments()[0];
    } else {
        _entityBeanType = (Class<T>) ((ParameterizedType) ((Class<?>) ((Class<?>) t).getGenericSuperclass()).getGenericSuperclass()).getActualTypeArguments()[0];
    }

    s_daoMaps.put(_entityBeanType.getCanonicalName(), this);
    final Class<?>[] interfaceClasses = _entityBeanType.getInterfaces();
    if (interfaceClasses != null) {
        for (final Class<?> interfaceClass : interfaceClasses) {
            s_daoMaps.put(interfaceClass.getCanonicalName(), this);
        }
    }
    logDetectedDaos();

    _table = DbUtil.getTableName(_entityBeanType);

    final SqlGenerator generator = new SqlGenerator(_entityBeanType);
    _partialSelectSql = generator.buildSelectSql(false);
    _count = generator.buildCountSql();
    _distinctIdSql = generator.buildDistinctIdSql();
    _partialQueryCacheSelectSql = generator.buildSelectSql(true);
    _embeddedFields = generator.getEmbeddedFields();
    _insertSqls = generator.buildInsertSqls();
    final Pair<StringBuilder, Map<String, Object>> dc = generator.buildDiscriminatorClause();
    _discriminatorClause = dc.first().length() == 0 ? null : dc.first();
    _discriminatorValues = dc.second();

    _idAttributes = generator.getIdAttributes();
    _idField = _idAttributes.get(_table).length > 0 ? _idAttributes.get(_table)[0].field : null;

    _tables = generator.buildTableReferences();

    _allAttributes = generator.getAllAttributes();
    _allColumns = generator.getAllColumns();

    _selectByIdSql = buildSelectByIdSql(createPartialSelectSql(null, true));
    _removeSql = generator.buildRemoveSql();
    _deleteSqls = generator.buildDeleteSqls();
    _removed = generator.getRemovedAttribute();
    _tgs = generator.getTableGenerators();
    _ecAttributes = generator.getElementCollectionAttributes();

    TableGenerator tg = this.getClass().getAnnotation(TableGenerator.class);
    if (tg != null) {
        _tgs.put(tg.name(), tg);
    }
    tg = this.getClass().getSuperclass().getAnnotation(TableGenerator.class);
    if (tg != null) {
        _tgs.put(tg.name(), tg);
    }

    final Callback[] callbacks = new Callback[]{NoOp.INSTANCE, new UpdateBuilder(this)};

    _enhancer = new Enhancer();
    _enhancer.setSuperclass(_entityBeanType);
    _enhancer.setCallbackFilter(s_callbackFilter);
    _enhancer.setCallbacks(callbacks);
    _factory = (Factory) _enhancer.create();

    _searchEnhancer = new Enhancer();
    _searchEnhancer.setSuperclass(_entityBeanType);
    _searchEnhancer.setCallback(new UpdateBuilder(this));

    if (s_logger.isTraceEnabled()) {
        s_logger.trace("Select SQL: " + _partialSelectSql.first().toString());
        s_logger.trace("Remove SQL: " + (_removeSql != null ? _removeSql.first() : "No remove sql"));
        s_logger.trace("Select by Id SQL: " + _selectByIdSql);
        s_logger.trace("Table References: " + _tables);
        s_logger.trace("Insert SQLs:");
        for (final Pair<String, Attribute[]> insertSql : _insertSqls) {
            s_logger.trace(insertSql.first());
        }

        s_logger.trace("Delete SQLs");
        for (final Pair<String, Attribute[]> deletSql : _deleteSqls) {
            s_logger.trace(deletSql.first());
        }

        s_logger.trace("Collection SQLs");
        for (final Attribute attr : _ecAttributes) {
            final EcInfo info = (EcInfo) attr.attache;
            s_logger.trace(info.insertSql);
            s_logger.trace(info.selectSql);
        }
    }

    setRunLevel(ComponentLifecycle.RUN_LEVEL_SYSTEM);
}
 
Example 12
Source File: GenericDaoBase.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
protected GenericDaoBase() {
    super();
    Type t = getClass().getGenericSuperclass();
    if (t instanceof ParameterizedType) {
        _entityBeanType = (Class<T>)((ParameterizedType)t).getActualTypeArguments()[0];
    } else if (((Class<?>)t).getGenericSuperclass() instanceof ParameterizedType) {
        _entityBeanType = (Class<T>)((ParameterizedType)((Class<?>)t).getGenericSuperclass()).getActualTypeArguments()[0];
    } else {
        _entityBeanType = (Class<T>)((ParameterizedType)((Class<?>)((Class<?>)t).getGenericSuperclass()).getGenericSuperclass()).getActualTypeArguments()[0];
    }

    s_daoMaps.put(_entityBeanType, this);
    Class<?>[] interphaces = _entityBeanType.getInterfaces();
    if (interphaces != null) {
        for (Class<?> interphace : interphaces) {
            s_daoMaps.put(interphace, this);
        }
    }

    _table = DbUtil.getTableName(_entityBeanType);

    final SqlGenerator generator = new SqlGenerator(_entityBeanType);
    _partialSelectSql = generator.buildSelectSql(false);
    _count = generator.buildCountSql();
    _distinctIdSql= generator.buildDistinctIdSql();
    _partialQueryCacheSelectSql = generator.buildSelectSql(true);
    _embeddedFields = generator.getEmbeddedFields();
    _insertSqls = generator.buildInsertSqls();
    final Pair<StringBuilder, Map<String, Object>> dc = generator.buildDiscriminatorClause();
    _discriminatorClause = dc.first().length() == 0 ? null : dc.first();
    _discriminatorValues = dc.second();

    _idAttributes = generator.getIdAttributes();
    _idField = _idAttributes.get(_table).length > 0 ? _idAttributes.get(_table)[0].field : null;

    _tables = generator.buildTableReferences();

    _allAttributes = generator.getAllAttributes();
    _allColumns = generator.getAllColumns();

    _selectByIdSql = buildSelectByIdSql(createPartialSelectSql(null, true));
    _removeSql = generator.buildRemoveSql();
    _deleteSqls = generator.buildDeleteSqls();
    _removed = generator.getRemovedAttribute();
    _tgs = generator.getTableGenerators();
    _ecAttributes = generator.getElementCollectionAttributes();

    TableGenerator tg = this.getClass().getAnnotation(TableGenerator.class);
    if (tg != null) {
        _tgs.put(tg.name(), tg);
    }
    tg = this.getClass().getSuperclass().getAnnotation(TableGenerator.class);
    if (tg != null) {
        _tgs.put(tg.name(), tg);
    }

    Callback[] callbacks = new Callback[] {NoOp.INSTANCE, new UpdateBuilder(this)};

    _enhancer = new Enhancer();
    _enhancer.setSuperclass(_entityBeanType);
    _enhancer.setCallbackFilter(s_callbackFilter);
    _enhancer.setCallbacks(callbacks);
    _factory = (Factory)_enhancer.create();

    _searchEnhancer = new Enhancer();
    _searchEnhancer.setSuperclass(_entityBeanType);
    _searchEnhancer.setCallback(new UpdateBuilder(this));

    if (s_logger.isTraceEnabled()) {
        s_logger.trace("Select SQL: " + _partialSelectSql.first().toString());
        s_logger.trace("Remove SQL: " + (_removeSql != null ? _removeSql.first() : "No remove sql"));
        s_logger.trace("Select by Id SQL: " + _selectByIdSql);
        s_logger.trace("Table References: " + _tables);
        s_logger.trace("Insert SQLs:");
        for (final Pair<String, Attribute[]> insertSql : _insertSqls) {
            s_logger.trace(insertSql.first());
        }

        s_logger.trace("Delete SQLs");
        for (final Pair<String, Attribute[]> deletSql : _deleteSqls) {
            s_logger.trace(deletSql.first());
        }

        s_logger.trace("Collection SQLs");
        for (Attribute attr : _ecAttributes) {
            EcInfo info = (EcInfo)attr.attache;
            s_logger.trace(info.insertSql);
            s_logger.trace(info.selectSql);
        }
    }

    setRunLevel(ComponentLifecycle.RUN_LEVEL_SYSTEM);
}