Java Code Examples for org.aopalliance.intercept.MethodInvocation#getThis()

The following examples show how to use org.aopalliance.intercept.MethodInvocation#getThis() . 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: ApiBootDataSourceSwitchAnnotationInterceptor.java    From beihu-boot with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    try {
        Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
        Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
        Method userDeclaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
        // get class declared DataSourceSwitch annotation
        DataSourceSwitch dataSourceSwitch = targetClass.getDeclaredAnnotation(DataSourceSwitch.class);
        if (dataSourceSwitch == null) {
            // get declared DataSourceSwitch annotation
            dataSourceSwitch = userDeclaredMethod.getDeclaredAnnotation(DataSourceSwitch.class);
        }
        if (dataSourceSwitch != null) {
            // setting current thread use data source pool name
            DataSourceContextHolder.set(dataSourceSwitch.value());
        }
        return invocation.proceed();
    } finally {
        // remove current thread use datasource pool name
        DataSourceContextHolder.remove();
    }

}
 
Example 2
Source File: ApiBootRateLimiterMethodInterceptor.java    From api-boot with Apache License 2.0 6 votes vote down vote up
/**
 * Processing Current Limited Business Logic
 *
 * @param invocation method invocation
 * @return method result
 * @throws Throwable error instance
 */
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    try {
        Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
        Method executeMethod = invocation.getMethod();

        RateLimiter rateLimiter = AopTools.getMethodAnnotation(targetClass, executeMethod, RateLimiter.class);

        // request key
        String requestKey = formatRequestKey(targetClass, executeMethod);
        logger.debug("RateLimiter Request Key:{}", requestKey);
        boolean acquire = apiBootRateLimiter.tryAcquire(rateLimiter.QPS(), requestKey);
        if (acquire) {
            return invocation.proceed();
        }
    } catch (Exception e) {
        logger.error("Current Limiting Request Encountered Exception.", e);
        throw e;
    }
    // If an instance is created
    if (!ObjectUtils.isEmpty(overFlowRequest)) {
        return overFlowRequest.overflow(invocation.getArguments());
    }
    return null;
}
 
Example 3
Source File: ApiBootMessagePushSwitchAnnotationInterceptor.java    From api-boot with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    try {
        Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
        Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
        Method declaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

        MessagePushSwitch messagePushSwitch = declaredMethod.getDeclaredAnnotation(MessagePushSwitch.class);
        // set current thread message push config name
        MessagePushContextHolder.set(messagePushSwitch.value());
        return invocation.proceed();
    } finally {
        // remove current thread use message push config name
        MessagePushContextHolder.remove();
    }

}
 
Example 4
Source File: ThrowsAdviceInterceptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void invokeHandlerMethod(MethodInvocation mi, Throwable ex, Method method) throws Throwable {
	Object[] handlerArgs;
	if (method.getParameterCount() == 1) {
		handlerArgs = new Object[] {ex};
	}
	else {
		handlerArgs = new Object[] {mi.getMethod(), mi.getArguments(), mi.getThis(), ex};
	}
	try {
		method.invoke(this.throwsAdvice, handlerArgs);
	}
	catch (InvocationTargetException targetEx) {
		throw targetEx.getTargetException();
	}
}
 
Example 5
Source File: TransactionInterceptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
public Object invoke(MethodInvocation invocation) throws Throwable {
	// Work out the target class: may be {@code null}.
	// The TransactionAttributeSource should be passed the target class
	// as well as the method, which may be from an interface.
	// 注释 9.5 执行事务拦截器,完成整个事务的逻辑
	Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);

	// Adapt to TransactionAspectSupport's invokeWithinTransaction...
	return invokeWithinTransaction(invocation.getMethod(), targetClass, invocation::proceed);
}
 
Example 6
Source File: TransactionInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
	// Work out the target class: may be {@code null}.
	// The TransactionAttributeSource should be passed the target class
	// as well as the method, which may be from an interface.
	Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);

	// Adapt to TransactionAspectSupport's invokeWithinTransaction...
	return invokeWithinTransaction(invocation.getMethod(), targetClass, new InvocationCallback() {
		@Override
		public Object proceedWithInvocation() throws Throwable {
			return invocation.proceed();
		}
	});
}
 
Example 7
Source File: TransactionInterceptor.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public Participant buildParticipant(MethodInvocation invocation) {
	Object target = invocation.getThis();
	Class<?> targetClass = target.getClass();
	Method method = invocation.getMethod();
	Object[] arguments = invocation.getArguments();
	
	return ParticipantBuilder.build(null, targetClass, method, arguments);
}
 
