Java Code Examples for net.sf.cglib.proxy.Enhancer

The following are top voted examples for showing how to use net.sf.cglib.proxy.Enhancer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: tauren   File: ProxyInterceptor.java   Source Code and License 6 votes vote down vote up
/**
 * 生成代理对象
 * @param targetClass  被代理对象的类型(类或接口)
 * @param target       被代理对象实例
 * @return             代理对象
 */
@SuppressWarnings("unchecked")
public <T> T newProxyInstance(final Class<T> targetClass, final Object target) {
    return (T) Enhancer.create(targetClass, new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            before(targetClass, method, args);
            Object ret = null;
            try {
                ret = method.invoke(target, args);
            } catch (Exception e) {
                exception(targetClass, method, args, e);
            }
            after(targetClass, method, args);
            return ret;
        }
    });
}
 
Example 2
Project: tauren   File: TransactionPartialInterceptor.java   Source Code and License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T newProxyInstance(final Class<T> targetClass, final Object target) {
    return (T) Enhancer.create(targetClass, new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

            /**
             * 如果没有@Transaction,则直接调用原方法
             */
            if (!method.isAnnotationPresent(Transaction.class)) {
                return method.invoke(target, args);
            }

            before(targetClass, method, args);
            Object ret = null;
            try {
                ret = method.invoke(target, args);
            } catch (Exception e) {
                exception(targetClass, method, args, e);
            }
            after(targetClass, method, args);
            return ret;
        }
    });
}
 
Example 3
Project: CreeperKiller   File: HammerKiller.java   Source Code and License 6 votes vote down vote up
public static Object createProxy(Object realObject) {
    try {
        MethodInterceptor interceptor = new HammerKiller();
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(realObject.getClass());
        enhancer.setCallbackType(interceptor.getClass());
        Class classForProxy = enhancer.createClass();
        Enhancer.registerCallbacks(classForProxy, new Callback[]{interceptor});
        Object createdProxy = classForProxy.newInstance();

        for (Field realField : FieldUtils.getAllFieldsList(realObject.getClass())) {
            if (Modifier.isStatic(realField.getModifiers()))
                continue;
            realField.setAccessible(true);

            realField.set(createdProxy, realField.get(realObject));
        }
        CreeperKiller.LOG.info("Removed HammerCore main menu hook, ads will no longer be displayed.");
        return createdProxy;
    } catch (Exception e) {
        CreeperKiller.LOG.error("Failed to create a proxy for HammerCore ads, they will not be removed.", e);
    }
    return realObject;
}
 
Example 4
Project: ProjectAres   File: ReflectiveParserManifest.java   Source Code and License 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 5
Project: parabuild-ci   File: CGLIBLazyInitializer.java   Source Code and License 6 votes vote down vote up
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 );
	}
}
 
Example 6
Project: gedis   File: JedisMethodInterceptor.java   Source Code and License 6 votes vote down vote up
/**
 * 使用 cglib 库创建 JedisProxy 的代理对象
 *
 * @return JedisProxy 代理
 */
public JedisProxy getJedisProxy() {
    if (jedisProxy != null) {
        return jedisProxy;
    }
    synchronized (JedisMethodInterceptor.class) {
        if (jedisProxy != null) {
            return jedisProxy;
        }
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(JedisProxy.class);
        enhancer.setCallback(this);
        jedisProxy = (JedisProxy) enhancer.create();
    }
    return jedisProxy;
}
 
Example 7
Project: businessworks   File: ProxyFactory.java   Source Code and License 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
Project: pageobjects   File: TransactionHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Adds transaction support to the page. The transaction support captures execution time of methods annotated with
 * {@link io.devcon5.pageobjects.tx.Transaction}
 *
 * @param <T>
 *
 * @param transactionSupport
 *         the transactionSupport element to be enhanced.
 * @return
 */
@SuppressWarnings("unchecked")
public static <T extends TransactionSupport> T addTransactionSupport(TransactionSupport transactionSupport) {
    return (T) Enhancer.create(transactionSupport.getClass(), (MethodInterceptor) (obj, method, args, proxy) -> {
        final Optional<String> txName = getTxName(transactionSupport, method);
        try {
            txName.ifPresent(transactionSupport::txBegin);
            Object result = method.invoke(transactionSupport, args);
            //dynamically enhance return values, if they are transactionSupport and not yet enhanced
            //this is required, i.e. if method return 'this' or create new objects which will
            //not be enhanced
            if (!isCGLibProxy(result) && result instanceof TransactionSupport) {
                result = addTransactionSupport(transactionSupport);
            }
            return result;
        } finally {
            txName.ifPresent(transactionSupport::txEnd);
        }
    });
}
 
Example 9
Project: java_learn   File: ClassPermGenOOM.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
	while(true) {
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(ClassPermGenOOM.class);
		enhancer.setUseCache(Boolean.FALSE);
		
		enhancer.setCallback(new MethodInterceptor() {
			
			@Override
			public Object intercept(Object arg0, Method arg1, Object[] arg2,
					MethodProxy arg3) throws Throwable {
				return arg3.invokeSuper(arg0, arg2);
			}
		});
		enhancer.create();
	}
}
 
