net.sf.cglib.proxy.Callback Java Examples

The following examples show how to use net.sf.cglib.proxy.Callback. 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: SeiFactoryImpl.java    From tomee with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
 
Example #3
Source File: GenericDaoBase.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #4
Source File: CGlibProxyFactory.java    From blog with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
	public <T> T createProxy(T targetObject, Callback callback) {
		if (targetObject == null) {
			throw new IllegalArgumentException("targetObject must not be null");
		}
		if (callback == null) {
			throw new IllegalArgumentException("callback must not be null");
		}
		Class<?> targetType = targetObject.getClass();
		return (T) Enhancer.create(targetType, callback);
//		Class<?> superclass = targetType.getSuperclass();
//		List<Class<?>> allInterfaces = ClassUtils.getAllInterfaces(targetType);
//		Class<?>[] allInterfacesAsArray = (Class<?>[]) allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
//		Enhancer enhancer = new Enhancer();
//		enhancer.setSuperclass(superclass);
//		enhancer.setInterfaces(allInterfacesAsArray);
//		enhancer.setCallback(callback);
//		enhancer.setUseFactory(true);
//
//		Object proxyObject = enhancer.create();
//		return (T) proxyObject;
	}
 
Example #5
Source File: GenericDaoBase.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #6
Source File: CGLIBEnhancedConverter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private Callback createReverseEngineeredCallbackOfProperType(Callback callback, int index,
    Map 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) {
                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));
}
 
Example #7
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 #8
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 #9
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 #10
Source File: ComponentInstantiationPostProcessor.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public ComponentInstantiationPostProcessor() {
    _callbacks = new Callback[2];
    _callbacks[0] = NoOp.INSTANCE;
    _callbacks[1] = new InterceptorDispatcher();

    _callbackFilter = new InterceptorFilter();
}
 
Example #11
Source File: CGLIBEnhancedConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void readCallback(HierarchicalStreamReader reader, UnmarshallingContext context,
    List callbacksToEnhance, List callbacks) {
    Callback callback = (Callback)context.convertAnother(null, mapper.realClass(reader
        .getNodeName()));
    callbacks.add(callback);
    if (callback == null) {
        callbacksToEnhance.add(NoOp.INSTANCE);
    } else {
        callbacksToEnhance.add(callback);
    }
}
 
Example #12
Source File: FixtureFactory.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
protected <T extends InteractionAwareFixture> T createFirst(Callback callback, Class<T> clazz, Class<?>[] constructorTypes, Object[] constructorArgs) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(clazz);
    enhancer.setCallback(callback);

    T result;
    if (constructorArgs != null && constructorArgs.length > 0) {
        result = (T) enhancer.create(constructorTypes, constructorArgs);
    } else {
        result = (T) enhancer.create();
    }
    return result;
}
 
Example #13
Source File: FixtureFactory.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
protected <T extends InteractionAwareFixture> T createUsingFactory(Callback callback, Factory factory, Class<?>[] constructorTypes, Object[] constructorArgs) {
    Callback[] callbacks = new Callback[] { callback };

    T result;
    if (constructorArgs != null && constructorArgs.length > 0) {
        result = (T) factory.newInstance(constructorTypes, constructorArgs, callbacks);
    } else {
        result = (T) factory.newInstance(callbacks);
    }
    return result;
}
 
Example #14
Source File: ProxyFactoryFactoryImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Object getProxy() {
	try {
		return factory.newInstance(
				new Callback[] { new PassThroughInterceptor( proxyClass.getName() ), NoOp.INSTANCE }
		);
	}
	catch ( Throwable t ) {
		throw new HibernateException( "Unable to instantiate proxy instance" );
	}
}
 
Example #15
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 #16
Source File: CGLIBEnhancedConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #17
Source File: ComponentInstantiationPostProcessor.java    From cosmic with Apache License 2.0 5 votes vote down vote up
public ComponentInstantiationPostProcessor() {
    _callbacks = new Callback[2];
    _callbacks[0] = NoOp.INSTANCE;
    _callbacks[1] = new InterceptorDispatcher();

    _callbackFilter = new InterceptorFilter();
}
 
Example #18
Source File: ProxyFactory.java    From businessworks with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #19
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 #20
Source File: ComponentInstantiationPostProcessor.java    From cosmic with Apache License 2.0 4 votes vote down vote up
private Callback[] getCallbacks() {
    return _callbacks;
}
 
Example #21
Source File: ComponentInstantiationPostProcessor.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
private Callback[] getCallbacks() {
    return _callbacks;
}
 
Example #22
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);
}