org.aopalliance.intercept.MethodInvocation Java Examples

The following examples show how to use org.aopalliance.intercept.MethodInvocation. 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: AuthenticationAspect.java    From act-platform with ISC License 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
  Service service = getService(invocation);
  RequestHeader requestHeader = getRequestHeader(invocation);

  try {
    // For each service method invocation verify that user is authenticated!
    //noinspection unchecked
    accessController.validate(requestHeader.getCredentials());
  } catch (InvalidCredentialsException ex) {
    throw new AuthenticationFailedException("Could not authenticate user: " + ex.getMessage());
  }

  if (SecurityContext.isSet()) {
    return invocation.proceed();
  }

  try (SecurityContext ignored = SecurityContext.set(service.createSecurityContext(requestHeader.getCredentials()))) {
    return invocation.proceed();
  }
}
 
Example #2
Source File: ProxyFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testInterceptorInclusionMethods() {
	class MyInterceptor implements MethodInterceptor {
		@Override
		public Object invoke(MethodInvocation invocation) throws Throwable {
			throw new UnsupportedOperationException();
		}
	}

	NopInterceptor di = new NopInterceptor();
	NopInterceptor diUnused = new NopInterceptor();
	ProxyFactory factory = new ProxyFactory(new TestBean());
	factory.addAdvice(0, di);
	assertThat(factory.getProxy(), instanceOf(ITestBean.class));
	assertTrue(factory.adviceIncluded(di));
	assertTrue(!factory.adviceIncluded(diUnused));
	assertTrue(factory.countAdvicesOfType(NopInterceptor.class) == 1);
	assertTrue(factory.countAdvicesOfType(MyInterceptor.class) == 0);

	factory.addAdvice(0, diUnused);
	assertTrue(factory.adviceIncluded(diUnused));
	assertTrue(factory.countAdvicesOfType(NopInterceptor.class) == 2);
}
 
Example #3
Source File: MdcAdvisor.java    From eclair with Apache License 2.0 6 votes vote down vote up
void processParameterDefinitions(MethodInvocation invocation, MethodMdc methodMdc, Set<String> localKeys) {
    Object[] arguments = invocation.getArguments();
    for (int a = 0; a < arguments.length; a++) {
        for (ParameterMdc definition : methodMdc.getParameterDefinitions().get(a)) {
            String key = definition.getKey();
            if (key.isEmpty()) {
                key = methodMdc.getParameterNames().get(a);
                if (isNull(key)) {
                    key = synthesizeKey(invocation.getMethod().getName(), a);
                }
            }
            String expressionString = definition.getExpressionString();
            Object value = expressionString.isEmpty() ? arguments[a] : expressionEvaluator.evaluate(expressionString, arguments[a]);
            putMdc(key, value, definition, localKeys);
        }
    }
}
 
Example #4
Source File: AsyncExecutionTests.java    From java-technology-stack 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 #5
Source File: MethodValidationInterceptor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
public static Object invokeWithinValidation(MethodInvocation invocation, Validator validator, Class<?>[] groups)
		throws Throwable {

	org.hibernate.validator.method.MethodValidator methodValidator =
			validator.unwrap(org.hibernate.validator.method.MethodValidator.class);
	Set<org.hibernate.validator.method.MethodConstraintViolation<Object>> result =
			methodValidator.validateAllParameters(
					invocation.getThis(), invocation.getMethod(), invocation.getArguments(), groups);
	if (!result.isEmpty()) {
		throw new org.hibernate.validator.method.MethodConstraintViolationException(result);
	}
	Object returnValue = invocation.proceed();
	result = methodValidator.validateReturnValue(
			invocation.getThis(), invocation.getMethod(), returnValue, groups);
	if (!result.isEmpty()) {
		throw new org.hibernate.validator.method.MethodConstraintViolationException(result);
	}
	return returnValue;
}
 
Example #6
Source File: PerformanceMonitorInterceptorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testExceptionPathStillLogsPerformanceMetricsCorrectly() throws Throwable {
	MethodInvocation mi = mock(MethodInvocation.class);

	given(mi.getMethod()).willReturn(String.class.getMethod("toString", new Class[0]));
	given(mi.proceed()).willThrow(new IllegalArgumentException());
	Log log = mock(Log.class);

	PerformanceMonitorInterceptor interceptor = new PerformanceMonitorInterceptor(true);
	try {
		interceptor.invokeUnderTrace(mi, log);
		fail("Must have propagated the IllegalArgumentException.");
	}
	catch (IllegalArgumentException expected) {
	}

	verify(log).trace(anyString());
}
 
