Java Code Examples for org.springframework.aop.framework.ProxyFactory#getProxy()

The following examples show how to use org.springframework.aop.framework.ProxyFactory#getProxy() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AnnotationTransactionInterceptorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void withCommitOnCheckedException() {
	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setTarget(new TestWithExceptions());
	proxyFactory.addAdvice(this.ti);

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

	try {
		proxy.doSomethingElseWithCheckedException();
		fail("Should throw Exception");
	}
	catch (Exception ex) {
		assertGetTransactionAndCommitCount(1);
	}
}
 
Example 2
Source File: MethodInvocationProceedingJoinPointTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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, 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 3
Source File: LocalSlsbInvokerInterceptorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private void testException(Exception expected) throws Exception {
	LocalInterfaceWithBusinessMethods ejb = mock(LocalInterfaceWithBusinessMethods.class);
	given(ejb.targetMethod()).willThrow(expected);

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

	LocalSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);

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

	try {
		target.targetMethod();
		fail("Should have thrown exception");
	}
	catch (Exception thrown) {
		assertTrue(thrown == expected);
	}

	verify(mockContext).close();
}
 
Example 4
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-11225
public void resolveArgumentTypeVariableWithNonGenericConverter() throws Exception {
	Method method = MyParameterizedController.class.getMethod("handleDto", Identifiable.class);
	HandlerMethod handlerMethod = new HandlerMethod(new MySimpleParameterizedController(), method);
	MethodParameter methodParam = handlerMethod.getMethodParameters()[0];

	String content = "{\"name\" : \"Jad\"}";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	HttpMessageConverter<Object> target = new MappingJackson2HttpMessageConverter();
	HttpMessageConverter<?> proxy = ProxyFactory.getProxy(HttpMessageConverter.class, new SingletonTargetSource(target));
	converters.add(proxy);
	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);

	SimpleBean result = (SimpleBean) processor.resolveArgument(methodParam, container, request, factory);

	assertNotNull(result);
	assertEquals("Jad", result.getName());
}
 
Example 5
Source File: AnnotationTransactionAttributeSourceTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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(ITestBean1.class);
	proxyFactory.addAdvice(ti);
	proxyFactory.setTarget(tb);
	ITestBean1 proxy = (ITestBean1) proxyFactory.getProxy();
	proxy.getAge();
	assertEquals(1, ptm.commits);

	ITestBean1 serializedProxy = (ITestBean1) 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 6
Source File: RemoteExporter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Get a proxy for the given service object, implementing the specified
 * service interface.
 * <p>Used to export a proxy that does not expose any internals but just
 * a specific interface intended for remote access. Furthermore, a
 * {@link RemoteInvocationTraceInterceptor} will be registered (by default).
 * @return the proxy
 * @see #setServiceInterface
 * @see #setRegisterTraceInterceptor
 * @see RemoteInvocationTraceInterceptor
 */
protected Object getProxyForService() {
	checkService();
	checkServiceInterface();

	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.addInterface(getServiceInterface());

	if (this.registerTraceInterceptor != null ? this.registerTraceInterceptor : this.interceptors == null) {
		proxyFactory.addAdvice(new RemoteInvocationTraceInterceptor(getExporterName()));
	}
	if (this.interceptors != null) {
		AdvisorAdapterRegistry adapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();
		for (Object interceptor : this.interceptors) {
			proxyFactory.addAdvisor(adapterRegistry.wrap(interceptor));
		}
	}

	proxyFactory.setTarget(getService());
	proxyFactory.setOpaque(true);

	return proxyFactory.getProxy(getBeanClassLoader());
}
 
