net.sf.cglib.proxy.Factory Java Examples

The following examples show how to use net.sf.cglib.proxy.Factory. 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: 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 #3
Source File: BindingTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetBlogsWithAuthorsAndPostsEagerly() {
  SqlSession session = sqlSessionFactory.openSession();
  try {
    BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class);
    List<Blog> blogs = mapper.selectBlogsWithAutorAndPostsEagerly();
    assertEquals(2, blogs.size());
    assertFalse(blogs.get(0) instanceof Factory);
    assertEquals(101, blogs.get(0).getAuthor().getId());
    assertEquals(1, blogs.get(0).getPosts().size());
    assertEquals(1, blogs.get(0).getPosts().get(0).getId());
    assertFalse(blogs.get(1) instanceof Factory);      
    assertEquals(102, blogs.get(1).getAuthor().getId());
    assertEquals(1, blogs.get(1).getPosts().size());
    assertEquals(2, blogs.get(1).getPosts().get(0).getId());
  } finally {
    session.close();
  }
}
 
Example #4
Source File: BindingTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetBlogsWithAuthorsAndPostsEagerly() {
  SqlSession session = sqlSessionFactory.openSession();
  try {
    BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class);
    List<Blog> blogs = mapper.selectBlogsWithAutorAndPostsEagerly();
    assertEquals(2, blogs.size());
    assertFalse(blogs.get(0) instanceof Factory);
    assertEquals(101, blogs.get(0).getAuthor().getId());
    assertEquals(1, blogs.get(0).getPosts().size());
    assertEquals(1, blogs.get(0).getPosts().get(0).getId());
    assertFalse(blogs.get(1) instanceof Factory);      
    assertEquals(102, blogs.get(1).getAuthor().getId());
    assertEquals(1, blogs.get(1).getPosts().size());
    assertEquals(2, blogs.get(1).getPosts().get(0).getId());
  } finally {
    session.close();
  }
}
 
Example #5
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 #6
Source File: CglibProxyTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateAProxyForAPartiallyLoadedBean() throws Exception {
  ResultLoaderMap loader = new ResultLoaderMap();
  loader.addLoader("id", null, null);
  Object proxy = proxyFactory.createProxy(author, loader, new Configuration(), new DefaultObjectFactory(), new ArrayList<Class<?>>(), new ArrayList<Object>());
  Author author2 = (Author) deserialize(serialize((Serializable) proxy));
  assertTrue(author2 instanceof Factory);
}
 
Example #7
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 #8
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 #9
Source File: CglibProxyTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateAProxyForAPartiallyLoadedBean() throws Exception {
  ResultLoaderMap loader = new ResultLoaderMap();
  loader.addLoader("id", null, null);
  Object proxy = proxyFactory.createProxy(author, loader, new Configuration(), new DefaultObjectFactory(), new ArrayList<Class<?>>(), new ArrayList<Object>());
  Author author2 = (Author) deserialize(serialize((Serializable) proxy));
  assertTrue(author2 instanceof Factory);
}
 
Example #10
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 #11
Source File: CglibProxySource.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
@Override
public T resolveProxy(final T proxy) {
    @SuppressWarnings("unchecked")
    final
    CglibProxyHandler<T> cglibProxyHandler =
            (CglibProxyHandler<T>) ((Factory) proxy).getCallback(0);
    final T pooledObject = cglibProxyHandler.disableProxy();
    return pooledObject;
}
 
Example #12
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 #13
Source File: GenericDaoBase.java    From cosmic with Apache License 2.0 4 votes vote down vote up
public T createSearchEntity(final MethodInterceptor interceptor) {
    final T entity = (T) _searchEnhancer.create();
    final Factory factory = (Factory) entity;
    factory.setCallback(0, interceptor);
    return entity;
}
 
Example #14
Source File: GenericDaoBase.java    From cosmic with Apache License 2.0 4 votes vote down vote up
@DB()
public static <T> UpdateBuilder getUpdateBuilder(final T entityObject) {
    final Factory factory = (Factory) entityObject;
    assert (factory != null);
    return (UpdateBuilder) factory.getCallback(1);
}
 
Example #15
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);
}
 
Example #16
Source File: GenericDaoBase.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
@DB()
public static <T> UpdateBuilder getUpdateBuilder(final T entityObject) {
    final Factory factory = (Factory)entityObject;
    assert (factory != null);
    return (UpdateBuilder)factory.getCallback(1);
}