org.aopalliance.intercept.MethodInterceptor Java Examples

The following examples show how to use org.aopalliance.intercept.MethodInterceptor. 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: DefaultAdvisorAdapterRegistry.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public Advisor wrap(Object adviceObject) throws UnknownAdviceTypeException {
	if (adviceObject instanceof Advisor) {
		return (Advisor) adviceObject;
	}
	if (!(adviceObject instanceof Advice)) {
		throw new UnknownAdviceTypeException(adviceObject);
	}
	Advice advice = (Advice) adviceObject;
	if (advice instanceof MethodInterceptor) {
		// So well-known it doesn't even need an adapter.
		return new DefaultPointcutAdvisor(advice);
	}
	for (AdvisorAdapter adapter : this.adapters) {
		// Check that it is supported.
		if (adapter.supportsAdvice(advice)) {
			return new DefaultPointcutAdvisor(advice);
		}
	}
	throw new UnknownAdviceTypeException(advice);
}
 
Example #2
Source File: MethodLogAdvisor.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
/**
 * AOP切点
 * @author Frodez
 * @date 2019-05-10
 */
@Override
public Advice getAdvice() {
	return (MethodInterceptor) invocation -> {
		Method method = invocation.getMethod();
		String name = ReflectUtil.fullName(method);
		if (method.getParameterCount() != 0) {
			Parameter[] parameters = method.getParameters();
			Object[] args = invocation.getArguments();
			Map<String, Object> paramMap = new HashMap<>(parameters.length);
			for (int i = 0; i < parameters.length; ++i) {
				paramMap.put(parameters[i].getName(), args[i]);
			}
			log.info("{} 请求参数:{}", name, JSONUtil.string(paramMap));
		} else {
			log.info("{} 本方法无入参", name);
		}
		Object result = invocation.proceed();
		if (method.getReturnType() != Void.class) {
			log.info("{} 返回值:{}", name, JSONUtil.string(result));
		} else {
			log.info("{} 本方法返回值类型为void", name);
		}
		return result;
	};
}
 
Example #3
Source File: DefaultAdvisorAdapterRegistry.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
	List<MethodInterceptor> interceptors = new ArrayList<>(3);
	Advice advice = advisor.getAdvice();
	if (advice instanceof MethodInterceptor) {
		interceptors.add((MethodInterceptor) advice);
	}
	for (AdvisorAdapter adapter : this.adapters) {
		if (adapter.supportsAdvice(advice)) {
			interceptors.add(adapter.getInterceptor(advisor));
		}
	}
	if (interceptors.isEmpty()) {
		throw new UnknownAdviceTypeException(advisor.getAdvice());
	}
	return interceptors.toArray(new MethodInterceptor[0]);
}
 
Example #4
Source File: AsyncAnnotationBeanPostProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void invokedAsynchronouslyOnProxyTarget() {
	StaticApplicationContext context = new StaticApplicationContext();
	context.registerBeanDefinition("postProcessor", new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class));
	TestBean tb = new TestBean();
	ProxyFactory pf = new ProxyFactory(ITestBean.class,
			(MethodInterceptor) invocation -> invocation.getMethod().invoke(tb, invocation.getArguments()));
	context.registerBean("target", ITestBean.class, () -> (ITestBean) pf.getProxy());
	context.refresh();

	ITestBean testBean = context.getBean("target", ITestBean.class);
	testBean.test();
	Thread mainThread = Thread.currentThread();
	testBean.await(3000);
	Thread asyncThread = testBean.getThread();
	assertNotSame(mainThread, asyncThread);
	context.close();
}
 
Example #5
Source File: SubsystemProxyFactory.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Instantiates a new managed subsystem proxy factory.
 */
public SubsystemProxyFactory()
{
    addAdvisor(new DefaultPointcutAdvisor(new MethodInterceptor()
    {
        public Object invoke(MethodInvocation mi) throws Throwable
        {
            Method method = mi.getMethod();
            try
            {
                return method.invoke(locateBean(mi), mi.getArguments());
            }
            catch (InvocationTargetException e)
            {
                // Unwrap invocation target exceptions
                throw e.getTargetException();
            }
        }
    }));
}
 
