Java Code Examples for org.springframework.aop.framework.ProxyFactory

The following examples show how to use org.springframework.aop.framework.ProxyFactory. These examples are extracted from open source projects. 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
protected Object createProxy(Object target, List<Advisor> advisors, Class<?>... interfaces) {
	ProxyFactory pf = new ProxyFactory(target);
	if (interfaces.length > 1 || interfaces[0].isInterface()) {
		pf.setInterfaces(interfaces);
	}
	else {
		pf.setProxyTargetClass(true);
	}

	// Required everywhere we use AspectJ proxies
	pf.addAdvice(ExposeInvocationInterceptor.INSTANCE);
	pf.addAdvisors(advisors);

	pf.setExposeProxy(true);
	return pf.getProxy();
}
 
Example 2
private void testAdvice(Advisor advisor, LogUserAdvice logAdvice, TestService target, String message,
		boolean proxyTargetClass) throws Exception {

	logAdvice.reset();

	ProxyFactory factory = new ProxyFactory(target);
	factory.setProxyTargetClass(proxyTargetClass);
	factory.addAdvisor(advisor);
	TestService bean = (TestService) factory.getProxy();

	assertEquals(0, logAdvice.getCountThrows());
	try {
		bean.sayHello();
		fail("Expected exception");
	}
	catch (TestException ex) {
		assertEquals(message, ex.getMessage());
	}
	assertEquals(1, logAdvice.getCountThrows());
}
 
Example 3
public void testMethodACL() throws Exception
{
    runAs("andy");

    Object o = new ClassWithMethods();
    Method method = o.getClass().getMethod("testMethod", new Class[] {});

    AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.addAdvisor(advisorAdapterRegistry.wrap(new Interceptor("ACL_METHOD.andy", "ACL_METHOD.BANANA")));
    proxyFactory.setTargetSource(new SingletonTargetSource(o));
    Object proxy = proxyFactory.getProxy();

    method.invoke(proxy, new Object[] {});
}
 
Example 4
@Test
public void testSerializable() throws Exception {
	DerivedTestBean tb = new DerivedTestBean();
	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setInterfaces(ITestBean.class);
	ConcurrencyThrottleInterceptor cti = new ConcurrencyThrottleInterceptor();
	proxyFactory.addAdvice(cti);
	proxyFactory.setTarget(tb);
	ITestBean proxy = (ITestBean) proxyFactory.getProxy();
	proxy.getAge();

	ITestBean serializedProxy = (ITestBean) SerializationTestUtils.serializeAndDeserialize(proxy);
	Advised advised = (Advised) serializedProxy;
	ConcurrencyThrottleInterceptor serializedCti =
			(ConcurrencyThrottleInterceptor) advised.getAdvisors()[0].getAdvice();
	assertEquals(cti.getConcurrencyLimit(), serializedCti.getConcurrencyLimit());
	serializedProxy.getAge();
}
 
Example 5
Source Project: spring4-understanding   Source File: GroovyAspectTests.java    License: Apache License 2.0 6 votes vote down vote up
private void testAdvice(Advisor advisor, LogUserAdvice logAdvice, TestService target, String message,
		boolean proxyTargetClass) throws Exception {

	logAdvice.reset();

	ProxyFactory factory = new ProxyFactory(target);
	factory.setProxyTargetClass(proxyTargetClass);
	factory.addAdvisor(advisor);
	TestService bean = (TestService) factory.getProxy();

	assertEquals(0, logAdvice.getCountThrows());
	try {
		bean.sayHello();
		fail("Expected exception");
	}
	catch (TestException ex) {
		assertEquals(message, ex.getMessage());
	}
	assertEquals(1, logAdvice.getCountThrows());
}
 
Example 6
Source Project: ignite   Source File: GridifySpringEnhancer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Enhances the object on load.
 *
 * @param <T> Type of the object to enhance.
 * @param obj Object to augment/enhance.
 * @return Enhanced object.
 */
@SuppressWarnings({"unchecked"})
public static <T> T enhance(T obj) {
    ProxyFactory proxyFac = new ProxyFactory(obj);

    proxyFac.addAdvice(dfltAsp);
    proxyFac.addAdvice(setToValAsp);
    proxyFac.addAdvice(setToSetAsp);

    while (proxyFac.getAdvisors().length > 0)
        proxyFac.removeAdvisor(0);

    proxyFac.addAdvisor(new DefaultPointcutAdvisor(
        new GridifySpringPointcut(GridifySpringPointcut.GridifySpringPointcutType.DFLT), dfltAsp));
    proxyFac.addAdvisor(new DefaultPointcutAdvisor(
        new GridifySpringPointcut(GridifySpringPointcut.GridifySpringPointcutType.SET_TO_VALUE), setToValAsp));
    proxyFac.addAdvisor(new DefaultPointcutAdvisor(
        new GridifySpringPointcut(GridifySpringPointcut.GridifySpringPointcutType.SET_TO_SET), setToSetAsp));

    return (T)proxyFac.getProxy();
}
 