Example 10
Project: odbogm   File: ObjectProxyFactory.java   Source Code and License 6 votes vote down vote up
public static <T> T cglibcreate(T o, OrientElement oe, Transaction transaction ) {
    // this is the main cglib api entry-point
    // this object will 'enhance' (in terms of CGLIB) with new capabilities
    // one can treat this class as a 'Builder' for the dynamic proxy
    Enhancer e = new Enhancer();

    // the class will extend from the real class
    e.setSuperclass(o.getClass());
    // we have to declare the interceptor  - the class whose 'intercept'
    // will be called when any method of the proxified object is called.
    ObjectProxy po = new ObjectProxy(o.getClass(),oe, transaction);
    e.setCallback(po);
    e.setInterfaces(new Class[]{IObjectProxy.class});

    // now the enhancer is configured and we'll create the proxified object
    T proxifiedObj = (T) e.create();
    
    po.___setProxyObject(proxifiedObj);
    
    // the object is ready to be used - return it
    return proxifiedObj;
}
 
Example 11
Project: odbogm   File: ObjectProxyFactory.java   Source Code and License 6 votes vote down vote up
public static <T> T cglibcreate(Class<T> c, OrientElement oe, Transaction transaction ) {
    // this is the main cglib api entry-point
    // this object will 'enhance' (in terms of CGLIB) with new capabilities
    // one can treat this class as a 'Builder' for the dynamic proxy
    Enhancer e = new Enhancer();

    // the class will extend from the real class
    e.setSuperclass(c);
    // we have to declare the interceptor  - the class whose 'intercept'
    // will be called when any method of the proxified object is called.
    ObjectProxy po = new ObjectProxy(c,oe, transaction);
    e.setCallback(po);
    e.setInterfaces(new Class[]{IObjectProxy.class});

    // now the enhancer is configured and we'll create the proxified object
    T proxifiedObj = (T) e.create();
    
    po.___setProxyObject(proxifiedObj);
    
    // the object is ready to be used - return it
    return proxifiedObj;
}
 
Example 12
Project: hotspot-gc-scenarios   File: Scenario4.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    Tmp tmp = new Tmp();
    while (!Thread.interrupted()) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Tmp.class);
        enhancer.setUseCache(false);
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
                return arg3.invokeSuper(arg0, arg2);
            }
        });
        enhancer.create();
    }
    System.out.println(tmp.hashCode());
}
 
Example 13
Project: domino-jna   File: NotesNativeAPI.java   Source Code and License 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 14
Project: md380codeplug-tool   File: LazyLoadingCodecDecorator.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public T decode(final BitBuffer buffer, final Resolver resolver,
                final Builder builder) throws DecodingException {
    final int size = wrapped.getSize().eval(resolver);
    final long pos = buffer.getBitPos();
    ClassLoader loader = this.getClass().getClassLoader();
    Enhancer enhancer = new Enhancer();
    enhancer.setClassLoader(loader);
    enhancer.setSuperclass(type);
    enhancer.setCallback(new MethodInterceptor() {

        private Object actual;

        public Object intercept(Object target, Method method,
                                Object[] args, MethodProxy proxy) throws Throwable {
            if (actual == null) {
                buffer.setBitPos(pos);
                actual = wrapped.decode(buffer, resolver, builder);
            }
            return proxy.invoke(actual, args);
        }
    });
    buffer.setBitPos(pos + size);
    return (T) enhancer.create();
}
 
Example 15
Project: ddd-reflection   File: ProxyCollectionHandler.java   Source Code and License 6 votes vote down vote up
public Object proxy() {
  Optional<Class> genericClassCollection = ReflectionUtils.getGenericClassCollection(fieldOrigin);

  if (!genericClassCollection.isPresent()) {
    throw new IllegalArgumentException("Invalid collection on field [" + fieldOrigin.getName() + "]");
  }

  Boolean hasPrimitive = PrimitiveTypeFields.getInstance().contains(genericClassCollection.get());

  if (hasPrimitive) {
    return hibernateCollection;
  } else {
    return this.hibernateCollection.stream()
        .map(item ->
            Enhancer.create(genericClassCollection.get(), ProxyInterceptor.create(item))
        ).collect(Collectors.toList());
  }
}
 
Example 16
Project: unitils   File: ProxyFactory.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected static <T> Class<T> createEnhancedClass(Class<T> proxiedClass, Class<?>... implementedInterfaces) {
    Enhancer enhancer = new Enhancer();

    Set<Class<?>> interfaces = new HashSet<Class<?>>();
    if (proxiedClass.isInterface()) {
        enhancer.setSuperclass(Object.class);
        interfaces.add(proxiedClass);
    } else {
        enhancer.setSuperclass(proxiedClass);
    }
    if (implementedInterfaces != null && implementedInterfaces.length > 0) {
        interfaces.addAll(asList(implementedInterfaces));
    }
    if (!interfaces.isEmpty()) {
        enhancer.setInterfaces(interfaces.toArray(new Class<?>[interfaces.size()]));
    }
    enhancer.setCallbackType(MethodInterceptor.class);
    enhancer.setUseFactory(true);
    return enhancer.createClass();
}
 