Example #7
Source File: SimpleTraceInterceptorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testExceptionPathStillLogsCorrectly() throws Throwable {
	MethodInvocation mi = mock(MethodInvocation.class);
	given(mi.getMethod()).willReturn(String.class.getMethod("toString"));
	given(mi.getThis()).willReturn(this);
	IllegalArgumentException exception = new IllegalArgumentException();
	given(mi.proceed()).willThrow(exception);

	Log log = mock(Log.class);

	final SimpleTraceInterceptor interceptor = new SimpleTraceInterceptor(true);

	try {
		interceptor.invokeUnderTrace(mi, log);
		fail("Must have propagated the IllegalArgumentException.");
	}
	catch (IllegalArgumentException expected) {
	}

	verify(log).trace(anyString());
	verify(log).trace(anyString(), eq(exception));
}
 
Example #8
Source File: TimerMetricsAdvice.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	try {
		// Get metric(method) name.
		String metricName = getMetricName(invocation);

		long start = System.currentTimeMillis();
		Object res = invocation.proceed();
		long timeDiff = System.currentTimeMillis() - start;

		// Save gauge.
		this.gaugeService.submit(warpTimerName(metricName), timeDiff);

		// Save gauge to healthIndicator.
		this.saveHealthIndicator(metricName, timeDiff);

		return res;
	} catch (Throwable e) {
		throw new UmcException(e);
	}
}
 
Example #9
Source File: CacheInterceptor.java    From java-technology-stack 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 #10
Source File: WxInvokerProxyFactoryBean.java    From FastBootWeixin with Apache License 2.0 6 votes vote down vote up
/**
 * 后续加上缓存,一定要加
 *
 * @param inv
 * @return the result
 * @throws Throwable
 */
@Override
public Object invoke(MethodInvocation inv) throws Throwable {
    if (ReflectionUtils.isObjectMethod(inv.getMethod())) {
        if (ReflectionUtils.isToStringMethod(inv.getMethod())) {
            return clazz.getName();
        }
        return ReflectionUtils.invokeMethod(inv.getMethod(), inv.getThis(), inv.getArguments());
    }
    WxApiMethodInfo wxApiMethodInfo = methodCache.get(inv.getMethod());
    if (wxApiMethodInfo == null) {
        wxApiMethodInfo = new WxApiMethodInfo(inv.getMethod(), wxApiTypeInfo);
        methodCache.put(inv.getMethod(), wxApiMethodInfo);
    }
    return wxApiExecutor.execute(wxApiMethodInfo, inv.getArguments());
}
 
Example #11
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 #12
Source File: DelegatePerTargetObjectIntroductionInterceptor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Subclasses may need to override this if they want to perform custom
 * behaviour in around advice. However, subclasses should invoke this
 * method, which handles introduced interfaces and forwarding to the target.
 */
@Override
@Nullable
public Object invoke(MethodInvocation mi) throws Throwable {
	if (isMethodOnIntroducedInterface(mi)) {
		Object delegate = getIntroductionDelegateFor(mi.getThis());

		// Using the following method rather than direct reflection,
		// we get correct handling of InvocationTargetException
		// if the introduced method throws an exception.
		Object retVal = AopUtils.invokeJoinpointUsingReflection(delegate, mi.getMethod(), mi.getArguments());

		// Massage return value if possible: if the delegate returned itself,
		// we really want to return the proxy.
		if (retVal == delegate && mi instanceof ProxyMethodInvocation) {
			retVal = ((ProxyMethodInvocation) mi).getProxy();
		}
		return retVal;
	}

	return doProceed(mi);
}
 
Example #13
Source File: CustomizableTraceInterceptorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testSunnyDayPathLogsCorrectly() throws Throwable {

	MethodInvocation methodInvocation = mock(MethodInvocation.class);
	given(methodInvocation.getMethod()).willReturn(String.class.getMethod("toString"));
	given(methodInvocation.getThis()).willReturn(this);

	Log log = mock(Log.class);
	given(log.isTraceEnabled()).willReturn(true);

	CustomizableTraceInterceptor interceptor = new StubCustomizableTraceInterceptor(log);
	interceptor.invoke(methodInvocation);

	verify(log, times(2)).trace(anyString());
}
 
