Java 类org.aopalliance.intercept.MethodInvocation 实例源码

项目:SpringTutorial    文件:InsertAroundMethod.java   
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {

    System.out.println("Method name : "
            + methodInvocation.getMethod().getName());

    // same with MethodBeforeAdvice
    System.out.println("InsertAroundMethod : Before method inserted!");

    try {
        // proceed to original method call
        Object result = methodInvocation.proceed();

        // same with AfterReturningAdvice
        System.out.println("InsertAroundMethod : after method inserted!");

        return result;

    } catch (IllegalArgumentException e) {
        // same with ThrowsAdvice
        System.out
                .println("InsertAroundMethod : Throw exception inserted!");
        throw e;
    }
}
项目:configx    文件:StandardBeanLifecycleDecorator.java   
/**
 * Apply a lock (preferably a read lock allowing multiple concurrent access) to the bean. Callers should replace the
 * bean input with the output.
 *
 * @param bean the bean to lock
 * @param lock the lock to apply
 * @return a proxy that locks while its methods are executed
 */
private Object getDisposalLockProxy(Object bean, final Lock lock) {
    ProxyFactory factory = new ProxyFactory(bean);
    factory.setProxyTargetClass(proxyTargetClass);
    factory.addAdvice(new MethodInterceptor() {
        public Object invoke(MethodInvocation invocation) throws Throwable {
            lock.lock();
            try {
                return invocation.proceed();
            } finally {
                lock.unlock();
            }
        }
    });
    return factory.getProxy();
}
项目:act-platform    文件:AuthenticationAspect.java   
@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();
  }
}
项目:lams    文件:DelegatePerTargetObjectIntroductionInterceptor.java   
/**
 * 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
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);
}
项目:act-platform    文件:ValidationAspect.java   
private void validateMethodParameters(MethodInvocation invocation) throws InvalidArgumentException {
  boolean isInvalid = false;
  InvalidArgumentException ex = new InvalidArgumentException();

  for (int i = 0; i < invocation.getMethod().getParameterCount(); i++) {
    Parameter parameter = invocation.getMethod().getParameters()[i];
    // Only validate arguments which implement ValidatingRequest.
    if (ValidatingRequest.class.isAssignableFrom(parameter.getType())) {
      ValidatingRequest request = (ValidatingRequest) invocation.getArguments()[i];
      if (request == null) {
        // Don't allow null request objects.
        ex.addValidationError(InvalidArgumentException.ErrorMessage.NULL, parameter.getName(), "NULL");
        isInvalid = true;
      } else {
        isInvalid |= validateRequest(request, ex);
      }
    }
  }

  if (isInvalid) {
    // If violations exist abort invoked service call.
    throw ex;
  }
}
项目:alfresco-repository    文件:BeanIdentifierImpl.java   
/**
 * Do the look up by interface type.
 * 
 * @return              Returns the name of the service or <tt>null</tt> if not found
 */
private String getBeanNameImpl(MethodInvocation mi) throws BeansException
{
    if (mi instanceof ProxyMethodInvocation)
    {
        Object proxy = ((ProxyMethodInvocation) mi).getProxy();
        Map beans = beanFactory.getBeansOfType(proxy.getClass());
        Iterator iter = beans.entrySet().iterator();
        while (iter.hasNext())
        {
            Map.Entry entry = (Map.Entry) iter.next();
            String name = (String) entry.getKey();
            if (proxy == entry.getValue() && !name.equals("DescriptorService"))
            {
                return name;
            }
        }
    }
    return null;
}
项目:alfresco-repository    文件:FilenameFilteringInterceptor.java   
private Object runAsSystem(MethodInvocation invocation) throws Throwable
{
    Object ret = null;

    // We're creating in enhanced mode and have a matching filename or path. Switch to
    // the system user to do the operation.

    AuthenticationUtil.pushAuthentication();
    try
    {
        AuthenticationUtil.setRunAsUserSystem();
        ret = invocation.proceed();
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }

    return ret;
}
项目:alfresco-repository    文件:SubsystemProxyFactory.java   
/**
 * Instantiates a new managed subsystem proxy factory.
 */