Example 17
Project: inbot-es-http-client   File: InbotJedisPool.java   Source Code and License 6 votes vote down vote up
@Override
public Jedis getResource() {
    // add a simplistic retry strategy so we don't fail on the occasional pool timeout
    Jedis resource = null;
    try {
        resource= super.getResource();
    } catch (RuntimeException e) {
        try {
            Thread.sleep(500); // give it half a second to recover
        } catch (InterruptedException ex) {
            throw new IllegalStateException(ex);
        }
        try {
            resource= super.getResource();
            poolRetryCounter.inc();
        } catch (RuntimeException e2) {
            LOG.error("redis connect failure after retry once. Host: '" + redisHost + "' port: '" + redisPort + "' redis db: '" + redisDatabase + "' redis password: '" + redisPassword +"'");
            poolFailCounter.inc();
            // rethrow and let things escalate
            throw e2;
        }
    }

    return (Jedis) Enhancer.create(Jedis.class, new MeasuringJedisHandler(resource));
}
 
Example 18
Project: cosmic   File: ComponentInstantiationPostProcessor.java   Source Code and License 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 19
Project: ximplementation-spring   File: CglibImplementeeBeanBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * Build CGLIB <i>implementee</i> bean.
 * 
 * @param implementation
 * @param implementorBeanFactory
 * @return
 */
protected Object doBuild(
		Implementation<?> implementation,
		ImplementorBeanFactory implementorBeanFactory)
{
	InvocationHandler invocationHandler = new CglibImplementeeInvocationHandler(
			implementation, implementorBeanFactory,
			implementeeMethodInvocationFactory);

	Enhancer enhancer = new Enhancer();
	enhancer.setInterfaces(new Class[] { CglibImplementee.class });
	enhancer.setSuperclass(implementation.getImplementee());
	enhancer.setCallback(invocationHandler);

	return enhancer.create();
}
 
Example 20
Project: microbule   File: CglibDynamicProxyStrategy.java   Source Code and License 6 votes vote down vote up
@Override
public <T> T createDynamicProxy(Class<T> type, Supplier<T> targetSupplier, String descriptionPattern, Object... descriptionParams) {
    final String description = String.format(descriptionPattern, descriptionParams);
    final Enhancer enhancer = new Enhancer();
    enhancer.setClassLoader(new DelegatingClassLoader(type.getClassLoader(), Enhancer.class.getClassLoader()));
    enhancer.setInterfaces(new Class[]{type});
    enhancer.setSuperclass(Object.class);
    enhancer.setCallbackFilter(FILTER);
    enhancer.setCallbacks(new Callback[]{
            (Dispatcher) targetSupplier::get,
            (MethodInterceptor) (proxy, method, params, methodProxy) -> proxy == params[0],
            (MethodInterceptor) (proxy, method, params, methodProxy) -> System.identityHashCode(proxy),
            (MethodInterceptor) (proxy, method, params, methodProxy) -> description
    });
    return type.cast(enhancer.create());
}
 
Example 21
Project: singular-server   File: SingularTestRequestCycleListener.java   Source Code and License 6 votes vote down vote up
private ServletWebRequest getSuperPoweredRequest(ServletWebRequest request, HttpServletRequest superPoweredMockRequest) {
    if (isSuperPowered(request)) {
        return request;
    }
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(SingularServletWebRequest.class);
    enhancer.setInterfaces(new Class[]{SuperPowered.class});
    enhancer.setCallback(new InvocationHandler() {
        @Override
        public Object invoke(Object o, Method method, Object[] objects)
                throws InvocationTargetException, IllegalAccessException {
            if ("getContainerRequest".equals(method.getName())) {
                return superPoweredMockRequest;
            }
            return method.invoke(request, objects);
        }
    });
    return (ServletWebRequest) enhancer.create();
}
 
Example 22
Project: navi   File: NaviDataServiceProxy.java   Source Code and License 6 votes vote down vote up
public NaviDataServiceProxy(IBaseDataService realService, Class<?> inter) {
    this.realService = realService;
    Class<?>[] inters = realService.getClass().getInterfaces();
    //直接实现目标的接口的情况下使用java原生动态代理,否则使用cglib
    if (find(inters, inter)) {
        this.proxyService = Proxy.newProxyInstance(
            realService.getClass().getClassLoader(), realService.getClass().getInterfaces(), this
        );
    } else {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.realService.getClass());
        // 回调方法
        enhancer.setCallback(this);
        // 创建代理对象
        this.proxyService = enhancer.create();
    }
}
 
Example 23
Project: cqrs4j   File: BaseAnnotationEventListenerBeanPostProcessorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testEventHandlerCallsRedirectToAdapter() {
    Object result1 = testSubject.postProcessBeforeInitialization(new AnnotatedEventListener(), "beanName");
    Object postProcessedBean = testSubject.postProcessAfterInitialization(result1, "beanName");

    assertTrue(Enhancer.isEnhanced(postProcessedBean.getClass()));
    assertTrue(postProcessedBean instanceof EventListener);
    assertTrue(postProcessedBean instanceof AnnotatedEventListener);

    EventListener eventListener = (EventListener) postProcessedBean;
    AnnotatedEventListener annotatedEventListener = (AnnotatedEventListener) postProcessedBean;
    eventListener.canHandle(StubDomainEvent.class);
    StubDomainEvent domainEvent = new StubDomainEvent();
    eventListener.handle(domainEvent);

    verify(mockAdapter).canHandle(StubDomainEvent.class);
    verify(mockAdapter).handle(domainEvent);
    reset(mockAdapter);
    annotatedEventListener.handleEvent(new StubDomainEvent());
    verifyZeroInteractions(mockAdapter);
}
 