Example 7
public void testMethodACL2() throws Exception
{
    runAs("andy");

    Object o = new ClassWithMethods();
    Method method = o.getClass().getMethod("testMethod", new Class[] {});

    AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.addAdvisor(advisorAdapterRegistry.wrap(new Interceptor("ACL_METHOD.BANANA", "ACL_METHOD."
            + PermissionService.ALL_AUTHORITIES)));
    proxyFactory.setTargetSource(new SingletonTargetSource(o));
    Object proxy = proxyFactory.getProxy();

    method.invoke(proxy, new Object[] {});
}
 
Example 8
@Test
public void testIntroductionInterceptorWithSuperInterface() throws Exception {
	TestBean raw = new TestBean();
	assertTrue(! (raw instanceof TimeStamped));
	ProxyFactory factory = new ProxyFactory(raw);

	TimeStamped ts = mock(SubTimeStamped.class);
	long timestamp = 111L;
	given(ts.getTimeStamp()).willReturn(timestamp);

	factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts), TimeStamped.class));

	TimeStamped tsp = (TimeStamped) factory.getProxy();
	assertTrue(!(tsp instanceof SubTimeStamped));
	assertTrue(tsp.getTimeStamp() == timestamp);
}
 
Example 9
@SuppressWarnings("serial")
@Test
public void testIntroductionInterceptorDoesntReplaceToString() throws Exception {
	TestBean raw = new TestBean();
	assertTrue(! (raw instanceof TimeStamped));
	ProxyFactory factory = new ProxyFactory(raw);

	TimeStamped ts = new SerializableTimeStamped(0);

	factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts) {
		@Override
		public String toString() {
			throw new UnsupportedOperationException("Shouldn't be invoked");
		}
	}));

	TimeStamped tsp = (TimeStamped) factory.getProxy();
	assertEquals(0, tsp.getTimeStamp());

	assertEquals(raw.toString(), tsp.toString());
}
 
Example 10
Source Project: spring-analysis-note   Source File: MBeanProxyFactoryBean.java    License: MIT License 6 votes vote down vote up
/**
 * Checks that the {@code proxyInterface} has been specified and then
 * generates the proxy for the target MBean.
 */
@Override
public void afterPropertiesSet() throws MBeanServerNotFoundException, MBeanInfoRetrievalException {
	super.afterPropertiesSet();

	if (this.proxyInterface == null) {
		this.proxyInterface = getManagementInterface();
		if (this.proxyInterface == null) {
			throw new IllegalArgumentException("Property 'proxyInterface' or 'managementInterface' is required");
		}
	}
	else {
		if (getManagementInterface() == null) {
			setManagementInterface(this.proxyInterface);
		}
	}
	this.mbeanProxy = new ProxyFactory(this.proxyInterface, this).getProxy(this.beanClassLoader);
}
 
Example 11
public void testBasicAllowChildAssociationRef2() throws Exception
{
    runAs("andy");

    Object o = new ClassWithMethods();
    Method method = o.getClass().getMethod("echoChildAssocRef", new Class[] { ChildAssociationRef.class });

    AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.addAdvisor(advisorAdapterRegistry.wrap(new Interceptor("AFTER_ACL_PARENT.sys:base.Read")));
    proxyFactory.setTargetSource(new SingletonTargetSource(o));
    Object proxy = proxyFactory.getProxy();

    permissionService.setPermission(new SimplePermissionEntry(rootNodeRef, getPermission(PermissionService.READ), "andy", AccessStatus.ALLOWED));

    Object answer = method.invoke(proxy, new Object[] { nodeService.getPrimaryParent(rootNodeRef) });
    assertEquals(answer, nodeService.getPrimaryParent(rootNodeRef));

    answer = method.invoke(proxy, new Object[] { nodeService.getPrimaryParent(systemNodeRef) });
    assertEquals(answer, nodeService.getPrimaryParent(systemNodeRef));
}
 