Example 8
Source File: AbstractAspect.java    From act-platform with ISC License 5 votes vote down vote up
/**
 * Retrieve the service instance from which a method was invoked.
 *
 * @param invocation Invoked method
 * @return Service of invoked method
 */
Service getService(MethodInvocation invocation) {
  if (!(invocation.getThis() instanceof Service)) {
    throw new IllegalArgumentException("Invocation target is not a service implementation: " + invocation.getThis());
  }
  return (Service) invocation.getThis();
}
 
Example 9
Source File: TransactionInterceptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
public Object invoke(MethodInvocation invocation) throws Throwable {
	// Work out the target class: may be {@code null}.
	// The TransactionAttributeSource should be passed the target class
	// as well as the method, which may be from an interface.
	Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);

	// Adapt to TransactionAspectSupport's invokeWithinTransaction...
	return invokeWithinTransaction(invocation.getMethod(), targetClass, invocation::proceed);
}
 
Example 10
Source File: MethodLockInterceptor.java    From common-project with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    MethodLock annotation=null;
    String lockKey="";
    boolean lock=false;
    try {
        Method currentMethod = methodInvocation.getMethod();
        Object[] arguments = methodInvocation.getArguments();
        Object target = methodInvocation.getThis();
        annotation = currentMethod.getAnnotation(MethodLock.class);
        String[] paramterNames = getParamterNames(currentMethod);
        ExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression(annotation.key());
        EvaluationContext context = new StandardEvaluationContext();
        for(int i=0;i<arguments.length;i++){
            context.setVariable(paramterNames[i],arguments[i]);
        }
        String value = expression.getValue(context, String.class);
        String methodName=target.getClass().getName()+"."+currentMethod.getName();
        logger.info("method lock handle: "+methodName);
        lockKey=methodName+":"+value;
        long time = annotation.time();
        int attemptNum = annotation.attemptNum();
        TimeUnit timeUnit = annotation.timeUnit();
        lock = distributedLock.lock(lockKey,time, timeUnit,attemptNum);
        if (!lock){
            logger.info("方法名====>"+methodName+" 未获取到锁");
            throw new RuntimeException("获取方法锁失败");
        }
        return methodInvocation.proceed();
    }finally {
        if (annotation!=null&&annotation.autoUnLock()&&lock){
            distributedLock.unlock(lockKey);
        }
    }
}
 
Example 11
Source File: AlfrescoCmisServiceInterceptor.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable
{
	String methodName = invocation.getMethod().getName();
	Object[] args = invocation.getArguments();

    // Keep note of whether debug is required
    boolean debug = logger.isDebugEnabled();
    boolean trace = logger.isTraceEnabled();
    StringBuilder sb = null;
    if (debug || trace)
    {
        sb = new StringBuilder("\n" +
                    "CMIS invocation:         \n" +
                    "   Method:                 " + methodName + "\n" +
                    "   Arguments:            \n");
        for (Object arg : args)
        {
            sb.append("      ").append(arg).append("\n");
        }
    }

    Object ret = null;
    AlfrescoCmisService service = (AlfrescoCmisService) invocation.getThis();

    try
    {
        // Wrap with pre- and post-method calls
        try
        {
            if(debug || trace)
            {
                sb.append(
                        "   Pre-call authentication: \n" +
                        "      Full auth:           " + AuthenticationUtil.getFullyAuthenticatedUser() + "\n" +
                        "      Effective auth:      " + AuthenticationUtil.getRunAsUser() + "\n");
            }

            if(!methodName.equalsIgnoreCase("close"))
            {
                service.beforeCall();
            }

            if(debug || trace)
            {
                sb.append(
                        "   In-call authentication: \n" +
                        "      Full auth:           " + AuthenticationUtil.getFullyAuthenticatedUser() + "\n" +
                        "      Effective auth:      " + AuthenticationUtil.getRunAsUser() + "\n");
            }

            FileFilterMode.setClient(Client.cmis);

            ret = invocation.proceed();
        }
        finally
        {
        	FileFilterMode.clearClient();

            if(!methodName.equalsIgnoreCase("close"))
            {
                service.afterCall();
            }

            if(debug || trace)
            {
                sb.append(
                        "   Post-call authentication: \n" +
                        "      Full auth:           " + AuthenticationUtil.getFullyAuthenticatedUser() + "\n" +
                        "      Effective auth:      " + AuthenticationUtil.getRunAsUser() + "\n");
            }
        }
        if (trace)
        {
            sb.append(
                    "   Returning:              ").append(ret).append("\n");
            logger.debug(sb);
        }
        // Done
        return ret;
    }
    catch (Throwable e)
    {
        if (debug)
        {
            sb.append("   Throwing:             " + e.getMessage());
            logger.debug(sb, e);
        }
        // Rethrow
        throw e;
    }
}
 