Example 24
Project: flux   File: TaskInterceptor.java   Source Code and License 6 votes vote down vote up
private Object createProxyReturnObject(final Method method) {
    if (method.getReturnType() == void.class) {
        return null;
    }
    /* The method is expected to return _something_, so we create a proxy for it */
    final String eventName = localContext.generateEventName(new Event() {
        @Override
        public String name() {
            return method.getReturnType().getName();
        }
    });
    final ReturnGivenStringCallback eventNameCallback = new ReturnGivenStringCallback(eventName);
    final ReturnGivenStringCallback realClassNameCallback = new ReturnGivenStringCallback(method.getReturnType().getName());
    final ProxyEventCallbackFilter filter = new ProxyEventCallbackFilter(method.getReturnType(),new Class[]{Intercepted.class}) {
        @Override
        protected ReturnGivenStringCallback getRealClassName() {
            return realClassNameCallback;
        }

        @Override
        public ReturnGivenStringCallback getNameCallback() {
            return eventNameCallback;
        }
    };
    return Enhancer.create(method.getReturnType(), new Class[]{Intercepted.class}, filter, filter.getCallbacks());
}
 
Example 25
Project: bd-codes   File: FXmain.java   Source Code and License 6 votes vote down vote up
public static void aopBase() {
	// 设计模式-代理模式(静态代理)
	System.out.println("设计模式-代理模式");
	ISubject sub = new SubjectImpProxy(new SubjectImp());
	sub.request();

	// JDK-动态代理,通过Proxy生成代理类
	System.out.println("\nJDK-动态代理");
	// Proxy:提供用于创建动态代理类和实例的静态方法,它还是由这些方法创建的所有动态代理类的超类。
	sub = (ISubject) Proxy.newProxyInstance(
	// 指定Classloader
			FXmain.class.getClassLoader(),
			// 指定要生成代理的接口,等同于 ISubject.class.getInterfaces()
			new Class[] { ISubject.class },
			// 初始化动态代理类,实现InvocationHandler接口的实现类
			new RequestInvocationHandler(new SubjectImp()));
	sub.request();

	// cglib-动态字节码生成
	System.out.println("\ncglib-动态字节码生成");
	Enhancer hancer = new Enhancer();
	hancer.setSuperclass(Requestable.class);
	hancer.setCallback(new RequestCallback());
	Requestable req = (Requestable) hancer.create();
	req.request();
}
 
Example 26
Project: ymate-platform-v2   File: PropertyStateSupport.java   Source Code and License 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() {
            public Object intercept(Object targetObject, Method targetMethod, Object[] methodParams, MethodProxy methodProxy) throws Throwable {
                Object _result = methodProxy.invokeSuper(targetObject, methodParams);
                PropertyStateMeta _meta = __propertyStates.get(targetMethod.getName());
                if (_meta != null && ArrayUtils.isNotEmpty(methodParams) && !ObjectUtils.equals(_meta.getOriginalValue(), methodParams[0])) {
                    _meta.setNewValue(methodParams[0]);
                }
                return _result;
            }
        }));
    }
    return __bound;
}
 
Example 27
Project: salta   File: SimpleProxyScopeManager.java   Source Code and License 6 votes vote down vote up
@Override
public Supplier<Object> scope(Supplier<Object> supplier, Binding binding, CoreDependencyKey<?> requestedKey) {

    // create the proxy right away, such that it can be reused
    // afterwards
    Object proxy = Enhancer.create(requestedKey.getRawType(), new Dispatcher() {

        @Override
        public Object loadObject() throws Exception {
            Map<Binding, Object> scopedObjects = tryGetValueMap().orElseThrow(
                    () -> new RuntimeException("Cannot access " + requestedKey + " outside of scope " + scopeName));
            return scopedObjects.computeIfAbsent(binding, b -> supplier.get());
        }
    });

    return () -> proxy;
}
 
Example 28
Project: cacheonix-core   File: ProxyFactoryFactoryImpl.java   Source Code and License 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 29
Project: powermock   File: Log4jUserTest.java   Source Code and License 6 votes vote down vote up
@Test
public void assertThatLog4jMockPolicyWorks() throws Exception {
	final Log4jUser tested = createPartialMockAndInvokeDefaultConstructor(Log4jUser.class, "getMessage");
	final String otherMessage = "other message";
	final String firstMessage = "first message and ";

	expect(tested.getMessage()).andReturn(firstMessage);

	replayAll();

	final String actual = tested.mergeMessageWith(otherMessage);
	Class<? extends Logger> class1 = Whitebox.getInternalState(Log4jUserParent.class, Logger.class).getClass();
	assertTrue(Enhancer.isEnhanced(class1));

	verifyAll();

	assertEquals(firstMessage + otherMessage, actual);
}
 
Example 30
Project: currencycloud-java   File: CurrencyCloudClient.java   Source Code and License 6 votes vote down vote up
/**
 * @return A proxy object whose getters will return null for unchanged entity's properties
 * (and new values for changed properties), or the entity itself if the entity was not
 * enhanced for dirty checking.
 * @throws com.currencycloud.client.CurrencyCloudClient.NoChangeException if the entity was dirty-checked
 * but there were no changes.
 */
static <E extends Entity> E wrapIfDirty(E entity, Class<E> entityClass) throws NoChangeException {
    if (entity != null) {
        Map<String, Object> values = getDirtyProperties(entity);
        if (values != null) {
            if (values.isEmpty()) {
                throw new NoChangeException();
            }
            values = new HashMap<>(values);
            values.put("id", entity.getId());
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(entityClass);
            enhancer.setCallback(new ModifiedValueProvider(values));
            return (E) enhancer.create();
        }
    }
    return entity;
}
 