Example #6
Source File: AsyncExecutionTests.java    From spring-analysis-note with 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 #7
Source File: AsyncExecutionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public DynamicAsyncMethodsInterfaceBean() {
	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(AsyncMethodsInterface.class);
	pf.addAdvisor(advisor);
	this.proxy = (AsyncMethodsInterface) pf.getProxy();
}
 
Example #8
Source File: BootifulBannersServiceApplication.java    From bootiful-banners with Apache License 2.0 6 votes vote down vote up
private Environment environmentForImage(int maxWidth, boolean invert) {
	Map<String, Object> specification = new HashMap<>();
	specification.put("banner.image.width", maxWidth);
	specification.put("banner.image.invert", invert);
	ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
	proxyFactoryBean.setInterfaces(Environment.class);
	proxyFactoryBean.addAdvice((MethodInterceptor) invocation -> {
		String containsProperty = "containsProperty";
		String getProperty = "getProperty";
		List<String> toHandle = Arrays.asList(containsProperty, getProperty);
		String methodName = invocation.getMethod().getName();
		if (toHandle.contains(methodName)) {
			String key = String.class.cast(invocation.getArguments()[0]);
			if (methodName.equals(containsProperty)) {
				return (specification.containsKey(key) || this.environment.containsProperty(key));
			}
			if (methodName.equals(getProperty)) {
				return specification.getOrDefault(key, this.environment.getProperty(key));
			}
		}
		return invocation.getMethod().invoke(this.environment, invocation.getArguments());
	});
	return Environment.class.cast(proxyFactoryBean.getObject());
}
 
Example #9
Source File: AsyncTimeoutAdvisor.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
/**
 * AOP切点
 * @author Frodez
 * @date 2019-05-10
 */
@Override
public Advice getAdvice() {
	/**
	 * 在一定时间段内拦截重复请求
	 * @param JoinPoint AOP切点
	 * @author Frodez
	 * @date 2018-12-21
	 */
	return (MethodInterceptor) invocation -> {
		HttpServletRequest request = MVCUtil.request();
		String name = ReflectUtil.fullName(invocation.getMethod());
		String key = KeyGenerator.servletKey(name, request);
		if (checker.check(key)) {
			log.info("重复请求:IP地址{}", ServletUtil.getAddr(request));
			return Result.repeatRequest().async();
		}
		checker.lock(key, timeoutCache.get(name));
		return invocation.proceed();
	};
}
 
Example #10
Source File: AsyncAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void invokedAsynchronouslyOnProxyTarget() {
	StaticApplicationContext context = new StaticApplicationContext();
	context.registerBeanDefinition("postProcessor", new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class));
	TestBean tb = new TestBean();
	ProxyFactory pf = new ProxyFactory(ITestBean.class,
			(MethodInterceptor) invocation -> invocation.getMethod().invoke(tb, invocation.getArguments()));
	context.registerBean("target", ITestBean.class, () -> (ITestBean) pf.getProxy());
	context.refresh();

	ITestBean testBean = context.getBean("target", ITestBean.class);
	testBean.test();
	Thread mainThread = Thread.currentThread();
	testBean.await(3000);
	Thread asyncThread = testBean.getThread();
	assertNotSame(mainThread, asyncThread);
	context.close();
}
 
Example #11
Source File: AsyncLimitUserAdvisor.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
/**
 * AOP切点
 * @author Frodez
 * @date 2019-05-10
 */
@Override
public Advice getAdvice() {
	/**
	 * 请求限流
	 * @param JoinPoint AOP切点
	 * @author Frodez
	 * @date 2018-12-21
	 */
	return (MethodInterceptor) invocation -> {
		Pair<RateLimiter, Long> pair = limitCache.get(ReflectUtil.fullName(invocation.getMethod()));
		if (!pair.getKey().tryAcquire(pair.getValue(), DefTime.UNIT)) {
			return Result.busy().async();
		}
		return invocation.proceed();
	};
}
 