Example 12
public void testBasicAllowNode() throws Exception
{
    runAs("andy");

    Object o = new ClassWithMethods();
    Method method = o.getClass().getMethod("echoNodeRef", new Class[] { NodeRef.class });

    AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.addAdvisor(advisorAdapterRegistry.wrap(new Interceptor("AFTER_ACL_NODE.sys:base.Read")));
    proxyFactory.setTargetSource(new SingletonTargetSource(o));
    Object proxy = proxyFactory.getProxy();

    permissionService.setPermission(new SimplePermissionEntry(rootNodeRef, getPermission(PermissionService.READ), "andy", AccessStatus.ALLOWED));

    Object answer = method.invoke(proxy, new Object[] { rootNodeRef });
    assertEquals(answer, rootNodeRef);

}
 
Example 13
public void testMethodACL4() throws Exception
{
    runAs("andy");

    Object o = new ClassWithMethods();
    Method method = o.getClass().getMethod("testMethod", new Class[] {});

    AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.addAdvisor(advisorAdapterRegistry.wrap(new Interceptor("ACL_METHOD.woof", "ACL_METHOD.BOO")));
    proxyFactory.setTargetSource(new SingletonTargetSource(o));
    Object proxy = proxyFactory.getProxy();

    try
    {
        method.invoke(proxy, new Object[] {});
    }
    catch (InvocationTargetException e)
    {

    }
}
 
Example 14
@Test
public void testCanGetStaticPartFromJoinPoint() {
	final Object raw = new TestBean();
	ProxyFactory pf = new ProxyFactory(raw);
	pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR);
	pf.addAdvice(new MethodBeforeAdvice() {
		@Override
		public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
			StaticPart staticPart = AbstractAspectJAdvice.currentJoinPoint().getStaticPart();
			assertEquals("Same static part must be returned on subsequent requests", staticPart, AbstractAspectJAdvice.currentJoinPoint().getStaticPart());
			assertEquals(ProceedingJoinPoint.METHOD_EXECUTION, staticPart.getKind());
			assertSame(AbstractAspectJAdvice.currentJoinPoint().getSignature(), staticPart.getSignature());
			assertEquals(AbstractAspectJAdvice.currentJoinPoint().getSourceLocation(), staticPart.getSourceLocation());
		}
	});
	ITestBean itb = (ITestBean) pf.getProxy();
	// Any call will do
	itb.getAge();
}
 
Example 15
Source Project: spring-analysis-note   Source File: GroovyAspectTests.java    License: MIT License 6 votes vote down vote up
private void testAdvice(Advisor advisor, LogUserAdvice logAdvice, TestService target, String message,
		boolean proxyTargetClass) throws Exception {

	logAdvice.reset();

	ProxyFactory factory = new ProxyFactory(target);
	factory.setProxyTargetClass(proxyTargetClass);
	factory.addAdvisor(advisor);
	TestService bean = (TestService) factory.getProxy();

	assertEquals(0, logAdvice.getCountThrows());
	try {
		bean.sayHello();
		fail("Expected exception");
	}
	catch (TestException ex) {
		assertEquals(message, ex.getMessage());
	}
	assertEquals(1, logAdvice.getCountThrows());
}
 
Example 16
@Test
@SuppressWarnings("unchecked")
public void proxiedListenersMixedWithTargetListeners() {
	MyOrderedListener1 listener1 = new MyOrderedListener1();
	MyOrderedListener2 listener2 = new MyOrderedListener2(listener1);
	ApplicationListener<ApplicationEvent> proxy1 = (ApplicationListener<ApplicationEvent>) new ProxyFactory(listener1).getProxy();
	ApplicationListener<ApplicationEvent> proxy2 = (ApplicationListener<ApplicationEvent>) new ProxyFactory(listener2).getProxy();

	SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster();
	smc.addApplicationListener(listener1);
	smc.addApplicationListener(listener2);
	smc.addApplicationListener(proxy1);
	smc.addApplicationListener(proxy2);

	smc.multicastEvent(new MyEvent(this));
	smc.multicastEvent(new MyOtherEvent(this));
	assertEquals(2, listener1.seenEvents.size());
}
 
Example 17
Source Project: java-technology-stack   Source File: MBeanProxyFactoryBean.java    License: MIT License 6 votes vote down vote up
/**
 * Checks that the {@code proxyInterface} has been specified and then
 * generates the proxy for the target MBean.
 */
@Override
public void afterPropertiesSet() throws MBeanServerNotFoundException, MBeanInfoRetrievalException {
	super.afterPropertiesSet();

	if (this.proxyInterface == null) {
		this.proxyInterface = getManagementInterface();
		if (this.proxyInterface == null) {
			throw new IllegalArgumentException("Property 'proxyInterface' or 'managementInterface' is required");
		}
	}
	else {
		if (getManagementInterface() == null) {
			setManagementInterface(this.proxyInterface);
		}
	}
	this.mbeanProxy = new ProxyFactory(this.proxyInterface, this).getProxy(this.beanClassLoader);
}
 
