public static HibernateProxy getProxy( final Factory factory, final Class persistentClass, final Class[] interfaces, final Method getIdentifierMethod, final Method setIdentifierMethod, final Serializable id, final SessionImplementor session) throws HibernateException { final CGLIBLazyInitializer instance = new CGLIBLazyInitializer( persistentClass, interfaces, id, getIdentifierMethod, setIdentifierMethod, session ); final HibernateProxy proxy = (HibernateProxy) factory.newInstance(instance); instance.constructed = true; return proxy; }
public static Factory getProxyFactory(Class persistentClass, Class[] interfaces) throws HibernateException { //note: interfaces is assumed to already contain HibernateProxy.class try { return (Factory) Enhancer.create( (interfaces.length==1) ? persistentClass : null, interfaces, NULL_METHOD_INTERCEPTOR ); } catch (Throwable t) { LogFactory.getLog(LazyInitializer.class).error("CGLIB Enhancement failed", t); throw new HibernateException( "CGLIB Enhancement failed", t ); } }
@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(); } }
@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; }
@Test public void equalsTest() throws Throwable { Implementation<Implementee> implementation = this.implementationResolver .resolve(Implementee.class, Implementor0.class, Implementor1.class); ImplementorBeanFactory implementorBeanFactory = SimpleImplementorBeanFactory .valueOf(new Implementor0(), new Implementor1()); Implementee implementee = this.cglibImplementeeBeanBuilder .build(implementation, implementorBeanFactory); CglibImplementeeInvocationHandler handler = (CglibImplementeeInvocationHandler) (((Factory) implementee) .getCallback(0)); Assert.assertTrue(handler.equals(handler)); Assert.assertFalse(handler.equals(null)); Assert.assertTrue(handler .equals(new CglibImplementeeInvocationHandler(implementation, implementorBeanFactory, this.cglibImplementeeBeanBuilder .getImplementeeMethodInvocationFactory()))); Assert.assertTrue(handler.equals(implementee)); Assert.assertFalse(handler.equals(new Object())); }
@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); }
/** * Creates the scoped proxy object using the given provider. * * @param injector The injector. * @return The scoped proxy object. */ @SuppressWarnings("unchecked") public T create(Injector injector) { Preconditions.checkNotNull(injector, "injector"); Preconditions.checkState(this.dispatcher != null, "no provider set"); this.enhancer.setCallbackType(this.dispatcher.getClass()); final Class<T> enhancedClass = this.enhancer.createClass(); final Errors errors = new Errors(); final T proxyInstance = this.constructionStrategy .createInstance(enhancedClass, injector, errors); errors.throwProvisionExceptionIfErrorsExist(); final Factory factory = (Factory) proxyInstance; factory.setCallback(CALLBACK_INDEX, this.dispatcher); return proxyInstance; }
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" ); } }
public void testSupportProxiesWithMultipleCallbackSetToNull() throws NullPointerException { final Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(HashMap.class); enhancer.setCallback(NoOp.INSTANCE); final HashMap orig = (HashMap)enhancer.create(); ((Factory)orig).setCallback(0, null); final String xml = "" + "<CGLIB-enhanced-proxy>\n" + " <type>java.util.HashMap</type>\n" + " <interfaces/>\n" + " <hasFactory>true</hasFactory>\n" + " <null/>\n" + "</CGLIB-enhanced-proxy>"; assertBothWays(orig, xml); }
@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; }
/** * 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; }
@Override protected void decorateInstance(T result, final MethodIntercept methodIntercept) { MethodInterceptor methodInterceptor = new MethodInterceptor() { public Object intercept(final Object proxy, Method method, Object[] args, final MethodProxy superProxy) throws Throwable { return methodIntercept.intercept(proxy, new MethodAdapter(method), args, new MethodIntercept.SuperInvoker() { public Object invokeSuper(Object[] superArgs) throws Throwable { return superProxy.invokeSuper(proxy, superArgs); } }); } }; Factory factory = (Factory) result; int callbackCount = factory.getCallbacks().length; for(int i = 0; i < callbackCount; i++) { factory.setCallback(i, methodInterceptor); } }
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; }
/** * Checks the given object proxy * @param obj The proxy to check * @throws Exception */ private void checkClassProxy(Object obj) throws Exception { assertTrue(obj instanceof Factory); assertTrue(obj instanceof FluentProxy); ParameterizedClass fluent = FluentProxyFactory.getFluentType(obj); assertNotNull(fluent); assertEquals(fluent.getRawClass(), Object.class); assertTrue(fluent.getParameterizations().isEmpty()); assertTrue(FluentProxyFactory.isFluentProxy(obj)); assertNull(FluentProxyFactory.getInvocationDelegate(obj)); assertSame(FluentProxyFactory.getFluentProxyFactory(obj), factory); String description = Long.toString(System.currentTimeMillis()); reset(provider, delegate); expect(provider.getInstance(String.class)).andReturn(description); replay(provider, delegate); assertSame(obj.toString(), description); verify(provider, delegate); }
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; }
@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); }
@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!"); }
@Override protected Fixture createFixture(final Object fixtureObject) { if (fixtureObject instanceof Factory) { return new JpaUnitFixture(executor, fixtureObject); } else { return new JpaUnitFixture(executor, createProxy(fixtureObject)); } }
@Test public void testCreateTestCreatesAnEnhancedObject() throws Exception { // GIVEN final JpaUnitConcordionRunner runner = new JpaUnitConcordionRunner(TestFixture.class); // WHEN final Object testObject1 = runner.createTest(); // THEN assertThat(testObject1, instanceOf(Factory.class)); }
@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 Factory getFactory(Class<?> classToProxify) throws IllegalAccessException, InstantiationException { if (factories.containsKey(classToProxify)) { return factories.get(classToProxify); } Factory factory = createFactory(classToProxify); factories.putIfAbsent(classToProxify, factory); return factory; }
private Factory createFactory(Class<?> classToProxify) throws IllegalAccessException, InstantiationException { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(classToProxify); enhancer.setCallbackFilter(new ImmutabilityCallbackFilter(this, classToProxify)); enhancer.setCallbackTypes(new Class[]{ EqualsMethodInterceptor.class, ExceptionMethodInterceptor.class, DelegatingMethodInterceptor.class, FreezingMethodInterceptor.class }); Class proxyClass = enhancer.createClass(); return (Factory) proxyClass.newInstance(); }
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; }
public void testSupportProxiesUsingFactoryWithMultipleCallbacks() throws NullPointerException { final Enhancer enhancer = new Enhancer(); enhancer.setCallbacks(new Callback[]{ new DelegatingInterceptor(null), new DelegatingHandler(null), new DelegatingDispatcher(null), NoOp.INSTANCE}); enhancer.setCallbackFilter(new CallbackFilter() { int i = 1; public int accept(Method method) { if (method.getDeclaringClass() == Runnable.class) { return 0; } return i < 3 ? i++ : i; } }); enhancer.setInterfaces(new Class[]{Runnable.class}); enhancer.setUseFactory(true); final Runnable orig = (Runnable)enhancer.create(); final String xml = xstream.toXML(orig); final Factory deserialized = (Factory)xstream.fromXML(xml); assertTrue("Not a Runnable anymore", deserialized instanceof Runnable); Callback[] callbacks = deserialized.getCallbacks(); assertEquals(4, callbacks.length); assertTrue(callbacks[0] instanceof DelegatingInterceptor); assertTrue(callbacks[1] instanceof DelegatingHandler); assertTrue(callbacks[2] instanceof DelegatingDispatcher); assertTrue(callbacks[3] instanceof NoOp); }
private Object create(Enhancer paramEnhancer, List paramList, boolean paramBoolean) { Object localObject = paramEnhancer.create(); if (paramBoolean) ((Factory)localObject).setCallbacks((Callback[])paramList.toArray(new Callback[paramList.size()])); return localObject; }