Example #12
Source File: NullPrimitiveTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testNullPrimitiveWithJdkProxy() {

	class SimpleFoo implements Foo {
		@Override
		public int getValue() {
			return 100;
		}
	}

	SimpleFoo target = new SimpleFoo();
	ProxyFactory factory = new ProxyFactory(target);
	factory.addAdvice(new MethodInterceptor() {
		@Override
		public Object invoke(MethodInvocation invocation) throws Throwable {
			return null;
		}
	});

	Foo foo = (Foo) factory.getProxy();

	thrown.expect(AopInvocationException.class);
	thrown.expectMessage("Foo.getValue()");
	assertEquals(0, foo.getValue());
}
 
Example #13
Source File: AopAccessLoggerSupport.java    From hsweb-framework with Apache License 2.0 6 votes vote down vote up
public AopAccessLoggerSupport() {
    setAdvice((MethodInterceptor) methodInvocation -> {
        MethodInterceptorHolder methodInterceptorHolder = MethodInterceptorHolder.create(methodInvocation);
        AccessLoggerInfo info = createLogger(methodInterceptorHolder);
        Object response;
        try {
            eventPublisher.publishEvent(new AccessLoggerBeforeEvent(info));
            listeners.forEach(listener -> listener.onLogBefore(info));
            response = methodInvocation.proceed();
            info.setResponse(response);
        } catch (Throwable e) {
            info.setException(e);
            throw e;
        } finally {
            info.setResponseTime(System.currentTimeMillis());
            //触发监听
            eventPublisher.publishEvent(new AccessLoggerAfterEvent(info));
            listeners.forEach(listener -> listener.onLogger(info));
        }
        return response;
    });
}
 
Example #14
Source File: NullPrimitiveTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testNullPrimitiveWithJdkProxy() {

	class SimpleFoo implements Foo {
		@Override
		public int getValue() {
			return 100;
		}
	}

	SimpleFoo target = new SimpleFoo();
	ProxyFactory factory = new ProxyFactory(target);
	factory.addAdvice(new MethodInterceptor() {
		@Override
		public Object invoke(MethodInvocation invocation) throws Throwable {
			return null;
		}
	});

	Foo foo = (Foo) factory.getProxy();

	thrown.expect(AopInvocationException.class);
	thrown.expectMessage("Foo.getValue()");
	assertEquals(0, foo.getValue());
}
 
Example #15
Source File: JdkDynamicAopProxy.java    From toy-spring with Apache License 2.0 6 votes vote down vote up
/**
 * InvocationHandler 接口中的 invoke 方法具体实现,封装了具体的代理逻辑
 *
 * @param proxy
 * @param method
 * @param args
 * @return 代理方法或原方法的返回值
 * @throws Throwable
 */
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    MethodMatcher methodMatcher = advised.getMethodMatcher();

    // 使用方法匹配器 methodMatcher 测试 bean 中原始方法 method 是否符合匹配规则
    if (methodMatcher != null && methodMatcher.matchers(method, advised.getTargetSource().getTargetClass())) {

        // 获取 Advice。MethodInterceptor 的父接口继承了 Advice
        MethodInterceptor methodInterceptor = advised.getMethodInterceptor();

        // 将 bean 的原始 method 封装成 MethodInvocation 实现类对象,
        // 将生成的对象传给 Adivce 实现类对象,执行通知逻辑
        return methodInterceptor.invoke(
                new ReflectiveMethodInvocation(advised.getTargetSource().getTarget(), method, args));
    } else {
        // 当前 method 不符合匹配规则,直接调用 bean 中的原始 method
        return method.invoke(advised.getTargetSource().getTarget(), args);
    }
}
 
Example #16
Source File: DefaultAdvisorAdapterRegistry.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
	List<MethodInterceptor> interceptors = new ArrayList<>(3);
	Advice advice = advisor.getAdvice();
	if (advice instanceof MethodInterceptor) {
		interceptors.add((MethodInterceptor) advice);
	}
	for (AdvisorAdapter adapter : this.adapters) {
		if (adapter.supportsAdvice(advice)) {
			interceptors.add(adapter.getInterceptor(advisor));
		}
	}
	if (interceptors.isEmpty()) {
		throw new UnknownAdviceTypeException(advisor.getAdvice());
	}
	return interceptors.toArray(new MethodInterceptor[0]);
}
 