Example 18
/**
 * Test the important case where the invocation is on a proxied interface method
 * but the attribute is defined on the target class.
 */
@Test
public void transactionAttributeDeclaredOnCglibClassMethod() throws Exception {
	Method classMethod = ITestBean1.class.getMethod("getAge");
	TestBean1 tb = new TestBean1();
	ProxyFactory pf = new ProxyFactory(tb);
	pf.setProxyTargetClass(true);
	Object proxy = pf.getProxy();

	AnnotationTransactionAttributeSource atas = new AnnotationTransactionAttributeSource();
	TransactionAttribute actual = atas.getTransactionAttribute(classMethod, proxy.getClass());

	RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute();
	rbta.getRollbackRules().add(new RollbackRuleAttribute(Exception.class));
	assertEquals(rbta.getRollbackRules(), ((RuleBasedTransactionAttribute) actual).getRollbackRules());
}
 
Example 19
@Test
public void serializable() throws Exception {
	TestBean1 tb = new TestBean1();
	CallCountingTransactionManager ptm = new CallCountingTransactionManager();
	AnnotationTransactionAttributeSource tas = new AnnotationTransactionAttributeSource();
	TransactionInterceptor ti = new TransactionInterceptor(ptm, tas);

	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setInterfaces(new Class[] {ITestBean.class});
	proxyFactory.addAdvice(ti);
	proxyFactory.setTarget(tb);
	ITestBean proxy = (ITestBean) proxyFactory.getProxy();
	proxy.getAge();
	assertEquals(1, ptm.commits);

	ITestBean serializedProxy = (ITestBean) SerializationTestUtils.serializeAndDeserialize(proxy);
	serializedProxy.getAge();
	Advised advised = (Advised) serializedProxy;
	TransactionInterceptor serializedTi = (TransactionInterceptor) advised.getAdvisors()[0].getAdvice();
	CallCountingTransactionManager serializedPtm =
			(CallCountingTransactionManager) serializedTi.getTransactionManager();
	assertEquals(2, serializedPtm.commits);
}
 
Example 20
@Test
public void testInvokesMethodOnEjbInstance() throws Exception {
	Object retVal = new Object();
	LocalInterfaceWithBusinessMethods ejb = mock(LocalInterfaceWithBusinessMethods.class);
	given(ejb.targetMethod()).willReturn(retVal);

	String jndiName= "foobar";
	Context mockContext = mockContext(jndiName, ejb);

	LocalSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);

	ProxyFactory pf = new ProxyFactory(new Class<?>[] { BusinessMethods.class });
	pf.addAdvice(si);
	BusinessMethods target = (BusinessMethods) pf.getProxy();

	assertTrue(target.targetMethod() == retVal);

	verify(mockContext).close();
	verify(ejb).remove();
}
 
Example 21
@SuppressWarnings("serial")
@Test
public void testIntroductionInterceptorDoesntReplaceToString() throws Exception {
	TestBean raw = new TestBean();
	assertTrue(! (raw instanceof TimeStamped));
	ProxyFactory factory = new ProxyFactory(raw);

	TimeStamped ts = new SerializableTimeStamped(0);

	factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts) {
		@Override
		public String toString() {
			throw new UnsupportedOperationException("Shouldn't be invoked");
		}
	}));

	TimeStamped tsp = (TimeStamped) factory.getProxy();
	assertEquals(0, tsp.getTimeStamp());

	assertEquals(raw.toString(), tsp.toString());
}
 
Example 22
/**
 * Helper method to create a {@link PermissionCheckedValue} from an existing <code>Object</code>.
 * 
 * @param object        the <code>Object</code> to proxy
 * @return                  a <code>Object</code> of the same type but including the
 *                          {@link PermissionCheckedValue} interface
 */
@SuppressWarnings("unchecked")
public static final <T extends Object> T create(T object)
{
    // Create the mixin
    DelegatingIntroductionInterceptor mixin = new PermissionCheckedValueMixin();
    // Create the advisor
    IntroductionAdvisor advisor = new DefaultIntroductionAdvisor(mixin, PermissionCheckedValue.class);
    // Proxy
    ProxyFactory pf = new ProxyFactory(object);
    pf.addAdvisor(advisor);
    Object proxiedObject = pf.getProxy();
    
    // Done
    return (T) proxiedObject;
}
 
