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

The following examples show how to use org.aopalliance.intercept.MethodInvocation#getMethod() . 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: CompletionRegisteringBeanPostProcessor.java    From spring-domain-events with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {

	Object result = invocation.proceed();
	Method method = invocation.getMethod();

	// Mark publication complete if the method is a transactional event listener.
	if (!isCompletingMethod(method)) {
		return result;
	}

	PublicationTargetIdentifier identifier = PublicationTargetIdentifier.forMethod(method);
	registry.get().markCompleted(invocation.getArguments()[0], identifier);

	return result;
}
 
Example 2
Source File: ConditionedInterceptor.java    From NoraUi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    //
    Method m = invocation.getMethod();

    if (m.isAnnotationPresent(Conditioned.class)) {
        Object[] arg = invocation.getArguments();
        if (arg.length > 0 && arg[arg.length - 1] instanceof List && !((List) arg[arg.length - 1]).isEmpty() && ((List) arg[arg.length - 1]).get(0) instanceof GherkinStepCondition) {
            List<GherkinStepCondition> conditions = (List) arg[arg.length - 1];
            displayMessageAtTheBeginningOfMethod(m.getName(), conditions);
            if (!checkConditions(conditions)) {
                Context.getCurrentScenario().write(Messages.getMessage(SKIPPED_DUE_TO_CONDITIONS));
                Context.goToNextStep();
                return Void.TYPE;
            }
        }
    }

    log.debug("NORAUI ConditionedInterceptor invoke method {}", invocation.getMethod());
    return invocation.proceed();
}
 
Example 3
Source File: HttpParamsValidateAdvisor.java    From common-project with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    Method method = methodInvocation.getMethod();
    Object[] arguments = methodInvocation.getArguments();
    Parameter[] parameters = method.getParameters();
    for (int i=0;i<parameters.length; i++) {
        ParamsValidate annotation = parameters[i].getAnnotation(ParamsValidate.class);
        if (annotation!=null){
            Set<ConstraintViolation<Object>> violationSet = ValidatorConfiguration.validator().validate(arguments[i]);
            for (ConstraintViolation model : violationSet) {
                logger.warn(model.getPropertyPath()+model.getMessage());
                return JSON.toJSONString(new ResponseMessage(-1,model.getPropertyPath()+model.getMessage()));
            }
        }
    }

    Object proceed = null;
    try {
        proceed = methodInvocation.proceed();
    }catch (Exception e){
        throw e;
    }
    return proceed;
}
 
Example 4
Source File: TransactionInterceptor.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
	Method method = invocation.getMethod();
	TransactionNode transactionNode = AnnotationUtils.findAnnotation(method, TransactionNode.class);
	if (transactionNode != null) { // check
		return transactionTemplate.execute(new TransactionCallback<Object>() {
			@Override
			public Object doInTransaction(Transaction transaction) throws Throwable {
				if (transaction.getTransactionStatus() == TransactionStatus.BEGINNING) { // Root / Nested / Branch
					Participant participant = buildParticipant(invocation);
					transactionTemplate.getTransactionManager().addParticipant(participant);
				}
				
				return invocation.proceed();
			}
		});
	} else {
		return invocation.proceed();
	}
}
 
Example 5
Source File: TxleJpaRepositoryInterceptor.java    From txle with Apache License 2.0 6 votes vote down vote up
public Object doFilter(MethodInvocation invocation) throws Throwable {
    Method method = invocation.getMethod();
    Query queryAnnotation = method.getAnnotation(Query.class);
    String sql = method.getName();
    if (queryAnnotation != null) {
        sql = queryAnnotation.value();
        // It'll not have a boundary if append arguments to metrics variables, that's not allowed, because it maybe lead to prometheus' death, so have to abandon arguments.
    }

    String globalTxId = txleMetrics.startMarkSQLDurationAndCount(sql, queryAnnotation == null, invocation.getArguments());

    Object obj = invocation.proceed();

    txleMetrics.endMarkSQLDuration(globalTxId);

    return obj;
}
 