Example 31
Project: rof   File: AbstractClassProxyFactory.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T create(final Class<T> clazz) {
    checkNotNull(clazz, "clazz cannot be null");

    if (!isAbstract(clazz)) {
        return null;
    }

    checkIfSupported(clazz);

    final Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(clazz);
    enhancer.setCallback(handler);

    return (T) enhancer.create();
}
 
Example 32
Project: xstream   File: CglibCompatibilityTest.java   Source Code and License 6 votes vote down vote up
public void testSupportForClassBasedProxyWithAdditionalInterface()
    throws NullPointerException {
    final Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(HashMap.class);
    enhancer.setCallback(NoOp.INSTANCE);
    enhancer.setInterfaces(new Class[]{Runnable.class});
    final Map orig = (Map)enhancer.create();
    final String xml = ""
        + "<CGLIB-enhanced-proxy>\n"
        + "  <type>java.util.HashMap</type>\n"
        + "  <interfaces>\n"
        + "    <java-class>java.lang.Runnable</java-class>\n"
        + "  </interfaces>\n"
        + "  <hasFactory>true</hasFactory>\n"
        + "  <net.sf.cglib.proxy.NoOp_-1/>\n"
        + "</CGLIB-enhanced-proxy>";

    final Object serialized = assertBothWays(orig, xml);
    assertTrue(serialized instanceof HashMap);
    assertTrue(serialized instanceof Map);
    assertTrue(serialized instanceof Runnable);
}
 
Example 33
Project: xstream   File: CglibCompatibilityTest.java   Source Code and License 6 votes vote down vote up
public void testSupportsProxiesWithMultipleInterfaces() throws NullPointerException {
    final Enhancer enhancer = new Enhancer();
    enhancer.setCallback(NoOp.INSTANCE);
    enhancer.setInterfaces(new Class[]{Map.class, Runnable.class});
    final Map orig = (Map)enhancer.create();
    final String xml = ""
        + "<CGLIB-enhanced-proxy>\n"
        + "  <type>java.lang.Object</type>\n"
        + "  <interfaces>\n"
        + "    <java-class>java.util.Map</java-class>\n"
        + "    <java-class>java.lang.Runnable</java-class>\n"
        + "  </interfaces>\n"
        + "  <hasFactory>true</hasFactory>\n"
        + "  <net.sf.cglib.proxy.NoOp_-1/>\n"
        + "</CGLIB-enhanced-proxy>";

    final Object serialized = assertBothWays(orig, xml);
    assertTrue(serialized instanceof Map);
    assertTrue(serialized instanceof Runnable);
}
 
Example 34
Project: xstream   File: CglibCompatibilityTest.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 35
Project: xstream   File: CglibCompatibilityTest.java   Source Code and License 6 votes vote down vote up
public void testSupportsSerialVersionUID()
    throws NullPointerException, NoSuchFieldException, IllegalAccessException {
    final Enhancer enhancer = new Enhancer();
    enhancer.setCallback(NoOp.INSTANCE);
    enhancer.setInterfaces(new Class[]{Runnable.class});
    enhancer.setSerialVersionUID(new Long(20060804L));
    final Runnable orig = (Runnable)enhancer.create();
    final String xml = ""
        + "<CGLIB-enhanced-proxy>\n"
        + "  <type>java.lang.Object</type>\n"
        + "  <interfaces>\n"
        + "    <java-class>java.lang.Runnable</java-class>\n"
        + "  </interfaces>\n"
        + "  <hasFactory>true</hasFactory>\n"
        + "  <net.sf.cglib.proxy.NoOp_-1/>\n"
        + "  <serialVersionUID>20060804</serialVersionUID>\n"
        + "</CGLIB-enhanced-proxy>";

    final Object serialized = assertBothWays(orig, xml);
    final Field field = serialized.getClass().getDeclaredField("serialVersionUID");
    field.setAccessible(true);
    assertEquals(20060804L, field.getLong(null));
}
 
Example 36
Project: xstream   File: CglibCompatibilityTest.java   Source Code and License 6 votes vote down vote up
public void testSupportsProxiesAsFieldMember() throws NullPointerException {
    ClassWithProxyMember expected = new ClassWithProxyMember();
    xstream.alias("with-proxy", ClassWithProxyMember.class);
    final Enhancer enhancer = new Enhancer();
    enhancer.setCallback(NoOp.INSTANCE);
    enhancer.setInterfaces(new Class[]{Map.class, Runnable.class});
    final Map orig = (Map)enhancer.create();
    expected.runnable = (Runnable)orig;
    expected.map = orig;
    final String xml = ""
        + "<with-proxy>\n"
        + "  <runnable class=\"CGLIB-enhanced-proxy\">\n"
        + "    <type>java.lang.Object</type>\n"
        + "    <interfaces>\n"
        + "      <java-class>java.util.Map</java-class>\n"
        + "      <java-class>java.lang.Runnable</java-class>\n"
        + "    </interfaces>\n"
        + "    <hasFactory>true</hasFactory>\n"
        + "    <net.sf.cglib.proxy.NoOp_-1/>\n"
        + "  </runnable>\n"
        + "  <map class=\"CGLIB-enhanced-proxy\" reference=\"../runnable\"/>\n"
        + "</with-proxy>";

    final Object serialized = assertBothWays(expected, xml);
    assertTrue(serialized instanceof ClassWithProxyMember);
}
 