Example #14
Source File: EventPublicationInterceptor.java    From disruptor-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	Object retVal = invocation.proceed();
	DisruptorEvent event = (DisruptorEvent) this.applicationEventClassConstructor.newInstance(new Object[] {invocation.getThis()});
	this.applicationEventPublisher.publishEvent(event);
	return retVal;
}
 
Example #15
Source File: RunAsTenantInterceptor.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Object invoke(final MethodInvocation mi) throws Throwable
{
    TenantRunAsWork<Object> runAs = new TenantRunAsWork<Object>()
    {
        public Object doWork() throws Exception
        {
            try
            {
                return mi.proceed();
            }
            catch(Throwable e)
            {
                e.printStackTrace();
                
                // Re-throw the exception
                if (e instanceof RuntimeException)
                {
                    throw (RuntimeException) e;
                }
                throw new RuntimeException("Failed to execute in RunAsTenant context", e);
            }
        }
    };
    
    if (tenantType == TENANT_TYPE.Default)
    {
        return TenantUtil.runAsDefaultTenant(runAs);
    }
    else
    {
        // run as tenant using current tenant context (if no tenant context then it is implied as the primary tenant, based on username)
        return TenantUtil.runAsTenant(runAs, AuthenticationUtil.getUserTenant(AuthenticationUtil.getFullyAuthenticatedUser()).getSecond());
    }
}
 
Example #16
Source File: LevelSensitiveLoggerTest.java    From eclair with Apache License 2.0 5 votes vote down vote up
@Test
public void isLogOutNecessaryNotNullEnabled() {
    // given
    MethodInvocation invocation = mock(MethodInvocation.class);
    MethodLog methodLog = givenMethodLog(null, null, givenOutLog(), null);

    LevelSensitiveLogger levelSensitiveLogger = spy(LevelSensitiveLogger.class);
    when(levelSensitiveLogger.isLogEnabled(any(), any())).thenReturn(true);
    // when
    boolean necessary = levelSensitiveLogger.isLogOutNecessary(invocation, methodLog);
    // then
    verify(levelSensitiveLogger).getLoggerName(invocation);
    verify(levelSensitiveLogger).isLogEnabled(any(), any());
    assertTrue(necessary);
}
 
Example #17
Source File: StatMethod.java    From TakinRPC with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    Stopwatch watch = Stopwatch.createStarted();
    invocation.getClass().getName();
    Object obj = invocation.proceed();
    logger.info(String.format("use:%s %s.%s ", watch.toString(), invocation.getMethod().getDeclaringClass().getSimpleName(), invocation.getMethod().getName()));
    return obj;
}
 
Example #18
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 #19
Source File: LdempotentMethodInterceptor.java    From fast-family-master with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    String ldempotentToken = Optional.ofNullable(WebUtils.getHttpServletRequest().getHeader(commonProperties.getLdempotent().getLdempotentHeaderName()))
            .orElseThrow(() -> new LdempotentException(ResponseCode.LDEMPOTENT_ERROR.getCode(),ResponseCode.LDEMPOTENT_ERROR.getMessage()));
    RMapCache<String,String> rMapCache = redissonClient.getMapCache(commonProperties.getLdempotent().getLdempotentKey());
    if (rMapCache.put(commonProperties.getLdempotent().getLdempotentPrefix() + ldempotentToken,ldempotentToken,
            commonProperties.getLdempotent().getTtl(), TimeUnit.MINUTES) != null){
        throw new LdempotentException(ResponseCode.LDEMPOTENT_ERROR.getCode(),ResponseCode.LDEMPOTENT_ERROR.getMessage());
    }
    return invocation.proceed();
}
 
Example #20
Source File: SecurityDialectPostProcessor.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
public Object postProcessBeforeInitialization(
	Object bean, String beanName) throws BeansException {
	if (bean instanceof SpringTemplateEngine) {
		SpringTemplateEngine engine =
					(SpringTemplateEngine) bean;
		SecurityExpressionHandler<MethodInvocation> handler =
			applicationContext.getBean(
							SecurityExpressionHandler.class);
		SecurityDialect dialect = new SecurityDialect(handler);
		engine.addDialect(dialect);
	}
	return bean;
}
 
Example #21
Source File: ExposeInvocationInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
	MethodInvocation oldInvocation = invocation.get();
	invocation.set(mi);
	try {
		return mi.proceed();
	}
	finally {
		invocation.set(oldInvocation);
	}
}
 