Example 7
Source File: DelegatingIntroductionInterceptorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializableDelegatingIntroductionInterceptorSerializable() throws Exception {
	SerializablePerson serializableTarget = new SerializablePerson();
	String name = "Tony";
	serializableTarget.setName("Tony");

	ProxyFactory factory = new ProxyFactory(serializableTarget);
	factory.addInterface(Person.class);
	long time = 1000;
	TimeStamped ts = new SerializableTimeStamped(time);

	factory.addAdvisor(new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts)));
	factory.addAdvice(new SerializableNopInterceptor());

	Person p = (Person) factory.getProxy();

	assertEquals(name, p.getName());
	assertEquals(time, ((TimeStamped) p).getTimeStamp());

	Person p1 = (Person) SerializationTestUtils.serializeAndDeserialize(p);
	assertEquals(name, p1.getName());
	assertEquals(time, ((TimeStamped) p1).getTimeStamp());
}
 
Example 8
Source File: ACLEntryAfterInvocationTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testBasicDenyInvalidNodeRef() 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("Value passed out must be valid", rootNodeRef, answer);

    NodeRef invalidNodeRef = new NodeRef("workspace://SpacesStore/noodle");
    answer = method.invoke(proxy, new Object[] { invalidNodeRef });
    method.invoke(proxy, new Object[] { invalidNodeRef });
    assertEquals("Value passed out must be equal", invalidNodeRef, answer);
}
 
Example 9
Source File: KStreamBoundElementFactory.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
private KStream createProxyForKStream(String name) {
	KStreamWrapperHandler wrapper = new KStreamWrapperHandler();
	ProxyFactory proxyFactory = new ProxyFactory(KStreamWrapper.class, KStream.class);
	proxyFactory.addAdvice(wrapper);

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

	// Add the binding properties to the catalogue for later retrieval during further
	// binding steps downstream.
	BindingProperties bindingProperties = this.bindingServiceProperties
			.getBindingProperties(name);
	this.kafkaStreamsBindingInformationCatalogue.registerBindingProperties(proxy,
			bindingProperties);
	return proxy;
}
 
Example 10
Source File: TransactionInterceptorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected Object advised(Object target, PlatformTransactionManager ptm, TransactionAttributeSource[] tas) throws Exception {
	TransactionInterceptor ti = new TransactionInterceptor();
	ti.setTransactionManager(ptm);
	ti.setTransactionAttributeSources(tas);

	ProxyFactory pf = new ProxyFactory(target);
	pf.addAdvice(0, ti);
	return pf.getProxy();
}
 
Example 11
Source File: PersistenceExceptionTranslationAdvisorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
protected RepositoryInterface createProxy(RepositoryInterfaceImpl target) {
	MapPersistenceExceptionTranslator mpet = new MapPersistenceExceptionTranslator();
	mpet.addTranslation(persistenceException1, new InvalidDataAccessApiUsageException("", persistenceException1));
	ProxyFactory pf = new ProxyFactory(target);
	pf.addInterface(RepositoryInterface.class);
	addPersistenceExceptionTranslation(pf, mpet);
	return (RepositoryInterface) pf.getProxy();
}
 
Example 12
Source File: DelegatingIntroductionInterceptorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testAutomaticInterfaceRecognitionInDelegate() throws Exception {
	final long t = 1001L;
	class Tester implements TimeStamped, ITester {
		@Override
		public void foo() throws Exception {
		}
		@Override
		public long getTimeStamp() {
			return t;
		}
	}

	DelegatingIntroductionInterceptor ii = new DelegatingIntroductionInterceptor(new Tester());

	TestBean target = new TestBean();

	ProxyFactory pf = new ProxyFactory(target);
	pf.addAdvisor(0, new DefaultIntroductionAdvisor(ii));

	//assertTrue(Arrays.binarySearch(pf.getProxiedInterfaces(), TimeStamped.class) != -1);
	TimeStamped ts = (TimeStamped) pf.getProxy();

	assertTrue(ts.getTimeStamp() == t);
	((ITester) ts).foo();

	((ITestBean) ts).getAge();
}
 
