org.springframework.context.event.test.TestEvent#org.springframework.aop.framework.ProxyFactory源码实例Demo

下面列出了org.springframework.context.event.test.TestEvent#org.springframework.aop.framework.ProxyFactory 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

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();
}
 
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());
}
 
源代码3 项目: alfresco-repository   文件: ACLEntryVoterTest.java
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[] {});
}
 
@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();
}
 
源代码5 项目: spring4-understanding   文件: GroovyAspectTests.java
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());
}
 
源代码6 项目: ignite   文件: GridifySpringEnhancer.java
/**
 * 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();
}
 
源代码7 项目: alfresco-repository   文件: ACLEntryVoterTest.java
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[] {});
}
 
@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);
}
 
@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());
}
 
/**
 * 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);
}
 
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));
}
 
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);

}
 
源代码13 项目: alfresco-repository   文件: ACLEntryVoterTest.java
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)
    {

    }
}
 
@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();
}
 
源代码15 项目: spring-analysis-note   文件: GroovyAspectTests.java
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());
}
 
@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());
}
 
/**
 * 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);
}
 
/**
 * 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());
}
 
@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);
}
 
@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();
}
 
@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());
}
 
/**
 * 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;
}
 
@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);
}
 
@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);
}
 
@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);
}
 
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();
}
 
@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);
}
 
@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());
}
 
源代码29 项目: rice   文件: KSBHttpInvokerProxyFactoryBean.java
@Override
public void afterPropertiesSet() {
	ProxyFactory proxyFactory = new ProxyFactory(getServiceInterfaces());
	proxyFactory.addAdvice(this);
	LOG.debug("Http proxying service " + getServiceConfiguration());
	this.serviceProxy = proxyFactory.getProxy();
}
 
@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();
}