Example #22
Source File: PerformanceMonitorInterceptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected Object invokeUnderTrace(MethodInvocation invocation, Log logger) throws Throwable {
	String name = createInvocationTraceName(invocation);
	StopWatch stopWatch = new StopWatch(name);
	stopWatch.start(name);
	try {
		return invocation.proceed();
	}
	finally {
		stopWatch.stop();
		writeToLog(logger, stopWatch.shortSummary());
	}
}
 
Example #23
Source File: ExposeBeanNameAdvisors.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
	if (!(mi instanceof ProxyMethodInvocation)) {
		throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi);
	}
	ProxyMethodInvocation pmi = (ProxyMethodInvocation) mi;
	pmi.setUserAttribute(BEAN_NAME_ATTRIBUTE, this.beanName);
	return mi.proceed();
}
 
Example #24
Source File: PermissionExpressionHandler.java    From zhcet-web with Apache License 2.0 5 votes vote down vote up
@Override
protected MethodSecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication, MethodInvocation invocation) {
    DomainPermissionExpression root = new DomainPermissionExpression(authentication);
    root.setPermissionEvaluator(getPermissionEvaluator());
    root.setTrustResolver(this.trustResolver);
    root.setRoleHierarchy(getRoleHierarchy());
    return root;
}
 
Example #25
Source File: AbstractSlsbInvokerInterceptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Prepares the thread context if necessary, and delegates to
 * {@link #invokeInContext}.
 */
@Override
@Nullable
public Object invoke(MethodInvocation invocation) throws Throwable {
	Context ctx = (this.exposeAccessContext ? getJndiTemplate().getContext() : null);
	try {
		return invokeInContext(invocation);
	}
	finally {
		getJndiTemplate().releaseContext(ctx);
	}
}
 
Example #26
Source File: SofaTracerMethodInvocationProcessor.java    From sofa-tracer with Apache License 2.0 5 votes vote down vote up
private Object proceedProxyMethodWithTracerAnnotation(MethodInvocation invocation,
                                                      Tracer tracerSpan) throws Throwable {
    if (tracer instanceof FlexibleTracer) {
        try {
            String operationName = tracerSpan.operateName();
            if (StringUtils.isBlank(operationName)) {
                operationName = invocation.getMethod().getName();
            }
            SofaTracerSpan sofaTracerSpan = ((FlexibleTracer) tracer)
                .beforeInvoke(operationName);
            sofaTracerSpan.setTag(CommonSpanTags.METHOD, invocation.getMethod().getName());
            if (invocation.getArguments() != null && invocation.getArguments().length != 0) {
                StringBuilder stringBuilder = new StringBuilder();
                for (Object obj : invocation.getArguments()) {
                    stringBuilder.append(obj.getClass().getName()).append(";");
                }
                sofaTracerSpan.setTag("param.types",
                    stringBuilder.toString().substring(0, stringBuilder.length() - 1));
            }
            return invocation.proceed();
        } catch (Throwable t) {
            ((FlexibleTracer) tracer).afterInvoke(t.getMessage());
            throw t;
        } finally {
            ((FlexibleTracer) tracer).afterInvoke();
        }
    } else {
        return invocation.proceed();
    }
}
 
Example #27
Source File: PrivilegesGuardInterceptor.java    From rebuild with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param invocation
 * @return
 */
private boolean isGuardMethod(MethodInvocation invocation) {
	if (CommonService.class.isAssignableFrom(invocation.getThis().getClass())) {
		return false;
	}
	String action = invocation.getMethod().getName();
	return action.startsWith("create") || action.startsWith("update") || action.startsWith("delete") 
			|| action.startsWith("assign") || action.startsWith("share") || action.startsWith("unshare")
			|| action.startsWith("bulk");
}
 
Example #28
Source File: AnnotationDrivenTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
	if (methodInvocation.getMethod().getName().equals("setSomething")) {
		assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
		assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
	}
	else {
		assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
		assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	}
	return methodInvocation.proceed();
}
 
Example #29
Source File: CglibAopProxy.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
	MethodInvocation invocation = new CglibMethodInvocation(proxy, this.target, method, args,
			this.targetClass, this.adviceChain, methodProxy);
	// If we get here, we need to create a MethodInvocation.
	Object retVal = invocation.proceed();
	retVal = processReturnType(proxy, this.target, method, retVal);
	return retVal;
}
 
Example #30
Source File: JndiObjectFactoryBean.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	Context ctx = (isEligible(invocation.getMethod()) ? this.jndiTemplate.getContext() : null);
	try {
		return invocation.proceed();
	}
	finally {
		this.jndiTemplate.releaseContext(ctx);
	}
}