Example 13
Source File: AspectJExpressionPointcutTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private TestBean getAdvisedProxy(String pointcutExpression, CallCountingInterceptor interceptor) {
	TestBean target = new TestBean();

	Pointcut pointcut = getPointcut(pointcutExpression);

	DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
	advisor.setAdvice(interceptor);
	advisor.setPointcut(pointcut);

	ProxyFactory pf = new ProxyFactory();
	pf.setTarget(target);
	pf.addAdvisor(advisor);

	return (TestBean) pf.getProxy();
}
 
Example 14
Source File: DelegatingIntroductionInterceptorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testIntroductionInterceptorWithDelegation() throws Exception {
	TestBean raw = new TestBean();
	assertTrue(! (raw instanceof TimeStamped));
	ProxyFactory factory = new ProxyFactory(raw);

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

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

	TimeStamped tsp = (TimeStamped) factory.getProxy();
	assertTrue(tsp.getTimeStamp() == timestamp);
}
 
Example 15
Source File: ACLEntryVoterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testDenyParentAssocNode() throws Exception
{
    runAs("andy");

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

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

    AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.addAdvisor(advisorAdapterRegistry.wrap(new Interceptor("ACL_PARENT.0.sys:base.Read")));

    proxyFactory.setTargetSource(new SingletonTargetSource(o));

    Object proxy = proxyFactory.getProxy();

    try
    {
        method.invoke(proxy, new Object[] { nodeService.getPrimaryParent(systemNodeRef) });
        assertNotNull(null);
    }
    catch (InvocationTargetException e)
    {

    }
}
 
Example 16
Source File: AopTestUtilsTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private Foo jdkProxy(Foo foo) {
	ProxyFactory pf = new ProxyFactory();
	pf.setTarget(foo);
	pf.addInterface(Foo.class);
	Foo proxy = (Foo) pf.getProxy();
	assertTrue("Proxy is a JDK dynamic proxy", AopUtils.isJdkDynamicProxy(proxy));
	assertThat(proxy, instanceOf(Foo.class));
	return proxy;
}
 
Example 17
Source File: ACLEntryVoterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testMultiChildAssocRefMethodsArg0() throws Exception
{
    runAs("andy");

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

    AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();

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

    method.invoke(proxy, new Object[] { null, null, null, null });

    try
    {
        method.invoke(proxy, new Object[] { nodeService.getPrimaryParent(rootNodeRef), null, null, null });
        assertNotNull(null);
    }
    catch (InvocationTargetException e)
    {

    }

    permissionService.setPermission(new SimplePermissionEntry(rootNodeRef, getPermission(PermissionService.READ),
            "andy", AccessStatus.ALLOWED));
    method.invoke(proxy, new Object[] { nodeService.getPrimaryParent(rootNodeRef), null, null, null });
}
 
Example 18
Source File: TransactionInterceptorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected Object advised(Object target, PlatformTransactionManager ptm, TransactionAttributeSource[] tas) throws Exception {
	TransactionInterceptor ti = new TransactionInterceptor();
	ti.setTransactionManager(ptm);
	ti.setTransactionAttributeSources(tas);

	ProxyFactory pf = new ProxyFactory(target);
	pf.addAdvice(0, ti);
	return pf.getProxy();
}
 
Example 19
Source File: QuickPerfProxyBeanPostProcessor.java    From quickperf with Apache License 2.0 5 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
    if (bean instanceof DataSource && !isProxyDataSourceBean(bean)) {
        final ProxyFactory factory = new ProxyFactory(bean);
        factory.setProxyTargetClass(true);
        factory.addAdvice(new ProxyDataSourceInterceptor((DataSource) bean));
        return factory.getProxy();
    }
    return bean;
}
 
Example 20
Source File: ACLEntryVoterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testAllowChildAssocNode() throws Exception
{
    runAs("andy");

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

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

    AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.addAdvisor(advisorAdapterRegistry.wrap(new Interceptor("ACL_NODE.0.sys:base.Read")));

    proxyFactory.setTargetSource(new SingletonTargetSource(o));

    Object proxy = proxyFactory.getProxy();

    method.invoke(proxy, new Object[] { nodeService.getPrimaryParent(systemNodeRef) });

}