Example 37
Project: xstream   File: CglibCompatibilityTest.java   Source Code and License 6 votes vote down vote up
public void testProxyTypeCanBeAliased() throws MalformedURLException {
    final Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(HashMap.class);
    enhancer.setCallback(new DelegatingHandler(new HashMap()));
    final Map orig = (Map)enhancer.create();
    orig.put("URL", new URL("http://xstream.codehaus.org"));
    xstream.aliasType("cglib", Map.class);
    final String expected = ""
        + "<cglib>\n"
        + "  <type>java.util.HashMap</type>\n"
        + "  <interfaces/>\n"
        + "  <hasFactory>true</hasFactory>\n"
        + "  <com.thoughtworks.acceptance.CglibCompatibilityTest_-DelegatingHandler>\n"
        + "    <delegate class=\"map\">\n"
        + "      <entry>\n"
        + "        <string>URL</string>\n"
        + "        <url>http://xstream.codehaus.org</url>\n"
        + "      </entry>\n"
        + "    </delegate>\n"
        + "  </com.thoughtworks.acceptance.CglibCompatibilityTest_-DelegatingHandler>\n"
        + "</cglib>";
    assertEquals(expected, xstream.toXML(orig));
}
 
Example 38
Project: tddl5   File: NodeDelegate.java   Source Code and License 6 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 39
Project: sterodium-rmi   File: RemoteObjectProxyFactory.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 40
Project: NeoEMF   File: PersistentEObjectAdapter.java   Source Code and License 6 votes vote down vote up
/**
   * Create an adapter for the given {@code object} in a specific {@code type}.
   *
   * @param adaptableObject the object to adapt
   * @param adapterType     the class in which the object must be adapted
   *
   * @return an adapted object in the given {@code type}
   */
  private static Object createAdapter(Object adaptableObject, Class<?> adapterType) {
      /*
       * Compute the interfaces that the proxy has to implement
 * These are the current interfaces + PersistentEObject
 */
      List<Class<?>> interfaces = ClassUtils.getAllInterfaces(adaptableObject.getClass());
      interfaces.add(PersistentEObject.class);

      // Create the proxy
      Enhancer proxy = new Enhancer();

/*
       * Use the ClassLoader of the type, otherwise it will cause OSGi troubles (like project trying to
 * create an PersistentEObject while it does not have a dependency to NeoEMF core)
 */
      proxy.setClassLoader(adapterType.getClassLoader());
      proxy.setSuperclass(adaptableObject.getClass());
      proxy.setInterfaces(interfaces.toArray(new Class[interfaces.size()]));
      proxy.setCallback(new PersistentEObjectProxyHandler());

      return proxy.create();
  }
 
Example 41
Project: croquet   File: EntityManagerProxyFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a proxy object that will write-replace with a wrapper around the {@link EntityManager}.
 * @param factory a factory to generate EntityManagers.
 * @return the proxied instance.
 */
static EntityManager createProxy(final HibernateEntityManagerFactory factory) {
    final EntityManagerInterceptor handler = new EntityManagerInterceptor(factory);

    final Enhancer e = new Enhancer();

    // make sure we're Serializable and have a write replace method
    e.setInterfaces(new Class[] { EntityManager.class, Serializable.class, IWriteReplace.class });
    e.setSuperclass(Object.class);
    e.setCallback(handler);
    e.setNamingPolicy(new DefaultNamingPolicy() {
        @Override
        public String getClassName(final String prefix,
                                   final String source,
                                   final Object key,
                                   final Predicate names) {
            return super.getClassName("CROQUET_ENTITY_MANAGER_PROXY_" + prefix, source, key, names);
        }
    });

    LOG.trace("Created proxy for an EntityManager");

    return (EntityManager)e.create();
}
 
Example 42
Project: croquet   File: QueryRunnerProxyFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a proxy object that will write-replace with a wrapper around a {@link QueryRunner}.
 * @param dataSourceFactory a provider to generate DataSources.
 * @return the proxied instance.
 */
public static QueryRunner createProxy(final DataSourceFactory dataSourceFactory) {
    final QueryRunnerInterceptor handler = new QueryRunnerInterceptor(dataSourceFactory);

    final Enhancer e = new Enhancer();

    // make sure we're Serializable and have a write replace method
    e.setInterfaces(new Class[] { Serializable.class, IWriteReplace.class });
    e.setSuperclass(QueryRunner.class);
    e.setCallback(handler);
    e.setNamingPolicy(new DefaultNamingPolicy() {
        @Override
        public String getClassName(final String prefix,
                                   final String source,
                                   final Object key,
                                   final Predicate names) {
            return super.getClassName("PROXY_" + prefix, source, key, names);
        }
    });

    LOG.trace("Created proxy for an EntityManager");

    return (QueryRunner)e.create();

}
 
Example 43
Project: guzz   File: EnchancerTest.java   Source Code and License 6 votes vote down vote up
public void testMe(){
	Article a = (Article) Enhancer.create(Article.class, new Class[]{DynamicUpdatable.class}, null, new Callback[]{
		new MethodInterceptor(){
			public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
				proxy.invokeSuper(obj, args) ;
				
				System.out.println(method.getName()) ;
				
				return null;
			}
		}
	}) ;
	
	assertTrue(a instanceof DynamicUpdatable) ;
	a.getContent() ;
}
 