Example 23
@Test
public void testIntroductionInterceptorWithSuperInterface() throws Exception {
	TestBean raw = new TestBean();
	assertTrue(! (raw instanceof TimeStamped));
	ProxyFactory factory = new ProxyFactory(raw);

	TimeStamped ts = mock(SubTimeStamped.class);
	long timestamp = 111L;
	given(ts.getTimeStamp()).willReturn(timestamp);

	factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts), TimeStamped.class));

	TimeStamped tsp = (TimeStamped) factory.getProxy();
	assertTrue(!(tsp instanceof SubTimeStamped));
	assertTrue(tsp.getTimeStamp() == timestamp);
}
 
Example 24
@Test
public void classLevelOnly() {
	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setTarget(new TestClassLevelOnly());
	proxyFactory.addAdvice(this.ti);

	TestClassLevelOnly proxy = (TestClassLevelOnly) proxyFactory.getProxy();

	proxy.doSomething();
	assertGetTransactionAndCommitCount(1);

	proxy.doSomethingElse();
	assertGetTransactionAndCommitCount(2);

	proxy.doSomething();
	assertGetTransactionAndCommitCount(3);

	proxy.doSomethingElse();
	assertGetTransactionAndCommitCount(4);
}
 
Example 25
@Test
public void withSingleMethodOverride() {
	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setTarget(new TestWithSingleMethodOverride());
	proxyFactory.addAdvice(this.ti);

	TestWithSingleMethodOverride proxy = (TestWithSingleMethodOverride) proxyFactory.getProxy();

	proxy.doSomething();
	assertGetTransactionAndCommitCount(1);

	proxy.doSomethingElse();
	assertGetTransactionAndCommitCount(2);

	proxy.doSomethingCompletelyElse();
	assertGetTransactionAndCommitCount(3);

	proxy.doSomething();
	assertGetTransactionAndCommitCount(4);
}
 
Example 26
Source Project: java-technology-stack   Source File: AsyncExecutionTests.java    License: MIT License 6 votes vote down vote up
public DynamicAsyncInterfaceBean() {
	ProxyFactory pf = new ProxyFactory(new HashMap<>());
	DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(new MethodInterceptor() {
		@Override
		public Object invoke(MethodInvocation invocation) throws Throwable {
			assertTrue(!Thread.currentThread().getName().equals(originalThreadName));
			if (Future.class.equals(invocation.getMethod().getReturnType())) {
				return new AsyncResult<>(invocation.getArguments()[0].toString());
			}
			return null;
		}
	});
	advisor.addInterface(AsyncInterface.class);
	pf.addAdvisor(advisor);
	this.proxy = (AsyncInterface) pf.getProxy();
}
 
Example 27
@Test
public void withMultiMethodOverride() {
	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setTarget(new TestWithMultiMethodOverride());
	proxyFactory.addAdvice(this.ti);

	TestWithMultiMethodOverride proxy = (TestWithMultiMethodOverride) proxyFactory.getProxy();

	proxy.doSomething();
	assertGetTransactionAndCommitCount(1);

	proxy.doSomethingElse();
	assertGetTransactionAndCommitCount(2);

	proxy.doSomethingCompletelyElse();
	assertGetTransactionAndCommitCount(3);

	proxy.doSomething();
	assertGetTransactionAndCommitCount(4);
}
 
Example 28
@Test
public void testWithIntroduction() {
	String beanName = "foo";
	TestBean target = new RequiresBeanNameBoundTestBean(beanName);
	ProxyFactory pf = new ProxyFactory(target);
	pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR);
	pf.addAdvisor(ExposeBeanNameAdvisors.createAdvisorIntroducingNamedBean(beanName));
	ITestBean proxy = (ITestBean) pf.getProxy();

	assertTrue("Introduction was made", proxy instanceof NamedBean);
	// Requires binding
	proxy.getAge();

	NamedBean nb = (NamedBean) proxy;
	assertEquals("Name returned correctly", beanName, nb.getBeanName());
}
 
Example 29
@Override
public void afterPropertiesSet() {
	ProxyFactory proxyFactory = new ProxyFactory(getServiceInterfaces());
	proxyFactory.addAdvice(this);
	LOG.debug("Http proxying service " + getServiceConfiguration());
	this.serviceProxy = proxyFactory.getProxy();
}
 
Example 30
@Override
protected Object advised(Object target, ReactiveTransactionManager ptm, TransactionAttributeSource[] tas) {
	TransactionInterceptor ti = new TransactionInterceptor();
	ti.setTransactionManager(ptm);
	ti.setTransactionAttributeSources(tas);

	ProxyFactory pf = new ProxyFactory(target);
	pf.addAdvice(0, ti);
	return pf.getProxy();
}