Example #17
Source File: ProcessScope.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
/**
 * creates a proxy that dispatches invocations to the currently bound {@link ProcessInstance}
 *
 * @return shareable {@link ProcessInstance}
 */
private Object createSharedProcessInstance()   {
	ProxyFactory proxyFactoryBean = new ProxyFactory(ProcessInstance.class, new MethodInterceptor() {
		public Object invoke(MethodInvocation methodInvocation) throws Throwable {
			String methodName = methodInvocation.getMethod().getName() ;

			logger.info("method invocation for " + methodName+ ".");
			if(methodName.equals("toString"))
				return "SharedProcessInstance";


			ProcessInstance processInstance = Context.getExecutionContext().getProcessInstance();
			Method method = methodInvocation.getMethod();
			Object[] args = methodInvocation.getArguments();
			Object result = method.invoke(processInstance, args);
			return result;
		}
	});
	return proxyFactoryBean.getProxy(this.classLoader);
}
 
Example #18
Source File: GuiceUtils.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
/**
 * Binds an exception trap on all interface methods of all classes bound against an interface.
 * Individual methods may opt out of trapping by annotating with {@link AllowUnchecked}.
 * Only void methods are allowed, any non-void interface methods must explicitly opt out.
 *
 * @param binder The binder to register an interceptor with.
 * @param wrapInterface Interface whose methods should be wrapped.
 * @throws IllegalArgumentException If any of the non-whitelisted interface methods are non-void.
 */
public static void bindExceptionTrap(Binder binder, Class<?> wrapInterface)
    throws IllegalArgumentException {

  Set<Method> disallowed = ImmutableSet.copyOf(Iterables.filter(
      ImmutableList.copyOf(wrapInterface.getMethods()),
      Predicates.and(Predicates.not(IS_WHITELISTED), Predicates.not(VOID_METHOD))));
  Preconditions.checkArgument(disallowed.isEmpty(),
      "Non-void methods must be explicitly whitelisted with @AllowUnchecked: %s", disallowed);

  Matcher<Method> matcher =
      Matchers.not(WHITELIST_MATCHER).and(interfaceMatcher(wrapInterface, false));
  binder.bindInterceptor(Matchers.subclassesOf(wrapInterface), matcher,
      new MethodInterceptor() {
        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
          try {
            return invocation.proceed();
          } catch (RuntimeException e) {
            LOG.warn("Trapped uncaught exception: " + e, e);
            return null;
          }
        }
      });
}
 
Example #19
Source File: AbstractAopProxyTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * @param context if true, want context
 */
private void testContext(final boolean context) throws Throwable {
	final String s = "foo";
	// Test return value
	MethodInterceptor mi = new MethodInterceptor() {
		@Override
		public Object invoke(MethodInvocation invocation) throws Throwable {
			if (!context) {
				assertNoInvocationContext();
			}
			else {
				assertNotNull("have context", ExposeInvocationInterceptor.currentInvocation());
			}
			return s;
		}
	};
	AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
	if (context) {
		pc.addAdvice(ExposeInvocationInterceptor.INSTANCE);
	}
	pc.addAdvice(mi);
	// Keep CGLIB happy
	if (requiresTarget()) {
		pc.setTarget(new TestBean());
	}
	AopProxy aop = createAopProxy(pc);

	assertNoInvocationContext();
	ITestBean tb = (ITestBean) aop.getProxy();
	assertNoInvocationContext();
	assertSame("correct return value", s, tb.getName());
}
 
Example #20
Source File: ProxyFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testInterceptorWithoutJoinpoint() {
	final TestBean target = new TestBean("tb");
	ITestBean proxy = ProxyFactory.getProxy(ITestBean.class, (MethodInterceptor) invocation -> {
		assertNull(invocation.getThis());
		return invocation.getMethod().invoke(target, invocation.getArguments());
	});
	assertEquals("tb", proxy.getName());
}
 