Example 12
Source File: OperateInfoInterceptor.java    From boubei-tss with Apache License 2.0 4 votes vote down vote up
public Object invoke(MethodInvocation invocation) throws Throwable {
	Object target = invocation.getThis();
	Object[] args = invocation.getArguments();
	args = (Object[]) EasyUtils.checkNull(args, new Object[]{});
	
       for (int i = 0; i < args.length; i++) {
           int manipulateKind = judgeManipulateKind(invocation.getMethod().getName());
           if (args[i] instanceof IOperatable 
           		&& (manipulateKind == SAVE || manipulateKind == UPDATE)) {
              
               IOperatable opObj = (IOperatable) args[i];
               Serializable pk = ((IEntity)opObj).getPK();
               
			if( pk == null ) { // ID为null,说明是新建
                   opObj.setCreateTime(new Date());
                   opObj.setCreatorId(Environment.getUserId());
                   opObj.setCreatorName(Environment.getUserName());  
                   
                   // 定时器写数据时,域信息已经指定
                   String domain = (String) EasyUtils.checkNull( opObj.getDomain(), Environment.getDomainOrign() );
                   opObj.setDomain(domain);
               } 
               else {
                   opObj.setUpdateTime(new Date());
                   opObj.setUpdatorId(Environment.getUserId());
                   opObj.setUpdatorName(Environment.getUserName());  
                   
                   /* 修改后,createTime的时分秒没了(日期传递到前台时截去了时分秒,保存后就没有了),
                    * update时不要前台传入的createTime,而是从DB查出来复制回去
                    */
                   @SuppressWarnings("unchecked")
                   IDao<IEntity> dao = (IDao<IEntity>) target;
                   IOperatable old = (IOperatable) dao.getEntity( opObj.getClass(), pk);
                   old = (IOperatable) EasyUtils.checkNull(old, opObj); // 可能修改时记录已被其它人[删除]
                   opObj.setCreateTime(old.getCreateTime());
               }
           }
       }
		
       return invocation.proceed();
}
 
Example 13
Source File: XssResolveAdviceInterceptor.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
@Override
public Object invoke(MethodInvocation invc) throws Throwable {
	Object controller = invc.getThis();
	Method md = invc.getMethod();
	try {
		// Type or method exist @UnsafeXss ignore?
		if (controller.getClass().isAnnotationPresent(UnsafeXss.class) || md.isAnnotationPresent(UnsafeXss.class)) {
			return invc.proceed();
		}

		Object[] args = invc.getArguments();
		if (!isNull(args)) {
			next: for (int i = 0; i < args.length; i++) {
				if (args[i] == null)
					continue;

				// Parameter ignore?
				for (Annotation[] anns : md.getParameterAnnotations()) {
					for (Annotation an : anns) {
						if (an.annotationType() == UnsafeXss.class) {
							continue next;
						}
					}
				}

				// Parameter declared type ignore?
				if (args[i].getClass().isAnnotationPresent(UnsafeXss.class)) {
					continue next;
				}

				// Processing HttpServlet request(if necessary)
				args[i] = processHttpRequestIfNecessary(args[i]);

				if (args[i] instanceof String) {
					args[i] = stringXssEncode(controller, md, i, (String) args[i]);
				} else {
					objectXssEnode(controller, md, i, args[i]);
				}
			}
		}
	} catch (Throwable e) {
		log.error("XSS resolving failure. causes at: ", e);
	}

	// Sets XSS protection headers.
	setXssProtectionHeadersIfNecessary(controller, md);

	return invc.proceed();
}
 
Example 14
Source File: JetCacheInterceptor.java    From jetcache with Apache License 2.0 4 votes vote down vote up
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
    if (configProvider == null) {
        configProvider = applicationContext.getBean(ConfigProvider.class);
    }
    if (configProvider != null && globalCacheConfig == null) {
        globalCacheConfig = configProvider.getGlobalCacheConfig();
    }
    if (globalCacheConfig == null || !globalCacheConfig.isEnableMethodCache()) {
        return invocation.proceed();
    }

    Method method = invocation.getMethod();
    Object obj = invocation.getThis();
    CacheInvokeConfig cac = null;
    if (obj != null) {
        String key = CachePointcut.getKey(method, obj.getClass());
        cac  = cacheConfigMap.getByMethodInfo(key);
    }

    /*
    if(logger.isTraceEnabled()){
        logger.trace("JetCacheInterceptor invoke. foundJetCacheConfig={}, method={}.{}(), targetClass={}",
                cac != null,
                method.getDeclaringClass().getName(),
                method.getName(),
                invocation.getThis() == null ? null : invocation.getThis().getClass().getName());
    }
    */

    if (cac == null || cac == CacheInvokeConfig.getNoCacheInvokeConfigInstance()) {
        return invocation.proceed();
    }

    CacheInvokeContext context = configProvider.getCacheContext().createCacheInvokeContext(cacheConfigMap);
    context.setTargetObject(invocation.getThis());
    context.setInvoker(invocation::proceed);
    context.setMethod(method);
    context.setArgs(invocation.getArguments());
    context.setCacheInvokeConfig(cac);
    context.setHiddenPackages(globalCacheConfig.getHiddenPackages());
    return CacheHandler.invoke(context);
}
 