public SubsystemProxyFactory()
{
    addAdvisor(new DefaultPointcutAdvisor(new MethodInterceptor()
    {
        public Object invoke(MethodInvocation mi) throws Throwable
        {
            Method method = mi.getMethod();
            try
            {
                return method.invoke(locateBean(mi), mi.getArguments());
            }
            catch (InvocationTargetException e)
            {
                // Unwrap invocation target exceptions
                throw e.getTargetException();
            }
        }
    }));
}
项目:alfresco-repository    文件:AlfrescoCmisStreamInterceptor.java   
public Object invoke(MethodInvocation mi) throws Throwable
{
    Class<?>[] parameterTypes = mi.getMethod().getParameterTypes();
    Object[] arguments = mi.getArguments();
    for (int i = 0; i < parameterTypes.length; i++)
    {
        if (arguments[i] instanceof ContentStreamImpl)
        {
            ContentStreamImpl contentStream = (ContentStreamImpl) arguments[i];
            if (contentStream != null)
            {
                // ALF-18006
                if (contentStream.getMimeType() == null)
                {
                    InputStream stream = contentStream.getStream();
                    String mimeType = mimetypeService.guessMimetype(contentStream.getFileName(), stream);
                    contentStream.setMimeType(mimeType);
                }
            }
        }
    }
    return mi.proceed();
}
项目:NoraUi    文件:ConditionedInterceptor.java   
/**
 * {@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));
                return Void.TYPE;
            }
        }
    }

    logger.debug("NORAUI ConditionedInterceptor invoke method {}", invocation.getMethod());
    return invocation.proceed();
}
项目:bdf2    文件:NoneLoginAjaxExceptionHandler.java   
public void handle(Throwable exception, MethodInvocation invocation) {
    HttpServletRequest request=DoradoContext.getCurrent().getRequest();
    String contextPath=request.getContextPath();
    StringBuffer sb=new StringBuffer();
    NoneLoginException ex=(NoneLoginException)exception;
    if(ex.isSessionKickAway()){
        sb.append("dorado.MessageBox.alert(\""+Configure.getString("bdf2.ajaxSessionKickAwayMessage")+"\",function(){\n");
        sb.append("window.open(\""+contextPath+Configure.getString("bdf2.formLoginUrl")+"\",\"_top\");\n");
        sb.append("})");            
    }else{
        sb.append("dorado.MessageBox.alert(\""+Configure.getString("bdf2.ajaxSessionExpireMessage")+"\",function(){\n");
        sb.append("window.open(\""+contextPath+Configure.getString("bdf2.formLoginUrl")+"\",\"_top\");\n");
        sb.append("})");            
    }
       throw new ClientRunnableException(sb.toString());
}
项目:esup-ecandidat    文件:UserController.java   
/**
 * @param viewClass
 * @return true si l'utilisateur peut accéder à la vue
 */
public boolean canCurrentUserAccessView(Class<? extends View> viewClass, Authentication auth) {
    if (auth == null) {
        return false;
    }
    MethodInvocation methodInvocation = MethodInvocationUtils.createFromClass(viewClass, "enter");
    Collection<ConfigAttribute> configAttributes = methodSecurityInterceptor.obtainSecurityMetadataSource()
            .getAttributes(methodInvocation);
    /* Renvoie true si la vue n'est pas sécurisée */
    if (configAttributes.isEmpty()) {
        return true;
    }
    /* Vérifie que l'utilisateur a les droits requis */
    try {
        methodSecurityInterceptor.getAccessDecisionManager().decide(auth, methodInvocation, configAttributes);
    } catch (InsufficientAuthenticationException | AccessDeniedException e) {
        return false;
    }
    return true;
}
项目:spring-cloud-sleuth-amqp    文件:AmqpMessagingBeforeReceiveInterceptor.java   
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
  final Message message = getMessageArgument(invocation.getArguments());
  if (message == null) {
    throw new IllegalStateException("Message cannot be null");
  }
  before(message);
  return invocation.proceed();
}
项目:lams    文件:PersistenceExceptionTranslationInterceptor.java   
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
    try {
        return mi.proceed();
    }
    catch (RuntimeException ex) {
        // Let it throw raw if the type of the exception is on the throws clause of the method.
        if (!this.alwaysTranslate && ReflectionUtils.declaresException(mi.getMethod(), ex.getClass())) {
            throw ex;
        }
        else {
            if (this.persistenceExceptionTranslator == null) {
                this.persistenceExceptionTranslator = detectPersistenceExceptionTranslators(this.beanFactory);
            }
            throw DataAccessUtils.translateIfNecessary(ex, this.persistenceExceptionTranslator);
        }
    }
}
项目:lams    文件:MBeanClientInterceptor.java   
/**
 * Refresh the connection and retry the MBean invocation if possible.
 * <p>If not configured to refresh on connect failure, this method
 * simply rethrows the original exception.
 * @param invocation the invocation that failed
 * @param ex the exception raised on remote invocation
 * @return the result value of the new invocation, if succeeded
 * @throws Throwable an exception raised by the new invocation,
 * if it failed as well
 * @see #setRefreshOnConnectFailure
 * @see #doInvoke
 */
