下面列出了javax.management.OperationsException#org.aopalliance.intercept.MethodInvocation 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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();
}
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);
}
}
}
@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);
}
}
@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();
}
}
@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();
}
}
/**
* 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);
}
@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();
}
}
/**
* 后续加上缓存,一定要加
*
* @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());
}
@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;
}
@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));
}
@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());
}
@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);
}
@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;
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
if (method == null) {
return invocation.proceed();
}
Method mostSpecificMethod = AopUtils.getMostSpecificMethod(method, invocation.getThis()
.getClass());
Tracer tracerSpan = findAnnotation(mostSpecificMethod, Tracer.class);
if (tracerSpan == null) {
return invocation.proceed();
}
return sofaMethodInvocationProcessor.process(invocation, tracerSpan);
}
@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;
}
/**
* 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();
}
@Test
public void testUndeclaredUncheckedException() throws Throwable {
final RuntimeException unexpectedException = new RuntimeException();
// 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 (RuntimeException thrown) {
assertEquals("exception matches", unexpectedException, thrown);
}
}
/**
* This implementation returns a shallow copy of this invocation object,
* including an independent copy of the original arguments array.
* <p>We want a shallow copy in this case: We want to use the same interceptor
* chain and other object references, but we want an independent value for the
* current interceptor index.
* @see java.lang.Object#clone()
*/
@Override
public MethodInvocation invocableClone() {
Object[] cloneArguments = this.arguments;
if (this.arguments.length > 0) {
// Build an independent copy of the arguments array.
cloneArguments = new Object[this.arguments.length];
System.arraycopy(this.arguments, 0, cloneArguments, 0, this.arguments.length);
}
return invocableClone(cloneArguments);
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
T tracedExecutor = tracedExecutorProvider.apply(delegate, tracer);
Method methodOnTracedBean = getMethod(invocation, tracedExecutor);
if (methodOnTracedBean != null) {
try {
return methodOnTracedBean.invoke(tracedExecutor, invocation.getArguments());
} catch (InvocationTargetException ex) {
throw ex.getCause();
}
}
return invocation.proceed();
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object retVal = invocation.proceed();
Assert.state(this.applicationEventClassConstructor != null, "No ApplicationEvent class set");
ApplicationEvent event = (ApplicationEvent)
this.applicationEventClassConstructor.newInstance(invocation.getThis());
Assert.state(this.applicationEventPublisher != null, "No ApplicationEventPublisher available");
this.applicationEventPublisher.publishEvent(event);
return retVal;
}
/**
* Determine the validation groups to validate against for the given method invocation.
* <p>Default are the validation groups as specified in the {@link Validated} annotation
* on the containing target class of the method.
* @param invocation the current MethodInvocation
* @return the applicable validation groups as a Class array
*/
protected Class<?>[] determineValidationGroups(MethodInvocation invocation) {
Validated validatedAnn = AnnotationUtils.findAnnotation(invocation.getMethod(), Validated.class);
if (validatedAnn == null) {
validatedAnn = AnnotationUtils.findAnnotation(invocation.getThis().getClass(), Validated.class);
}
return (validatedAnn != null ? validatedAnn.value() : new Class<?>[0]);
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
// 执行业务
long start = System.currentTimeMillis();
Object result = invocation.proceed();
long time = System.currentTimeMillis() - start;
// 异步记录日志
sysLogAspectService.createLog(invocation, time);
return result;
}
@Override
protected Object invokeUnderTrace(MethodInvocation invocation, Log logger) throws Throwable {
String invocationDescription = getInvocationDescription(invocation);
writeToLog(logger, "Entering " + invocationDescription);
try {
Object rval = invocation.proceed();
writeToLog(logger, "Exiting " + invocationDescription);
return rval;
}
catch (Throwable ex) {
writeToLog(logger, "Exception thrown in " + invocationDescription, ex);
throw ex;
}
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Set<String> localKeys = new HashSet<>();
try (LocalKeysHolder ignored = new LocalKeysHolder(localKeys)) {
MethodMdc methodMdc = methodDefinitions.get(invocation.getMethod());
processMethodDefinitions(invocation, methodMdc, localKeys);
processParameterDefinitions(invocation, methodMdc, localKeys);
return invocation.proceed();
}
}
private Exception adaptExceptionIfNecessary(MethodInvocation methodInvocation, ResourceException ex) {
if (ReflectionUtils.declaresException(methodInvocation.getMethod(), ex.getClass())) {
return ex;
}
else {
return new InternalResourceException(ex);
}
}
/**
* Adds the {@code String} representation of the method return value
* to the supplied {@code StringBuffer}. Correctly handles
* {@code null} and {@code void} results.
* @param methodInvocation the {@code MethodInvocation} that returned the value
* @param matcher the {@code Matcher} containing the matched placeholder
* @param output the {@code StringBuffer} to write output to
* @param returnValue the value returned by the method invocation.
*/
private void appendReturnValue(
MethodInvocation methodInvocation, Matcher matcher, StringBuffer output, @Nullable Object returnValue) {
if (methodInvocation.getMethod().getReturnType() == void.class) {
matcher.appendReplacement(output, "void");
}
else if (returnValue == null) {
matcher.appendReplacement(output, "null");
}
else {
matcher.appendReplacement(output, Matcher.quoteReplacement(returnValue.toString()));
}
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
// Validate parameters.
validateMethodParameters(invocation);
// No violations found, proceed with service call.
return invocation.proceed();
}
@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;
}
@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();
}
/**
* @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");
}