Example 44
Project: transloader   File: Triangulate.java   Source Code and License 6 votes vote down vote up
public static Object anyInstanceOf(Class type) {
	try {
		if (type == null || type == void.class) return null;
		if (type.isArray()) return anyArrayOf(type.getComponentType());
		Object triangulatedInstance = tryToTriangulateFromThisClass(type);
		if (triangulatedInstance != null) return triangulatedInstance;
		if (type.isInterface())
			return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] {type},
					new TriangulatingInvocationHandler());
		if (Modifier.isAbstract(type.getModifiers()))
			return Enhancer.create(type, new TriangulatingInvocationHandler());
		return ObjenesisHelper.newInstance(type);
	} catch (Exception e) {
		throw new NestableRuntimeException(e);
	}
}
 
Example 45
Project: jcloudscale   File: CgLibUtil.java   Source Code and License 6 votes vote down vote up
public static Object replaceCOWithProxy(Class<?> className, Object[] parameters, Class<?>[] parameterTypes) throws Throwable {
	
	Enhancer enhancer = new Enhancer();
	enhancer.setCallback(new JCloudScaleCloudObjectHandler());
	enhancer.setSuperclass(className);
	
	try {
		if(parameters != null && parameterTypes.length > 0)
			return enhancer.create(parameterTypes, parameters);
		else
			return enhancer.create();
	} catch(CodeGenerationException e) {
		// we are not particularly interested in the CodeGenerationException, more in what caused it
		if(e.getCause() != null)
			throw e.getCause();
		else
			throw e;
	}
}
 
Example 46
Project: magenta   File: DataSpecificationFieldHandler.java   Source Code and License 6 votes vote down vote up
@Override
public boolean handle(Field f, Object target, Supplier<Fixture<S>> current) {

  if (f.isAnnotationPresent(org.magenta.annotations.InjectDataSpecification.class)) {

    InjectDataSpecification annotation = f.getAnnotation(org.magenta.annotations.InjectDataSpecification.class);

    if (DataSpecification.class.isAssignableFrom(f.getType())) {

      Enhancer e = new Enhancer();
      e.setSuperclass(current.get().getSpecification().getClass());
      e.setCallback(interceptor(supplierOfDataSpecification(current)));
      e.setInterceptDuringConstruction(false);

      DataSpecification proxy = (DataSpecification)e.create();


      FieldInjectorUtils.injectInto(target, f, proxy);
      return true;
    }else{
      throw new IllegalStateException("Invalid field : Annotation ["+InjectDataSpecification.class.getName()+"] is present on field named ["+f.getName()+"] on the class ["+f.getDeclaringClass().getCanonicalName()+"],\n but this field type should implement ["+DataSpecification.class.getName()+"] instead of ["+f.getType()+"].");
    }
  } else {
    return false;
  }
}
 
Example 47
Project: thread-weaver   File: MethodRecorder.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 48
Project: guice-old   File: ProxyFactory.java   Source Code and License 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 49
Project: cloudstack   File: ComponentInstantiationPostProcessor.java   Source Code and License 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 50
Project: byte-buddy   File: ClassByImplementationBenchmark.java   Source Code and License 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}) {
        @Override
        protected Object getCallback(Method method) {
            if (method.getDeclaringClass() == baseClass) {
                return new FixedValue() {
                    @Override
                    public Object loadObject() throws Exception {
                        return null;
                    }
                };
            } else {
                return NoOp.INSTANCE;
            }
        }
    };
    enhancer.setCallbackFilter(callbackHelper);
    enhancer.setCallbacks(callbackHelper.getCallbacks());
    return (ExampleInterface) enhancer.create();
}
 
Example 51
Project: furnace   File: ClassLoaderAdapterProxiedTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testAdaptProxiedType() throws Exception
{
   ClassLoader loader = MockService.class.getClassLoader();
   final MockService internal = new MockService();

   MockService delegate = (MockService) Enhancer.create(MockService.class, new LazyLoader()
   {
      @Override
      public Object loadObject() throws Exception
      {
         return internal;
      }
   });

   MockService adapter = ClassLoaderAdapterBuilder.callingLoader(loader).delegateLoader(loader)
            .enhance(delegate, MockService.class);

   Assert.assertNotEquals(internal.getResult(), adapter.getResult());
   Assert.assertEquals(internal.getResult().getValue(), adapter.getResult().getValue());
}
 
Example 52
Project: furnace   File: ClassLoaderAdapterProxiedTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testAdaptProxiedResult() throws Exception
{
   ClassLoader loader = MockService.class.getClassLoader();
   final MockService internal = new MockService();

   MockService delegate = (MockService) Enhancer.create(MockService.class, new LazyLoader()
   {
      @Override
      public Object loadObject() throws Exception
      {
         return internal;
      }
   });

   MockService adapter = ClassLoaderAdapterBuilder.callingLoader(loader).delegateLoader(loader)
            .enhance(delegate, MockService.class);

   Assert.assertNotEquals(internal.getResult(), adapter.getResultEnhanced());
}
 