Example 6
Source File: JCacheInterceptor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
public Object invoke(final MethodInvocation invocation) throws Throwable {
	Method method = invocation.getMethod();

	CacheOperationInvoker aopAllianceInvoker = () -> {
		try {
			return invocation.proceed();
		}
		catch (Throwable ex) {
			throw new CacheOperationInvoker.ThrowableWrapper(ex);
		}
	};

	try {
		return execute(aopAllianceInvoker, invocation.getThis(), method, invocation.getArguments());
	}
	catch (CacheOperationInvoker.ThrowableWrapper th) {
		throw th.getOriginal();
	}
}
 
Example 7
Source File: AbstractMonitoringInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a {@code String} name for the given {@code MethodInvocation}
 * that can be used for trace/logging purposes. This name is made up of the
 * configured prefix, followed by the fully-qualified name of the method being
 * invoked, followed by the configured suffix.
 * @see #setPrefix
 * @see #setSuffix
 */
protected String createInvocationTraceName(MethodInvocation invocation) {
	StringBuilder sb = new StringBuilder(getPrefix());
	Method method = invocation.getMethod();
	Class<?> clazz = method.getDeclaringClass();
	if (this.logTargetClassInvocation && clazz.isInstance(invocation.getThis())) {
		clazz = invocation.getThis().getClass();
	}
	sb.append(clazz.getName());
	sb.append('.').append(method.getName());
	sb.append(getSuffix());
	return sb.toString();
}
 
Example 8
Source File: SimpleLockDelegate.java    From fast-family-master with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    Method method = invocation.getMethod();
    lockStrategy = matchLockStrategy(method);
    LockInfo lockInfo = new LockInfo();
    RLock rLock = null;
    try {
        rLock = lockStrategy.tryLock(lockInfo);
        return invocation.proceed();
    } catch (Exception e) {
        throw e;
    } finally {
        lockStrategy.unlock(rLock);
    }
}
 
Example 9
Source File: MBeanClientInterceptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Nullable
private Object invokeAttribute(PropertyDescriptor pd, MethodInvocation invocation)
		throws JMException, IOException {

	Assert.state(this.serverToUse != null, "No MBeanServerConnection available");

	String attributeName = JmxUtils.getAttributeName(pd, this.useStrictCasing);
	MBeanAttributeInfo inf = this.allowedAttributes.get(attributeName);
	// If no attribute is returned, we know that it is not defined in the
	// management interface.
	if (inf == null) {
		throw new InvalidInvocationException(
				"Attribute '" + pd.getName() + "' is not exposed on the management interface");
	}

	if (invocation.getMethod().equals(pd.getReadMethod())) {
		if (inf.isReadable()) {
			return this.serverToUse.getAttribute(this.objectName, attributeName);
		}
		else {
			throw new InvalidInvocationException("Attribute '" + attributeName + "' is not readable");
		}
	}
	else if (invocation.getMethod().equals(pd.getWriteMethod())) {
		if (inf.isWritable()) {
			this.serverToUse.setAttribute(this.objectName, new Attribute(attributeName, invocation.getArguments()[0]));
			return null;
		}
		else {
			throw new InvalidInvocationException("Attribute '" + attributeName + "' is not writable");
		}
	}
	else {
		throw new IllegalStateException(
				"Method [" + invocation.getMethod() + "] is neither a bean property getter nor a setter");
	}
}
 
Example 10
Source File: Target_DefaultMethodInvokingMethodInterceptor.java    From spring-boot-graal-feature with Apache License 2.0 5 votes vote down vote up
@Substitute
public Object invoke(MethodInvocation invocation) throws Throwable {
	Method method = invocation.getMethod();
	Object[] arguments = invocation.getArguments();
	Object proxy = ((ProxyMethodInvocation)invocation).getProxy();
	return method.invoke(proxy,arguments);
}
 
Example 11
Source File: AbstractMonitoringInterceptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create a {@code String} name for the given {@code MethodInvocation}
 * that can be used for trace/logging purposes. This name is made up of the
 * configured prefix, followed by the fully-qualified name of the method being
 * invoked, followed by the configured suffix.
 * @see #setPrefix
 * @see #setSuffix
 */
protected String createInvocationTraceName(MethodInvocation invocation) {
	StringBuilder sb = new StringBuilder(getPrefix());
	Method method = invocation.getMethod();
	Class<?> clazz = method.getDeclaringClass();
	if (this.logTargetClassInvocation && clazz.isInstance(invocation.getThis())) {
		clazz = invocation.getThis().getClass();
	}
	sb.append(clazz.getName());
	sb.append('.').append(method.getName());
	sb.append(getSuffix());
	return sb.toString();
}
 