protected Object handleConnectFailure(MethodInvocation invocation, Exception ex) throws Throwable {
    if (this.refreshOnConnectFailure) {
        String msg = "Could not connect to JMX server - retrying";
        if (logger.isDebugEnabled()) {
            logger.warn(msg, ex);
        }
        else if (logger.isWarnEnabled()) {
            logger.warn(msg);
        }
        prepare();
        return doInvoke(invocation);
    }
    else {
        throw ex;
    }
}
项目:gemini.blueprint    文件:OsgiServiceStaticInterceptorTest.java   
public void testInvocationWhenServiceNA() throws Throwable {
    // service n/a
    ServiceReference reference = new MockServiceReference() {
        public Bundle getBundle() {
            return null;
        }
    };

    interceptor = new ServiceStaticInterceptor(new MockBundleContext(), reference);

    Object target = new Object();
    Method m = target.getClass().getDeclaredMethod("hashCode", null);

    MethodInvocation invocation = new MockMethodInvocation(m);
    try {
        interceptor.invoke(invocation);
        fail("should have thrown exception");
    }
    catch (ServiceUnavailableException ex) {
        // expected
    }
}
项目:Equella    文件:MethodSecurityInteceptor.java   
@SuppressWarnings("unchecked")
private Object filterResult(MethodInvocation invocation, final SecurityAttribute secAttr) throws Throwable // NOSONAR
{
    Object returnedObject = invocation.proceed();
    if( returnedObject == null )
    {
        return null;
    }

    if( returnedObject instanceof Collection )
    {
        return filterCollection(secAttr, (Collection<Object>) returnedObject);
    }
    else if( returnedObject instanceof Map )
    {
        return filterMap(secAttr, (Map<Object, Object>) returnedObject);
    }
    else
    {
        checkSingleObject(secAttr.getFilterPrivileges(), returnedObject);
        return returnedObject;
    }
}
项目:lams    文件:MethodValidationInterceptor.java   
@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;
}
项目:dswork    文件:DataSourceSpyInterceptor.java   
public Object invoke(MethodInvocation invocation) throws Throwable
{
    Object result = invocation.proceed();
    if(SpyLogFactory.getSpyLogDelegator().isJdbcLoggingEnabled())
    {
        if(result instanceof Connection)
        {
            Connection conn = (Connection) result;
            return new ConnectionSpy(conn, getRdbmsSpecifics(conn));
        }
    }
    return result;
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:SecurityDialectPostProcessor.java   
@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;
}
项目:lams    文件:AspectJAfterThrowingAdvice.java   
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
    try {
        return mi.proceed();
    }
    catch (Throwable t) {
        if (shouldInvokeOnThrowing(t)) {
            invokeAdviceMethod(getJoinPointMatch(), null, t);
        }
        throw t;
    }
}
项目:unitimes    文件:UniTimeSecurityExpressionHandler.java   
@Override
protected MethodSecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication, MethodInvocation invocation) {
    MyMethodSecurityExpressionRoot root = new MyMethodSecurityExpressionRoot(authentication);
    root.setThis(invocation.getThis());
    root.setPermissionEvaluator(getPermissionEvaluator());

    return root;
}
项目:spring-security-oauth2-boot    文件:OAuth2SsoCustomConfiguration.java   
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    if (invocation.getMethod().getName().equals("init")) {
        Method method = ReflectionUtils
                .findMethod(WebSecurityConfigurerAdapter.class, "getHttp");
        ReflectionUtils.makeAccessible(method);
        HttpSecurity http = (HttpSecurity) ReflectionUtils.invokeMethod(method,
                invocation.getThis());
        this.configurer.configure(http);
    }
    return invocation.proceed();
}
项目:hiatus-spring-boot    文件:MethodUnitOfWorkInterceptor.java   
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    counter.increase();
    try {
        return invocation.proceed();
    } finally {
        counter.decrease();
    }
}
项目:lams    文件:JamonPerformanceMonitorInterceptor.java   
/**
 * Wraps the invocation with a JAMon Monitor and writes the current
 * performance statistics to the log (if enabled).
 * @see com.jamonapi.MonitorFactory#start
 * @see com.jamonapi.Monitor#stop
 */