Example 15
Source File: ApiBootResourceLoadMethodInterceptor.java    From api-boot with Apache License 2.0 4 votes vote down vote up
/**
 * Execute method
 * All event is after method execution query resource url
 *
 * @param invocation MethodInvocation
 * @return Execute Result
 * @throws Throwable method declared exception
 * @see org.minbox.framework.api.boot.plugin.resource.load.enums.ResourceStoreEvent
 */
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
    Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);

    // declared method object instance
    Method declaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

    // method param array
    Object[] params = invocation.getArguments();

    // execute method logic
    Object result = invocation.proceed();
    // get resource Load
    ResourceLoad resourceLoad = declaredMethod.getDeclaredAnnotation(ResourceLoad.class);
    if (!ObjectUtils.isEmpty(resourceLoad)) {
        switch (resourceLoad.event()) {
            case SELECT:
                logger.debug("Execute select resource.");
                if (!ObjectUtils.isEmpty(result)) {
                    // resource push
                    apiBootResourcePusher.loadResource(declaredMethod, result);
                }
                break;
            case INSERT:
                logger.debug("Execute insert resource.");
                // pull resource form param
                apiBootResourcePusher.insertResource(declaredMethod, params);
                break;
            case DELETE:
                logger.debug("Execute delete resource.");
                apiBootResourcePusher.deleteResource(declaredMethod, params);
                break;
            case UPDATE:
                logger.debug("Execute update resource.");
                apiBootResourcePusher.updateResource(declaredMethod, params);
                break;
            default:
                break;
        }
    }
    return result;
}
 
Example 16
Source File: AbstractAopProxyTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	this.target = invocation.getThis();
	return invocation.proceed();
}
 
Example 17
Source File: AbstractAopProxyTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	this.target = invocation.getThis();
	return invocation.proceed();
}
 
Example 18
Source File: AbstractTraceInterceptor.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Return the appropriate {@code Log} instance to use for the given
 * {@code MethodInvocation}. If the {@code useDynamicLogger} flag
 * is set, the {@code Log} instance will be for the target class of the
 * {@code MethodInvocation}, otherwise the {@code Log} will be the
 * default static logger.
 * @param invocation the {@code MethodInvocation} being traced
 * @return the {@code Log} instance to use
 * @see #setUseDynamicLogger
 */
protected Log getLoggerForInvocation(MethodInvocation invocation) {
	if (this.defaultLogger != null) {
		return this.defaultLogger;
	}
	else {
		Object target = invocation.getThis();
		return LogFactory.getLog(getClassForLogging(target));
	}
}
 
Example 19
Source File: AbstractTraceInterceptor.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Return the appropriate {@code Log} instance to use for the given
 * {@code MethodInvocation}. If the {@code useDynamicLogger} flag
 * is set, the {@code Log} instance will be for the target class of the
 * {@code MethodInvocation}, otherwise the {@code Log} will be the
 * default static logger.
 * @param invocation the {@code MethodInvocation} being traced
 * @return the {@code Log} instance to use
 * @see #setUseDynamicLogger
 */
protected Log getLoggerForInvocation(MethodInvocation invocation) {
	if (this.defaultLogger != null) {
		return this.defaultLogger;
	}
	else {
		Object target = invocation.getThis();
		return LogFactory.getLog(getClassForLogging(target));
	}
}
 
Example 20
Source File: AbstractTraceInterceptor.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Return the appropriate {@code Log} instance to use for the given
 * {@code MethodInvocation}. If the {@code useDynamicLogger} flag
 * is set, the {@code Log} instance will be for the target class of the
 * {@code MethodInvocation}, otherwise the {@code Log} will be the
 * default static logger.
 * @param invocation the {@code MethodInvocation} being traced
 * @return the {@code Log} instance to use
 * @see #setUseDynamicLogger
 */
protected Log getLoggerForInvocation(MethodInvocation invocation) {
	if (this.defaultLogger != null) {
		return this.defaultLogger;
	}
	else {
		Object target = invocation.getThis();
		return LogFactory.getLog(getClassForLogging(target));
	}
}