Example 53
Project: furnace   File: ClassLoaderAdapterProxiedTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testAdaptProxiedResultReturnTypeObject() throws Exception
{
   ClassLoader loader = MockService.class.getClassLoader();
   final MockService internal = new MockService();

   MockService delegate = (MockService) Enhancer.create(MockService.class, new LazyLoader()
   {
      @Override
      public Object loadObject() throws Exception
      {
         return internal;
      }
   });

   MockService adapter = ClassLoaderAdapterBuilder.callingLoader(loader).delegateLoader(loader)
            .enhance(delegate, MockService.class);

   Assert.assertNotEquals(internal.getResult(), adapter.getResultEnhancedReturnTypeObject());
}
 
Example 54
Project: furnace   File: ClassLoaderAdapterProxiedTest.java   Source Code and License 6 votes vote down vote up
@Test(expected = ClassCastException.class)
public void testCannotAdaptFinalResultReturnType() throws Exception
{
   ClassLoader loader = MockService.class.getClassLoader();
   final MockService internal = new MockService();

   MockService delegate = (MockService) Enhancer.create(MockService.class, new LazyLoader()
   {
      @Override
      public Object loadObject() throws Exception
      {
         return internal;
      }
   });

   MockService adapter = ClassLoaderAdapterBuilder.callingLoader(loader).delegateLoader(loader)
            .enhance(delegate, MockService.class);
   adapter.getResultFinalReturnType();
}
 
Example 55
Project: furnace   File: ClassLoaderAdapterProxiedTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCanAdaptFinalResultReturnTypeObject() throws Exception
{
   ClassLoader loader = MockService.class.getClassLoader();
   final MockService internal = new MockService();

   MockService delegate = (MockService) Enhancer.create(MockService.class, new LazyLoader()
   {
      @Override
      public Object loadObject() throws Exception
      {
         return internal;
      }
   });

   MockService adapter = ClassLoaderAdapterBuilder.callingLoader(loader).delegateLoader(loader)
            .enhance(delegate, MockService.class);

   Assert.assertNotEquals(internal.getResultFinalReturnTypeObject(), adapter.getResultFinalReturnTypeObject());
   Assert.assertEquals(((Result) internal.getResultFinalReturnTypeObject()).getValue(),
            ((Result) adapter.getResultFinalReturnTypeObject()).getValue());
}
 
Example 56
Project: furnace   File: ClassLoaderAdapterProxiedTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testAdaptFinalResult() throws Exception
{
   ClassLoader loader = MockService.class.getClassLoader();
   final MockService internal = new MockService();

   MockService delegate = (MockService) Enhancer.create(MockService.class, new LazyLoader()
   {
      @Override
      public Object loadObject() throws Exception
      {
         return internal;
      }
   });

   MockService adapter = ClassLoaderAdapterBuilder.callingLoader(loader).delegateLoader(loader)
            .enhance(delegate, MockService.class);

   Assert.assertNotEquals(internal.getResultInterfaceFinalImpl(), adapter.getResultInterfaceFinalImpl());
   Object unwrapped = Proxies.unwrap(adapter);
   Assert.assertNotSame(adapter, unwrapped);
}
 
Example 57
Project: furnace   File: ClassLoaderAdapterProxiedTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testNullValuesAsMethodParameters() throws Exception
{
   ClassLoader loader = MockService.class.getClassLoader();
   final MockService internal = new MockService();

   MockService delegate = (MockService) Enhancer.create(MockService.class, new LazyLoader()
   {
      @Override
      public Object loadObject() throws Exception
      {
         return internal;
      }
   });
   MockService adapter = ClassLoaderAdapterBuilder.callingLoader(loader).delegateLoader(loader)
            .enhance(delegate, MockService.class);
   Assert.assertNull(internal.echo(null));
   Assert.assertNull(adapter.echo(null));
}
 
Example 58
Project: furnace   File: ClassLoaderAdapterProxiedTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testShouldNotProxyJavaNioPath() throws Exception
{
   ClassLoader loader = JavaIOFactory.class.getClassLoader();
   final JavaIOFactory internal = new JavaIOFactory();

   JavaIOFactory delegate = (JavaIOFactory) Enhancer.create(JavaIOFactory.class, new LazyLoader()
   {
      @Override
      public Object loadObject() throws Exception
      {
         return internal;
      }
   });
   JavaIOFactory adapter = ClassLoaderAdapterBuilder.callingLoader(loader).delegateLoader(loader)
            .enhance(delegate, JavaIOFactory.class);
   Path path = adapter.getPath();
   Assert.assertFalse(Proxies.isProxyType(path.getClass()));
}
 
Example 59
Project: furnace   File: ClassLoaderAdapterProxiedTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testShouldNotProxyJavaUtilLogging() throws Exception {
   ClassLoader loader = JavaUtilLoggingFactory.class.getClassLoader();
   final JavaUtilLoggingFactory internal = new JavaUtilLoggingFactory();

   JavaUtilLoggingFactory delegate = (JavaUtilLoggingFactory) Enhancer.create(JavaUtilLoggingFactory.class, new LazyLoader() {
      @Override
      public Object loadObject() throws Exception {
         return internal;
      }
   });

   JavaUtilLoggingFactory adapter = ClassLoaderAdapterBuilder.callingLoader(loader).delegateLoader(loader)
           .enhance(delegate, JavaUtilLoggingFactory.class);
   LogRecord logRecord = adapter.getLogRecord();
   Assert.assertFalse(Proxies.isProxyType(logRecord.getClass()));
   Assert.assertFalse(Proxies.isProxyType(logRecord.getLevel().getClass()));
}
 
Example 60
Project: google-guice   File: ProxyFactory.java   Source Code and License 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();
  }
}