Example #21
Source File: ProcessScope.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
private Object createDirtyCheckingProxy(final String name, final Object scopedObject) throws Throwable {
	ProxyFactory proxyFactoryBean = new ProxyFactory(scopedObject);
	proxyFactoryBean.setProxyTargetClass(this.proxyTargetClass);
	proxyFactoryBean.addAdvice(new MethodInterceptor() {
		public Object invoke(MethodInvocation methodInvocation) throws Throwable {
			Object result = methodInvocation.proceed();
			persistVariable(name, scopedObject);
			return result;
		}
	});
	return proxyFactoryBean.getProxy(this.classLoader);
}
 
Example #22
Source File: GenericMessageEndpointFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Wrap each concrete endpoint instance with an AOP proxy,
 * exposing the message listener's interfaces as well as the
 * endpoint SPI through an AOP introduction.
 */
@Override
public MessageEndpoint createEndpoint(XAResource xaResource) throws UnavailableException {
	GenericMessageEndpoint endpoint = (GenericMessageEndpoint) super.createEndpoint(xaResource);
	ProxyFactory proxyFactory = new ProxyFactory(this.messageListener);
	DelegatingIntroductionInterceptor introduction = new DelegatingIntroductionInterceptor(endpoint);
	introduction.suppressInterface(MethodInterceptor.class);
	proxyFactory.addAdvice(introduction);
	return (MessageEndpoint) proxyFactory.getProxy();
}
 
Example #23
Source File: ProxyFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public PointcutForVoid() {
	setAdvice(new MethodInterceptor() {
		@Override
		public Object invoke(MethodInvocation invocation) throws Throwable {
			methodNames.add(invocation.getMethod().getName());
			return invocation.proceed();
		}
	});
	setPointcut(new DynamicMethodMatcherPointcut() {
		@Override
		public boolean matches(Method m, Class<?> targetClass, Object[] args) {
			return m.getReturnType() == Void.TYPE;
		}
	});
}
 
Example #24
Source File: JdkDynamicProxyTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testInterceptorIsInvokedWithNoTarget() {
	// Test return value
	final int age = 25;
	MethodInterceptor mi = (invocation -> age);

	AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
	pc.addAdvice(mi);
	AopProxy aop = createAopProxy(pc);

	ITestBean tb = (ITestBean) aop.getProxy();
	assertEquals("correct return value", age, tb.getAge());
}
 
Example #25
Source File: AbstractAopProxyTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testDeclaredException() throws Throwable {
	final Exception expectedException = new Exception();
	// Test return value
	MethodInterceptor mi = new MethodInterceptor() {
		@Override
		public Object invoke(MethodInvocation invocation) throws Throwable {
			throw expectedException;
		}
	};
	AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
	pc.addAdvice(ExposeInvocationInterceptor.INSTANCE);
	pc.addAdvice(mi);

	// We don't care about the object
	mockTargetSource.setTarget(new TestBean());
	pc.setTargetSource(mockTargetSource);
	AopProxy aop = createAopProxy(pc);

	try {
		ITestBean tb = (ITestBean) aop.getProxy();
		// Note: exception param below isn't used
		tb.exceptional(expectedException);
		fail("Should have thrown exception raised by interceptor");
	}
	catch (Exception thrown) {
		assertEquals("exception matches", expectedException, thrown);
	}
}
 
Example #26
Source File: AbstractAopProxyTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * An interceptor throws a checked exception not on the method signature.
 * For efficiency, we don't bother unifying java.lang.reflect and
 * org.springframework.cglib UndeclaredThrowableException
 */
@Test
public void testUndeclaredCheckedException() throws Throwable {
	final Exception unexpectedException = new Exception();
	// Test return value
	MethodInterceptor mi = new MethodInterceptor() {
		@Override
		public Object invoke(MethodInvocation invocation) throws Throwable {
			throw unexpectedException;
		}
	};
	AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
	pc.addAdvice(ExposeInvocationInterceptor.INSTANCE);
	pc.addAdvice(mi);

	// We don't care about the object
	pc.setTarget(new TestBean());
	AopProxy aop = createAopProxy(pc);
	ITestBean tb = (ITestBean) aop.getProxy();

	try {
		// Note: exception param below isn't used
		tb.getAge();
		fail("Should have wrapped exception raised by interceptor");
	}
	catch (UndeclaredThrowableException thrown) {
		assertEquals("exception matches", unexpectedException, thrown.getUndeclaredThrowable());
	}
	catch (Exception ex) {
		ex.printStackTrace();
		fail("Didn't expect exception: " + ex);
	}
}
 