@Override
protected Object invokeUnderTrace(MethodInvocation invocation, Log logger) throws Throwable {
    String name = createInvocationTraceName(invocation);
    Monitor monitor = MonitorFactory.start(name);
    try {
        return invocation.proceed();
    }
    finally {
        monitor.stop();
        if (!this.trackAllInvocations || isLogEnabled(logger)) {
            logger.trace("JAMon performance statistics for method [" + name + "]:\n" + monitor);
        }
    }
}
项目:spring-boot-mybatisplus-multiple-datasource    文件:DataSourceSwitchMethodInterceptor.java   
@Override
public Object invoke ( MethodInvocation invocation ) throws Throwable {
    final String packageName = invocation.getThis().getClass().getPackage().getName();
    if ( packageName.contains( "user" ) ) {
        setDataSourceKey( invocation.getMethod() , GlobalConstant.USER_DATA_SOURCE_KEY );
    }
    if ( packageName.contains( "order" ) ) {
        setDataSourceKey( invocation.getMethod() , GlobalConstant.ORDER_DATA_SOURCE_KEY );
    }
    return invocation.proceed();
}
项目:lams    文件:AspectJAroundAdvice.java   
@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;
    ProceedingJoinPoint pjp = lazyGetProceedingJoinPoint(pmi);
    JoinPointMatch jpm = getJoinPointMatch(pmi);
    return invokeAdviceMethod(pjp, jpm, null, null);
}
项目:lams    文件:AbstractAspectJAdvice.java   
/**
 * Lazily instantiate joinpoint for the current invocation.
 * Requires MethodInvocation to be bound with ExposeInvocationInterceptor.
 * <p>Do not use if access is available to the current ReflectiveMethodInvocation
 * (in an around advice).
 * @return current AspectJ joinpoint, or through an exception if we're not in a
 * Spring AOP invocation.
 */
public static JoinPoint currentJoinPoint() {
    MethodInvocation mi = ExposeInvocationInterceptor.currentInvocation();
    if (!(mi instanceof ProxyMethodInvocation)) {
        throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi);
    }
    ProxyMethodInvocation pmi = (ProxyMethodInvocation) mi;
    JoinPoint jp = (JoinPoint) pmi.getUserAttribute(JOIN_POINT_KEY);
    if (jp == null) {
        jp = new MethodInvocationProceedingJoinPoint(pmi);
        pmi.setUserAttribute(JOIN_POINT_KEY, jp);
    }
    return jp;
}
项目:beadledom    文件:JooqTxnInterceptor.java   
/**
 * Invokes the method wrapped within a unit of work and a transaction.
 *
 * @param methodInvocation the method to be invoked within a transaction
 * @return the result of the call to the invoked method
 * @throws Throwable if an exception occurs during the method invocation, transaction, or unit of
 *     work
 */
private Object invokeInTransactionAndUnitOfWork(MethodInvocation methodInvocation)
    throws Throwable {
  boolean unitOfWorkAlreadyStarted = unitOfWork.isActive();
  if (!unitOfWorkAlreadyStarted) {
    unitOfWork.begin();
  }

  Throwable originalThrowable = null;
  try {
    return dslContextProvider.get().transactionResult(() -> {
      try {
        return methodInvocation.proceed();
      } catch (Throwable e) {
        if (e instanceof RuntimeException) {
          throw (RuntimeException) e;
        }

        throw new RuntimeException(e);
      }
    });
  } catch (Throwable t) {
    originalThrowable = t;
    throw t;
  } finally {
    if (!unitOfWorkAlreadyStarted) {
      endUnitOfWork(originalThrowable);
    }
  }
}
项目:lams    文件:ExposeBeanNameAdvisors.java   
@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();
}
项目:lams    文件:AbstractAspectJAdvice.java   
/**
 * Get the current join point match at the join point we are being dispatched on.
 */
