001
014
015 package com.liferay.portal.service;
016
017 import com.liferay.portal.kernel.service.ServiceContext;
018 import com.liferay.portal.kernel.service.ServiceContextThreadLocal;
019 import com.liferay.portal.spring.aop.ChainableMethodAdvice;
020
021 import java.lang.reflect.Method;
022
023 import org.aopalliance.intercept.MethodInvocation;
024
025
028 public class ServiceContextAdvice extends ChainableMethodAdvice {
029
030 @Override
031 public Object invoke(MethodInvocation methodInvocation) throws Throwable {
032 if (!hasServiceContextParameter(methodInvocation.getMethod())) {
033 serviceBeanAopCacheManager.removeMethodInterceptor(
034 methodInvocation, this);
035 }
036
037 boolean pushedServiceContext = pushServiceContext(methodInvocation);
038
039 try {
040 return methodInvocation.proceed();
041 }
042 finally {
043 if (pushedServiceContext) {
044 ServiceContextThreadLocal.popServiceContext();
045 }
046 }
047 }
048
049 protected boolean hasServiceContextParameter(Method method) {
050 Class<?>[] parameterTypes = method.getParameterTypes();
051
052 for (int i = parameterTypes.length - 1; i >= 0; i--) {
053 if (ServiceContext.class.isAssignableFrom(parameterTypes[i])) {
054 return true;
055 }
056 }
057
058 return false;
059 }
060
061 protected boolean pushServiceContext(MethodInvocation methodInvocation) {
062 Object[] arguments = methodInvocation.getArguments();
063
064 if (arguments == null) {
065 return false;
066 }
067
068 for (int i = arguments.length - 1; i >= 0; i--) {
069 if (arguments[i] instanceof ServiceContext) {
070 ServiceContext serviceContext = (ServiceContext)arguments[i];
071
072 ServiceContextThreadLocal.pushServiceContext(serviceContext);
073
074 return true;
075 }
076 }
077
078 return false;
079 }
080
081 }