Example #27
Source File: NativeQueryProxyFactoryImpl.java    From spring-native-query with MIT License 5 votes vote down vote up
@Override
public Object create(Class<? extends NativeQuery> classe) {
    ProxyFactory proxy = new ProxyFactory();
    proxy.setTarget(Mockito.mock(classe));
    proxy.setInterfaces(classe, NativeQuery.class);
    proxy.addAdvice((MethodInterceptor) invocation -> {
        if ("toString".equals(invocation.getMethod().getName())) {
            return "NativeQuery Implementation";
        }
        NativeQueryInfo info = NativeQueryCache.get(classe, invocation);
        return nativeQueryMethodInterceptor.executeQuery(info);
    });
    return proxy.getProxy(classe.getClassLoader());
}
 
Example #28
Source File: DefaultPollableMessageSource.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
public void setSource(MessageSource<?> source) {
	ProxyFactory pf = new ProxyFactory(source);
	class ReceiveAdvice implements MethodInterceptor {

		private final List<ChannelInterceptor> interceptors = new ArrayList<>();

		@Override
		public Object invoke(MethodInvocation invocation) throws Throwable {
			Object result = invocation.proceed();
			if (result instanceof Message) {
				Message<?> received = (Message<?>) result;
				for (ChannelInterceptor interceptor : this.interceptors) {
					received = interceptor.preSend(received, dummyChannel);
					if (received == null) {
						return null;
					}
				}
				return received;
			}
			return result;
		}

	}
	final ReceiveAdvice advice = new ReceiveAdvice();
	advice.interceptors.addAll(this.interceptors);
	NameMatchMethodPointcutAdvisor sourceAdvisor = new NameMatchMethodPointcutAdvisor(
			advice);
	sourceAdvisor.addMethodName("receive");
	pf.addAdvisor(sourceAdvisor);
	this.source = (MessageSource<?>) pf.getProxy();
}
 
Example #29
Source File: AbstractAopProxyTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * There are times when we want to call proceed() twice.
 * We can do this if we clone the invocation.
 */
@Test
public void testCloneInvocationToProceedThreeTimes() throws Throwable {
	TestBean tb = new TestBean();
	ProxyFactory pc = new ProxyFactory(tb);
	pc.addInterface(ITestBean.class);

	MethodInterceptor twoBirthdayInterceptor = new MethodInterceptor() {
		@Override
		public Object invoke(MethodInvocation mi) throws Throwable {
			// Clone the invocation to proceed three times
			// "The Moor's Last Sigh": this technology can cause premature aging
			MethodInvocation clone1 = ((ReflectiveMethodInvocation) mi).invocableClone();
			MethodInvocation clone2 = ((ReflectiveMethodInvocation) mi).invocableClone();
			clone1.proceed();
			clone2.proceed();
			return mi.proceed();
		}
	};
	@SuppressWarnings("serial")
	StaticMethodMatcherPointcutAdvisor advisor = new StaticMethodMatcherPointcutAdvisor(twoBirthdayInterceptor) {
		@Override
		public boolean matches(Method m, @Nullable Class<?> targetClass) {
			return "haveBirthday".equals(m.getName());
		}
	};
	pc.addAdvisor(advisor);
	ITestBean it = (ITestBean) createProxy(pc);

	final int age = 20;
	it.setAge(age);
	assertEquals(age, it.getAge());
	// Should return the age before the third, AOP-induced birthday
	assertEquals(age + 2, it.haveBirthday());
	// Return the final age produced by 3 birthdays
	assertEquals(age + 3, it.getAge());
}
 
Example #30
Source File: ValidationModule.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void configure() {
  final MethodInterceptor interceptor = new ValidationInterceptor();
  bindInterceptor(Matchers.any(), Matchers.annotatedWith(Validate.class), interceptor);
  requestInjection(interceptor);
  bind(ConstraintValidatorFactory.class).to(GuiceConstraintValidatorFactory.class);
}