Example 12
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 13
Source File: MBeanClientInterceptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Nullable
private Object invokeAttribute(PropertyDescriptor pd, MethodInvocation invocation)
		throws JMException, IOException {

	Assert.state(this.serverToUse != null, "No MBeanServerConnection available");

	String attributeName = JmxUtils.getAttributeName(pd, this.useStrictCasing);
	MBeanAttributeInfo inf = this.allowedAttributes.get(attributeName);
	// If no attribute is returned, we know that it is not defined in the
	// management interface.
	if (inf == null) {
		throw new InvalidInvocationException(
				"Attribute '" + pd.getName() + "' is not exposed on the management interface");
	}

	if (invocation.getMethod().equals(pd.getReadMethod())) {
		if (inf.isReadable()) {
			return this.serverToUse.getAttribute(this.objectName, attributeName);
		}
		else {
			throw new InvalidInvocationException("Attribute '" + attributeName + "' is not readable");
		}
	}
	else if (invocation.getMethod().equals(pd.getWriteMethod())) {
		if (inf.isWritable()) {
			this.serverToUse.setAttribute(this.objectName, new Attribute(attributeName, invocation.getArguments()[0]));
			return null;
		}
		else {
			throw new InvalidInvocationException("Attribute '" + attributeName + "' is not writable");
		}
	}
	else {
		throw new IllegalStateException(
				"Method [" + invocation.getMethod() + "] is neither a bean property getter nor a setter");
	}
}
 
Example 14
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 15
Source File: AbstractAopProxyTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
	Method m = mi.getMethod();
	Object retval = mi.proceed();
	assertEquals("Method invocation has same method on way back", m, mi.getMethod());
	return retval;
}
 
Example 16
Source File: AbstractMonitoringInterceptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a {@code String} name for the given {@code MethodInvocation}
 * that can be used for trace/logging purposes. This name is made up of the
 * configured prefix, followed by the fully-qualified name of the method being
 * invoked, followed by the configured suffix.
 * @see #setPrefix
 * @see #setSuffix
 */
protected String createInvocationTraceName(MethodInvocation invocation) {
	Method method = invocation.getMethod();
	Class<?> clazz = method.getDeclaringClass();
	if (this.logTargetClassInvocation && clazz.isInstance(invocation.getThis())) {
		clazz = invocation.getThis().getClass();
	}
	return getPrefix() + clazz.getName() + '.' + method.getName() + getSuffix();
}
 
Example 17
Source File: JvueMethodAclVoter.java    From jvue-admin with MIT License 4 votes vote down vote up
@Override
public int vote(Authentication authentication, MethodInvocation invocation,
        Collection<ConfigAttribute> attributes) {
    JwtUserDetails jwtUser = null;
    // 1.判断是否为超级管理员,是的话直接放行
    if (authentication.getPrincipal() instanceof JwtUserDetails) {
        jwtUser = (JwtUserDetails) authentication.getPrincipal();
        if (jwtUser.getSuperUser() == JvueDataStatus.SUPER_USER_TRUE) {
            // 放行
            return ACCESS_GRANTED;
        }
    } else {
        return ACCESS_ABSTAIN;
    }

    // 1.判断URL对应的权限定义
    // >> arg1 FilterInvocation: URL: /module?page=0&pageSize=10
    // >> 如果不需要登录的话,直接放行
    Method method = invocation.getMethod();
    AclResc classResc = method.getDeclaringClass().getAnnotation(AclResc.class);
    AclResc methodAclResc = method.getAnnotation(AclResc.class);
    Integer apiCode = 0;
    if (classResc != null) {
        apiCode += classResc.id();
    }
    if (methodAclResc != null) {
        apiCode += methodAclResc.id();
    }
    
    if(apiCode > 0) {
        List<Integer> roles = jvueRoleService.getRolesByApi(apiCode);
        if (!roles.isEmpty()) {
            // 2.判断是否为超级管理员,是的话直接放行
            Collection<Integer> intersection =
                    CollectionUtils.intersection(roles, jwtUser.getRoles());
            if (intersection.isEmpty()) {
                // 没有匹配到角色
                return ACCESS_DENIED;
            } else {
                logger.debug("匹配到角色 {}", intersection);
                return ACCESS_GRANTED;
            }
        } else {
            return ACCESS_ABSTAIN;
        }
    } else {
        return ACCESS_ABSTAIN;
    }
}
 