protected JoinPointMatch getJoinPointMatch() {
    MethodInvocation mi = ExposeInvocationInterceptor.currentInvocation();
    if (!(mi instanceof ProxyMethodInvocation)) {
        throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi);
    }
    return getJoinPointMatch((ProxyMethodInvocation) mi);
}
项目:spring-boot-data-source-decorator    文件:DataSourceDecoratorInterceptor.java   
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    if (invocation.getMethod().getName().equals("getConnection")) {
        if (invocation.getMethod().getParameterCount() == 0) {
            return decoratedDataSource.getConnection();
        }
        else if (invocation.getMethod().getParameterCount() == 2) {
            return decoratedDataSource.getConnection((String) invocation.getArguments()[0], (String) invocation.getArguments()[1]);
        }
    }
    if (invocation.getMethod().getName().equals("toString")) {
        return decoratingChain.stream()
                .map(entry -> entry.getBeanName() + " [" + entry.getDataSource().getClass().getName() + "]")
                .collect(Collectors.joining(" -> ")) + " -> " + beanName + " [" + realDataSource.getClass().getName() + "]";
    }
    if (invocation.getMethod().getDeclaringClass() == DecoratedDataSource.class) {
        if (invocation.getMethod().getName().equals("getRealDataSource")) {
            return realDataSource;
        }
        if (invocation.getMethod().getName().equals("getDecoratedDataSource")) {
            return decoratedDataSource;
        }
        if (invocation.getMethod().getName().equals("getDecoratingChain")) {
            return Collections.unmodifiableList(decoratingChain);
        }
    }
    return invocation.proceed();
}
项目:act-platform    文件:AbstractAspect.java   
/**
 * 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();
}
项目:java-spring-cloud    文件:ExecutorBeanPostProcessor.java   
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
  Executor tracedExecutor = tracedExecutor(tracer, delegate);
  Method methodOnTracedBean = getMethod(invocation, tracedExecutor);
  if (methodOnTracedBean != null) {
    return methodOnTracedBean.invoke(tracedExecutor, invocation.getArguments());
  }
  return invocation.proceed();
}
项目:lams    文件:PerformanceMonitorInterceptor.java   
@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();
        logger.trace(stopWatch.shortSummary());
    }
}
项目:lams    文件:ExposeInvocationInterceptor.java   
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
    MethodInvocation oldInvocation = invocation.get();
    invocation.set(mi);
    try {
        return mi.proceed();
    }
    finally {
        invocation.set(oldInvocation);
    }
}
项目:lams    文件:ExposeInvocationInterceptor.java   
/**
 * Return the AOP Alliance MethodInvocation object associated with the current invocation.
 * @return the invocation object associated with the current invocation
 * @throws IllegalStateException if there is no AOP invocation in progress,
 * or if the ExposeInvocationInterceptor was not added to this interceptor chain
 */
public static MethodInvocation currentInvocation() throws IllegalStateException {
    MethodInvocation mi = invocation.get();
    if (mi == null)
        throw new IllegalStateException(
                "No MethodInvocation found: Check that an AOP invocation is in progress, and that the " +
                "ExposeInvocationInterceptor is upfront in the interceptor chain. Specifically, note that " +
                "advices with order HIGHEST_PRECEDENCE will execute before ExposeInvocationInterceptor!");
    return mi;
}
项目:alfresco-repository    文件:AuditMethodInterceptor.java   
/**
 * Allow the given method invocation to proceed, auditing values before invocation and
 * after returning or throwing.
 * 
 * @param mi                the invocation
 * @return                  Returns the method return (if a value is not thrown)
 * @throws Throwable        rethrows any exception generated by the invocation
 * 
 * @since 3.2
 */
private Object proceed(MethodInvocation mi) throws Throwable
{
    // Are we in a nested audit?
    Boolean wasInAudit = inAudit.get();
    try
    {
        // If we are already in a nested audit call, there is nothing to do
        if (Boolean.TRUE.equals(wasInAudit))
        {
            return mi.proceed();
        }

        Auditable auditableDef = mi.getMethod().getAnnotation(Auditable.class);
        if (auditableDef == null)
        {
            // No annotation, so just continue as normal
            return mi.proceed();
        }

        // First get the argument map, if present
        Object[] args = mi.getArguments();
        Map<String, Serializable> namedArguments = getInvocationArguments(auditableDef, args);
        // Get the service name
        String serviceName = beanIdentifier.getBeanName(mi);
        if (serviceName == null)
        {
            // Not a public service
            return mi.proceed();
        }
        String methodName = mi.getMethod().getName();

        return proceedWithAudit(mi, auditableDef, serviceName, methodName, namedArguments);
    }
    finally
    {
        inAudit.set(wasInAudit);                       
    }
}
项目:otter-G    文件:LogInterceptor.java   
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    long startTime = System.currentTimeMillis();
    Object result = null;
    try {
        result = methodInvocation.proceed();
    } catch (Exception e) {
        dump(methodInvocation, e, System.currentTimeMillis() - startTime);// 记录异常信息
        throw e;
    }
    // 记录异常信息
    dump(methodInvocation, result, System.currentTimeMillis() - startTime); // 记录正常结果信息
    return result;
}
项目:alfresco-repository    文件:RunAsTenantInterceptor.java   
@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());
    }
}