Example 18
Source File: SingleEntryTransactionResourceInterceptor.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private Object invokeInternal(MethodInvocation invocation) throws Throwable
{
    // Get the txn start time
    long txnStartTime = AlfrescoTransactionSupport.getTransactionStartTime();
    if (txnStartTime < 0)
    {
        // There is no transaction
        return invocation.proceed();
    }
    
    // Check if the required time has passed
    long now = System.currentTimeMillis();
    long txnElapsedTime = (now - txnStartTime);
    if (txnElapsedTime < elapsedTimeBeforeActivationMillis)
    {
        // It's not been long enough
        return invocation.proceed();
    }

    // We need to start timing the method calls
    Method calledMethod = invocation.getMethod();
    long beforeNs = System.nanoTime();
    Object ret = invocation.proceed();
    long deltaNs = System.nanoTime() - beforeNs;
    
    // Get the method stats
    @SuppressWarnings("unchecked")
    Map<Method, MethodStatistics> methodStatsByMethod =
        (Map<Method, MethodStatistics>) AlfrescoTransactionSupport.getResource(resourceKey);
    if (methodStatsByMethod == null)
    {
        methodStatsByMethod = new HashMap<Method, MethodStatistics>(11);
        AlfrescoTransactionSupport.bindResource(resourceKey, methodStatsByMethod);
    }
    
    // Update method stats
    MethodStatistics calledMethodStats = methodStatsByMethod.get(calledMethod);
    if (calledMethodStats == null)
    {
        calledMethodStats = new MethodStatistics();
        methodStatsByMethod.put(calledMethod, calledMethodStats);
    }
    calledMethodStats.accumulateNs(deltaNs);
    
    // Check if we need to call the resource managers to clean up 
    if ((now - lastCallMillis) >= resourceManagerCallFrequencyMillis)
    {
        for (MethodResourceManager resourceManager : methodResourceManagers)
        {
            resourceManager.manageResources(methodStatsByMethod, txnElapsedTime, calledMethod);
        }
        lastCallMillis = now;
    }
    
    // Done
    return ret;
}
 
Example 19
Source File: BusinessLogInterceptor.java    From boubei-tss with Apache License 2.0 4 votes vote down vote up
public Object invoke(MethodInvocation invocation) throws Throwable {
     Method targetMethod = invocation.getMethod(); /* 获取目标方法 */
     Object[] args = invocation.getArguments(); /* 获取目标方法的参数 */
     
     Long preTime = System.currentTimeMillis();
     Object returnVal = invocation.proceed(); /* 调用目标方法的返回值 */
     
     int methodExcuteTime = (int) (System.currentTimeMillis() - preTime);

     Logable annotation = targetMethod.getAnnotation(Logable.class); // 取得注释对象
     if (annotation != null) {

         String operateTable = annotation.operateObject();
         String operateInfo = annotation.operateInfo();
         
         String operateMethod = targetMethod.getName();
         
         returnVal = EasyUtils.checkNull(returnVal, "_null_");
         Map<String, Object> data = new HashMap<String, Object>();
         data.put("returnVal", returnVal);
         
         Class<? extends Object> rvClazz = returnVal.getClass();
Table table = rvClazz.getAnnotation(Table.class);
         if( table != null ) {
         	// 检测数据表是否配置了忽略日志,eg:取号器等
         	LogDisable logDisable = rvClazz.getAnnotation(LogDisable.class);
         	if( logDisable != null ) {
         		return returnVal;
         	}
         	
         	if( "${table}".equals(operateTable) ) {
         		operateTable = table.name();
         	}
         	data.put("tableName", operateTable);
         }
         if( returnVal instanceof IEntity ) {
         	operateMethod += ", " + ((IEntity)returnVal).getPK();
         }

         Log log = new Log(operateMethod, parseMacro(operateInfo, args, data));
         log.setOperateTable(operateTable);
         log.setMethodExcuteTime(methodExcuteTime);

         businessLogger.output(log);
     }

     return returnVal;
 }
 
Example 20
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);
}